blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
140
path
stringlengths
5
183
src_encoding
stringclasses
6 values
length_bytes
int64
12
5.32M
score
float64
2.52
4.94
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
12
5.32M
download_success
bool
1 class
f8e0ff2e35c17c117eee7bdafd8745142247d6bd
Rust
jgust/advent-of-code-2018
/day2/src/bin/d2p2.rs
UTF-8
1,267
3.5
4
[ "MIT" ]
permissive
use day2::{hamming_distance, INPUT}; use std::collections::HashSet; fn main() { let words: Vec<&str> = INPUT.lines().map(|line| line.trim()).collect(); let mut candidates = HashSet::new(); for w1 in &words { let found: HashSet<&str> = words .iter() .filter(|w2| hamming_distance(w1, w2) == Ok(1)) .map(|&w| w) .collect(); candidates.extend(found); } if candidates.len() > 1 { // Here we rely on the assumption that all words found with a hamming distance of 1 // in the step above belong to the same series. Thus all are differing on the same letter. // Therefore it is enough to just compare the first two entries in the set. let mut cand_iter = candidates.iter(); let first = cand_iter.next().unwrap(); let second = cand_iter.next().unwrap(); let common: String = first .chars() .zip(second.chars()) .filter(|(c1, c2)| c1 == c2) .map(|(c1, _)| c1) .collect(); println!( "Found {} candidates. Common letters are: {}", candidates.len(), common ); } else { println!("No candidates found!"); } }
true
e1ea72419d1c006a54ce2ed17707e35cc2ec3f75
Rust
tokio-rs/tokio
/tokio/src/runtime/runtime.rs
UTF-8
17,214
3.296875
3
[ "MIT" ]
permissive
use crate::runtime::blocking::BlockingPool; use crate::runtime::scheduler::CurrentThread; use crate::runtime::{context, EnterGuard, Handle}; use crate::task::JoinHandle; use std::future::Future; use std::time::Duration; cfg_rt_multi_thread! { use crate::runtime::Builder; use crate::runtime::scheduler::MultiThread; cfg_unstable! { use crate::runtime::scheduler::MultiThreadAlt; } } /// The Tokio runtime. /// /// The runtime provides an I/O driver, task scheduler, [timer], and /// blocking pool, necessary for running asynchronous tasks. /// /// Instances of `Runtime` can be created using [`new`], or [`Builder`]. /// However, most users will use the `#[tokio::main]` annotation on their /// entry point instead. /// /// See [module level][mod] documentation for more details. /// /// # Shutdown /// /// Shutting down the runtime is done by dropping the value, or calling /// [`shutdown_background`] or [`shutdown_timeout`]. /// /// Tasks spawned through [`Runtime::spawn`] keep running until they yield. /// Then they are dropped. They are not *guaranteed* to run to completion, but /// *might* do so if they do not yield until completion. /// /// Blocking functions spawned through [`Runtime::spawn_blocking`] keep running /// until they return. /// /// The thread initiating the shutdown blocks until all spawned work has been /// stopped. This can take an indefinite amount of time. The `Drop` /// implementation waits forever for this. /// /// The [`shutdown_background`] and [`shutdown_timeout`] methods can be used if /// waiting forever is undesired. When the timeout is reached, spawned work that /// did not stop in time and threads running it are leaked. The work continues /// to run until one of the stopping conditions is fulfilled, but the thread /// initiating the shutdown is unblocked. /// /// Once the runtime has been dropped, any outstanding I/O resources bound to /// it will no longer function. Calling any method on them will result in an /// error. /// /// # Sharing /// /// There are several ways to establish shared access to a Tokio runtime: /// /// * Using an <code>[Arc]\<Runtime></code>. /// * Using a [`Handle`]. /// * Entering the runtime context. /// /// Using an <code>[Arc]\<Runtime></code> or [`Handle`] allows you to do various /// things with the runtime such as spawning new tasks or entering the runtime /// context. Both types can be cloned to create a new handle that allows access /// to the same runtime. By passing clones into different tasks or threads, you /// will be able to access the runtime from those tasks or threads. /// /// The difference between <code>[Arc]\<Runtime></code> and [`Handle`] is that /// an <code>[Arc]\<Runtime></code> will prevent the runtime from shutting down, /// whereas a [`Handle`] does not prevent that. This is because shutdown of the /// runtime happens when the destructor of the `Runtime` object runs. /// /// Calls to [`shutdown_background`] and [`shutdown_timeout`] require exclusive /// ownership of the `Runtime` type. When using an <code>[Arc]\<Runtime></code>, /// this can be achieved via [`Arc::try_unwrap`] when only one strong count /// reference is left over. /// /// The runtime context is entered using the [`Runtime::enter`] or /// [`Handle::enter`] methods, which use a thread-local variable to store the /// current runtime. Whenever you are inside the runtime context, methods such /// as [`tokio::spawn`] will use the runtime whose context you are inside. /// /// [timer]: crate::time /// [mod]: index.html /// [`new`]: method@Self::new /// [`Builder`]: struct@Builder /// [`Handle`]: struct@Handle /// [`tokio::spawn`]: crate::spawn /// [`Arc::try_unwrap`]: std::sync::Arc::try_unwrap /// [Arc]: std::sync::Arc /// [`shutdown_background`]: method@Runtime::shutdown_background /// [`shutdown_timeout`]: method@Runtime::shutdown_timeout #[derive(Debug)] pub struct Runtime { /// Task scheduler scheduler: Scheduler, /// Handle to runtime, also contains driver handles handle: Handle, /// Blocking pool handle, used to signal shutdown blocking_pool: BlockingPool, } /// The flavor of a `Runtime`. /// /// This is the return type for [`Handle::runtime_flavor`](crate::runtime::Handle::runtime_flavor()). #[derive(Debug, PartialEq, Eq)] #[non_exhaustive] pub enum RuntimeFlavor { /// The flavor that executes all tasks on the current thread. CurrentThread, /// The flavor that executes tasks across multiple threads. MultiThread, /// The flavor that executes tasks across multiple threads. #[cfg(tokio_unstable)] MultiThreadAlt, } /// The runtime scheduler is either a multi-thread or a current-thread executor. #[derive(Debug)] pub(super) enum Scheduler { /// Execute all tasks on the current-thread. CurrentThread(CurrentThread), /// Execute tasks across multiple threads. #[cfg(all(feature = "rt-multi-thread", not(target_os = "wasi")))] MultiThread(MultiThread), /// Execute tasks across multiple threads. #[cfg(all(tokio_unstable, feature = "rt-multi-thread", not(target_os = "wasi")))] MultiThreadAlt(MultiThreadAlt), } impl Runtime { pub(super) fn from_parts( scheduler: Scheduler, handle: Handle, blocking_pool: BlockingPool, ) -> Runtime { Runtime { scheduler, handle, blocking_pool, } } cfg_not_wasi! { /// Creates a new runtime instance with default configuration values. /// /// This results in the multi threaded scheduler, I/O driver, and time driver being /// initialized. /// /// Most applications will not need to call this function directly. Instead, /// they will use the [`#[tokio::main]` attribute][main]. When a more complex /// configuration is necessary, the [runtime builder] may be used. /// /// See [module level][mod] documentation for more details. /// /// # Examples /// /// Creating a new `Runtime` with default configuration values. /// /// ``` /// use tokio::runtime::Runtime; /// /// let rt = Runtime::new() /// .unwrap(); /// /// // Use the runtime... /// ``` /// /// [mod]: index.html /// [main]: ../attr.main.html /// [threaded scheduler]: index.html#threaded-scheduler /// [runtime builder]: crate::runtime::Builder #[cfg(feature = "rt-multi-thread")] #[cfg_attr(docsrs, doc(cfg(feature = "rt-multi-thread")))] pub fn new() -> std::io::Result<Runtime> { Builder::new_multi_thread().enable_all().build() } } /// Returns a handle to the runtime's spawner. /// /// The returned handle can be used to spawn tasks that run on this runtime, and can /// be cloned to allow moving the `Handle` to other threads. /// /// Calling [`Handle::block_on`] on a handle to a `current_thread` runtime is error-prone. /// Refer to the documentation of [`Handle::block_on`] for more. /// /// # Examples /// /// ``` /// use tokio::runtime::Runtime; /// /// let rt = Runtime::new() /// .unwrap(); /// /// let handle = rt.handle(); /// /// // Use the handle... /// ``` pub fn handle(&self) -> &Handle { &self.handle } /// Spawns a future onto the Tokio runtime. /// /// This spawns the given future onto the runtime's executor, usually a /// thread pool. The thread pool is then responsible for polling the future /// until it completes. /// /// The provided future will start running in the background immediately /// when `spawn` is called, even if you don't await the returned /// `JoinHandle`. /// /// See [module level][mod] documentation for more details. /// /// [mod]: index.html /// /// # Examples /// /// ``` /// use tokio::runtime::Runtime; /// /// # fn dox() { /// // Create the runtime /// let rt = Runtime::new().unwrap(); /// /// // Spawn a future onto the runtime /// rt.spawn(async { /// println!("now running on a worker thread"); /// }); /// # } /// ``` #[track_caller] pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output> where F: Future + Send + 'static, F::Output: Send + 'static, { self.handle.spawn(future) } /// Runs the provided function on an executor dedicated to blocking operations. /// /// # Examples /// /// ``` /// use tokio::runtime::Runtime; /// /// # fn dox() { /// // Create the runtime /// let rt = Runtime::new().unwrap(); /// /// // Spawn a blocking function onto the runtime /// rt.spawn_blocking(|| { /// println!("now running on a worker thread"); /// }); /// # } /// ``` #[track_caller] pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R> where F: FnOnce() -> R + Send + 'static, R: Send + 'static, { self.handle.spawn_blocking(func) } /// Runs a future to completion on the Tokio runtime. This is the /// runtime's entry point. /// /// This runs the given future on the current thread, blocking until it is /// complete, and yielding its resolved result. Any tasks or timers /// which the future spawns internally will be executed on the runtime. /// /// # Non-worker future /// /// Note that the future required by this function does not run as a /// worker. The expectation is that other tasks are spawned by the future here. /// Awaiting on other futures from the future provided here will not /// perform as fast as those spawned as workers. /// /// # Multi thread scheduler /// /// When the multi thread scheduler is used this will allow futures /// to run within the io driver and timer context of the overall runtime. /// /// Any spawned tasks will continue running after `block_on` returns. /// /// # Current thread scheduler /// /// When the current thread scheduler is enabled `block_on` /// can be called concurrently from multiple threads. The first call /// will take ownership of the io and timer drivers. This means /// other threads which do not own the drivers will hook into that one. /// When the first `block_on` completes, other threads will be able to /// "steal" the driver to allow continued execution of their futures. /// /// Any spawned tasks will be suspended after `block_on` returns. Calling /// `block_on` again will resume previously spawned tasks. /// /// # Panics /// /// This function panics if the provided future panics, or if called within an /// asynchronous execution context. /// /// # Examples /// /// ```no_run /// use tokio::runtime::Runtime; /// /// // Create the runtime /// let rt = Runtime::new().unwrap(); /// /// // Execute the future, blocking the current thread until completion /// rt.block_on(async { /// println!("hello"); /// }); /// ``` /// /// [handle]: fn@Handle::block_on #[track_caller] pub fn block_on<F: Future>(&self, future: F) -> F::Output { #[cfg(all( tokio_unstable, tokio_taskdump, feature = "rt", target_os = "linux", any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64") ))] let future = super::task::trace::Trace::root(future); #[cfg(all(tokio_unstable, feature = "tracing"))] let future = crate::util::trace::task( future, "block_on", None, crate::runtime::task::Id::next().as_u64(), ); let _enter = self.enter(); match &self.scheduler { Scheduler::CurrentThread(exec) => exec.block_on(&self.handle.inner, future), #[cfg(all(feature = "rt-multi-thread", not(target_os = "wasi")))] Scheduler::MultiThread(exec) => exec.block_on(&self.handle.inner, future), #[cfg(all(tokio_unstable, feature = "rt-multi-thread", not(target_os = "wasi")))] Scheduler::MultiThreadAlt(exec) => exec.block_on(&self.handle.inner, future), } } /// Enters the runtime context. /// /// This allows you to construct types that must have an executor /// available on creation such as [`Sleep`] or [`TcpStream`]. It will /// also allow you to call methods such as [`tokio::spawn`]. /// /// [`Sleep`]: struct@crate::time::Sleep /// [`TcpStream`]: struct@crate::net::TcpStream /// [`tokio::spawn`]: fn@crate::spawn /// /// # Example /// /// ``` /// use tokio::runtime::Runtime; /// /// fn function_that_spawns(msg: String) { /// // Had we not used `rt.enter` below, this would panic. /// tokio::spawn(async move { /// println!("{}", msg); /// }); /// } /// /// fn main() { /// let rt = Runtime::new().unwrap(); /// /// let s = "Hello World!".to_string(); /// /// // By entering the context, we tie `tokio::spawn` to this executor. /// let _guard = rt.enter(); /// function_that_spawns(s); /// } /// ``` pub fn enter(&self) -> EnterGuard<'_> { self.handle.enter() } /// Shuts down the runtime, waiting for at most `duration` for all spawned /// work to stop. /// /// See the [struct level documentation](Runtime#shutdown) for more details. /// /// # Examples /// /// ``` /// use tokio::runtime::Runtime; /// use tokio::task; /// /// use std::thread; /// use std::time::Duration; /// /// fn main() { /// let runtime = Runtime::new().unwrap(); /// /// runtime.block_on(async move { /// task::spawn_blocking(move || { /// thread::sleep(Duration::from_secs(10_000)); /// }); /// }); /// /// runtime.shutdown_timeout(Duration::from_millis(100)); /// } /// ``` pub fn shutdown_timeout(mut self, duration: Duration) { // Wakeup and shutdown all the worker threads self.handle.inner.shutdown(); self.blocking_pool.shutdown(Some(duration)); } /// Shuts down the runtime, without waiting for any spawned work to stop. /// /// This can be useful if you want to drop a runtime from within another runtime. /// Normally, dropping a runtime will block indefinitely for spawned blocking tasks /// to complete, which would normally not be permitted within an asynchronous context. /// By calling `shutdown_background()`, you can drop the runtime from such a context. /// /// Note however, that because we do not wait for any blocking tasks to complete, this /// may result in a resource leak (in that any blocking tasks are still running until they /// return. /// /// See the [struct level documentation](Runtime#shutdown) for more details. /// /// This function is equivalent to calling `shutdown_timeout(Duration::from_nanos(0))`. /// /// ``` /// use tokio::runtime::Runtime; /// /// fn main() { /// let runtime = Runtime::new().unwrap(); /// /// runtime.block_on(async move { /// let inner_runtime = Runtime::new().unwrap(); /// // ... /// inner_runtime.shutdown_background(); /// }); /// } /// ``` pub fn shutdown_background(self) { self.shutdown_timeout(Duration::from_nanos(0)) } } #[allow(clippy::single_match)] // there are comments in the error branch, so we don't want if-let impl Drop for Runtime { fn drop(&mut self) { match &mut self.scheduler { Scheduler::CurrentThread(current_thread) => { // This ensures that tasks spawned on the current-thread // runtime are dropped inside the runtime's context. let _guard = context::try_set_current(&self.handle.inner); current_thread.shutdown(&self.handle.inner); } #[cfg(all(feature = "rt-multi-thread", not(target_os = "wasi")))] Scheduler::MultiThread(multi_thread) => { // The threaded scheduler drops its tasks on its worker threads, which is // already in the runtime's context. multi_thread.shutdown(&self.handle.inner); } #[cfg(all(tokio_unstable, feature = "rt-multi-thread", not(target_os = "wasi")))] Scheduler::MultiThreadAlt(multi_thread) => { // The threaded scheduler drops its tasks on its worker threads, which is // already in the runtime's context. multi_thread.shutdown(&self.handle.inner); } } } } cfg_metrics! { impl Runtime { /// TODO pub fn metrics(&self) -> crate::runtime::RuntimeMetrics { self.handle.metrics() } } }
true
400263a4c9dfeb4178156627b713a2a9054baff4
Rust
iCodeIN/colo
/src/color/parse.rs
UTF-8
9,676
3.046875
3
[ "MIT" ]
permissive
use anyhow::anyhow; use std::{cmp::Ordering, num::ParseFloatError}; use thiserror::Error; use super::{hex, html, Color, ColorFormat, ColorSpace}; use crate::{ terminal::{stdin, ColorPicker}, State, }; use ParseError::*; /// Error caused by parsing a number in a certain color space. /// /// This error can occur if the wrong number of color components /// was supplied (e.g. `rgb` with only 2 components), or if a /// color component is out of range (for example, `rgb` requires /// that all components are in 0..=255). #[derive(Debug, Error)] #[non_exhaustive] pub enum ParseError { #[error("Wrong number of color components (expected {expected}, got {got})")] NumberOfComponents { expected: usize, got: usize }, #[error("Color component {component:?} can't be negative (got {got})")] Negative { component: &'static str, got: f64 }, #[error("Color component {component:?} out of range (expected {min} to {max}, got {got})")] OutOfRange { component: &'static str, min: f64, max: f64, got: f64, }, #[error("{string:?} could not be parsed as a number. Reason: {cause}")] InvalidFloat { string: String, cause: ParseFloatError, }, #[error("Expected a number, got {got:?}")] MissingFloat { got: String }, #[error("Unclosed {open:?} paren, expected {expected:?} at {string:?}")] UnclosedParen { open: char, expected: char, string: String, }, #[error("Expected hex color or HTML color, got {string:?}")] ExpectedWord { string: String }, #[error(transparent)] ParseHexError(#[from] hex::ParseHexError), #[error("Unknown color {got:?}, did you mean {suggestion:?}?")] Misspelled { got: String, suggestion: String }, #[error("This value in the {cs:?} color space can't be randomly generated")] UnsupportedRand { cs: ColorSpace }, #[error(transparent)] Other(#[from] anyhow::Error), } /// Parses a string that can contain an arbitrary number of colors in different /// formats pub fn parse(mut input: &str, state: State) -> Result<Vec<(Color, ColorFormat)>, ParseError> { let mut output = Vec::new(); loop { let input_i = input.trim_start(); if input_i.is_empty() { return Ok(output); } let (cs, input_i) = parse_color_space(input_i); let input_i = input_i.trim_start(); let (open_paren, input_i) = open_paren(input_i); let mut input_i = input_i.trim_start(); if let Some(cs) = cs { let expected = cs.num_components(); let mut nums = [0.0, 0.0, 0.0, 0.0]; for (i, num) in nums.iter_mut().enumerate().take(expected) { input_i = input_i.trim_start(); input_i = skip(input_i, ','); input_i = input_i.trim_start(); let (n, input_ii) = parse_number(input_i)? .map(Ok) .or_else(|| parse_rand_component(input_i, cs, i).transpose()) .transpose()? .ok_or_else(|| MissingFloat { got: input_i.into(), })?; *num = n; input_i = input_ii.trim_start(); } let nums = &nums[0..expected]; let color: Color = Color::new(cs, nums).map_err(|err| err)?; output.push((color, ColorFormat::Normal(cs))); input_i = input_i.trim_start(); } else if input_i.starts_with("- ") || input_i.starts_with("-,") { input_i = input_i[2..].trim_start(); let new_values = stdin::read_line(state)?; let colors = parse(&new_values, state)?; if colors.len() != 1 { return Err(anyhow!("Expected 1 color, got {}", colors.len()).into()); } output.push(colors[0]); } else { let (word, input_ii) = take_word(input_i).ok_or_else(|| ParseError::ExpectedWord { string: input_i.into(), })?; let color = if word == "pick" { let color = ColorPicker::new(None, None).display(state)?; (color, color.get_color_format()) } else if word == "rand" { (Color::random_rgb(), ColorFormat::Hex) } else if let Some(color) = html::get(word) { (Color::Rgb(color), ColorFormat::Html) } else { match hex::parse(word) { Ok(hex) => (Color::Rgb(hex), ColorFormat::Hex), Err(err) => { if word.chars().all(|c| c.is_ascii_alphabetic()) && word.len() > 3 { let mut similar = html::get_similar(word); if !similar.is_empty() { similar.sort_by(|&(_, l), &(_, r)| { if l < r { Ordering::Less } else if l > r { Ordering::Greater } else { Ordering::Equal } }); let (suggestion, _) = similar[similar.len() - 1]; return Err(ParseError::Misspelled { got: word.to_string(), suggestion: suggestion.to_string(), }); } } return Err(err.into()); } } }; output.push(color); let input_ii = input_ii.trim_start(); input_i = input_ii; } if let Some(open) = open_paren { input_i = close_paren(input_i, open)?; } input_i = skip(input_i, ','); input = input_i; } } fn parse_color_space(input: &str) -> (Option<ColorSpace>, &str) { if let Some((word, rest)) = take_word(input) { if let Ok(cs) = word.parse::<ColorSpace>() { return (Some(cs), rest); } } (None, input) } fn open_paren(input: &str) -> (Option<char>, &str) { let mut chars = input.chars(); match chars.next() { Some(c) if c == '(' || c == '[' || c == '{' => (Some(c), chars.as_str()), _ => (None, input), } } fn close_paren(input: &str, open: char) -> Result<&str, ParseError> { let expected = closing_for(open); let mut chars = input.chars(); match chars.next() { Some(c) if c == expected => Ok(chars.as_str()), _ => Err(ParseError::UnclosedParen { open, expected, string: input.into(), }), } } fn closing_for(c: char) -> char { match c { '<' => '>', '(' => ')', '[' => ']', '{' => '}', c => c, } } fn parse_number(input: &str) -> Result<Option<(f64, &str)>, ParseError> { let (num, rest) = take_until(input, |c| !matches!(c, '0'..='9' | '.' | '_' | '-')); if num.is_empty() { return Ok(None); } let mut num = num.parse().map_err(|cause| InvalidFloat { string: num.into(), cause, })?; let mut rest = rest.trim_start(); if rest.starts_with('%') { rest = &rest[1..]; num /= 100.0; } Ok(Some((num, rest))) } fn parse_rand_component( input: &str, cs: ColorSpace, i: usize, ) -> Result<Option<(f64, &str)>, ParseError> { if let Some((word, rest)) = take_word(input) { if word == "rand" { return Ok(Some(( match cs { ColorSpace::Rgb => fastrand::u8(..) as f64, ColorSpace::Cmy => fastrand::f64(), ColorSpace::Cmyk => fastrand::f64(), ColorSpace::Hsv | ColorSpace::Hsl => match i { 0 => fastrand::u32(0..360) as f64, _ => fastrand::f64(), }, ColorSpace::Lch => match i { 0 | 1 => fastrand::u32(0..=100) as f64, _ => fastrand::u32(0..360) as f64, }, ColorSpace::Luv => match i { 0 | 1 => fastrand::u32(0..=100) as f64, _ => fastrand::u32(0..=360) as f64, }, ColorSpace::Lab if i == 0 => fastrand::u32(0..=100) as f64, ColorSpace::HunterLab if i == 0 => fastrand::u32(0..=100) as f64, ColorSpace::Xyz if i == 1 => fastrand::u32(0..=100) as f64, ColorSpace::Yxy if i == 0 => fastrand::u32(0..=100) as f64, ColorSpace::Gray => fastrand::f64(), _ => return Err(ParseError::UnsupportedRand { cs }), }, rest, ))); } } Ok(None) } fn take_word(input: &str) -> Option<(&str, &str)> { let res = take_until(input, |c| { !(c.is_ascii_alphanumeric() || c == '_' || c == '#') }); Some(res).filter(|(word, _)| !word.is_empty()) } fn take_until(input: &str, f: impl FnMut(char) -> bool) -> (&str, &str) { let next = input.split(f).next().unwrap_or(""); let rest = &input[next.len()..]; (next, rest) } fn skip(input: &str, c: char) -> &str { let mut chars = input.chars(); match chars.next() { Some(char) if char == c => chars.as_str(), _ => input, } }
true
d4f5d03312f890fb54c9090f1c93b331cb91d2b5
Rust
clucompany/cluConcatBytes
/examples/raw.rs
UTF-8
713
3
3
[ "Apache-2.0" ]
permissive
#![feature(plugin)] #![plugin(cluConcatBytes)] fn main() { let c_str = concat_bytes!(@"cluWorld"); //[u8; 8] //array: [99, 108, 117, 87, 111, 114, 108, 100], len: 8 assert_eq!(&c_str, b"cluWorld"); let c_str2 = concat_bytes!(@"cluWorld"); //[u8; 8] //array: [99, 108, 117, 87, 111, 114, 108, 100], len: 8 assert_eq!(&c_str2, b"cluWorld"); let c_str3 = concat_bytes!(@"clu", b"World"); //[u8; 8] //array: [99, 108, 117, 87, 111, 114, 108, 100], len: 8 assert_eq!(&c_str3, b"cluWorld"); my_function(c_str); my_function(c_str2); my_function(c_str3); } fn my_function(array: [u8; 8]) { //'static --> it is possible not to write. println!("array: {:?}, len: {}", array, array.len()); }
true
f7f4df005c6eb469faffb9787cd652b98067e0c9
Rust
snow2flying/drogue-tls
/src/tls_connection.rs
UTF-8
7,882
2.8125
3
[ "Apache-2.0" ]
permissive
use crate::alert::*; use crate::connection::*; use crate::handshake::ServerHandshake; use crate::key_schedule::KeySchedule; use crate::record::{ClientRecord, ServerRecord}; use crate::{ traits::{AsyncRead, AsyncWrite}, TlsError, }; use rand_core::{CryptoRng, RngCore}; use crate::application_data::ApplicationData; use heapless::spsc::Queue; pub use crate::config::*; // Some space needed by TLS record const TLS_RECORD_OVERHEAD: usize = 128; /// Type representing an async TLS connection. An instance of this type can /// be used to establish a TLS connection, write and read encrypted data over this connection, /// and closing to free up the underlying resources. pub struct TlsConnection<'a, RNG, Socket, CipherSuite> where RNG: CryptoRng + RngCore + 'static, Socket: AsyncRead + AsyncWrite + 'a, CipherSuite: TlsCipherSuite + 'static, { delegate: Socket, rng: RNG, config: TlsConfig<'a, CipherSuite>, key_schedule: KeySchedule<CipherSuite::Hash, CipherSuite::KeyLen, CipherSuite::IvLen>, record_buf: &'a mut [u8], opened: bool, } impl<'a, RNG, Socket, CipherSuite> TlsConnection<'a, RNG, Socket, CipherSuite> where RNG: CryptoRng + RngCore + 'static, Socket: AsyncRead + AsyncWrite + 'a, CipherSuite: TlsCipherSuite + 'static, { /// Create a new TLS connection with the provided context and a async I/O implementation pub fn new(context: TlsContext<'a, CipherSuite, RNG>, delegate: Socket) -> Self { Self { delegate, config: context.config, rng: context.rng, opened: false, key_schedule: KeySchedule::new(), record_buf: context.record_buf, } } /// Open a TLS connection, performing the handshake with the configuration provided when creating /// the connection instance. /// /// Returns an error if the handshake does not proceed. If an error occurs, the connection instance /// must be recreated. pub async fn open<'m>(&mut self) -> Result<(), TlsError> where 'a: 'm, { let mut handshake: Handshake<CipherSuite> = Handshake::new(); let mut state = State::ClientHello; loop { let next_state = state .process( &mut self.delegate, &mut handshake, &mut self.record_buf, &mut self.key_schedule, &self.config, &mut self.rng, ) .await?; trace!("State {:?} -> {:?}", state, next_state); state = next_state; if let State::ApplicationData = state { self.opened = true; break; } } Ok(()) } /// Encrypt and send the provided slice over the connection. The connection /// must be opened before writing. /// /// Returns the number of bytes written. pub async fn write(&mut self, buf: &[u8]) -> Result<usize, TlsError> { if self.opened { let mut wp = 0; let mut remaining = buf.len(); let max_block_size = self.record_buf.len() - TLS_RECORD_OVERHEAD; while remaining > 0 { let delegate = &mut self.delegate; let key_schedule = &mut self.key_schedule; let to_write = core::cmp::min(remaining, max_block_size); let record: ClientRecord<'a, '_, CipherSuite> = ClientRecord::ApplicationData(&buf[wp..to_write]); let (_, len) = encode_record(&mut self.record_buf, key_schedule, &record)?; delegate.write(&self.record_buf[..len]).await?; key_schedule.increment_write_counter(); wp += to_write; remaining -= to_write; } Ok(buf.len()) } else { Err(TlsError::MissingHandshake) } } /// Read and decrypt data filling the provided slice. The slice must be able to /// keep the expected amount of data that can be received in one record to avoid /// loosing data. pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, TlsError> { if self.opened { let mut remaining = buf.len(); // Note: Read only a single ApplicationData record for now, as we don't do any buffering. while remaining == buf.len() { let socket = &mut self.delegate; let key_schedule = &mut self.key_schedule; let record = decode_record::<Socket, CipherSuite>( socket, &mut self.record_buf, key_schedule, ) .await?; let mut records = Queue::new(); decrypt_record::<CipherSuite>(key_schedule, &mut records, record)?; while let Some(record) = records.dequeue() { match record { ServerRecord::ApplicationData(ApplicationData { header: _, data }) => { trace!("Got application data record"); if buf.len() < data.len() { warn!("Passed buffer is too small"); Err(TlsError::EncodeError) } else { let to_copy = core::cmp::min(data.len(), buf.len()); // TODO Need to buffer data not consumed trace!("Got {} bytes to copy", to_copy); buf[..to_copy].copy_from_slice(&data.as_slice()[..to_copy]); remaining -= to_copy; Ok(()) } } ServerRecord::Alert(alert) => { if let AlertDescription::CloseNotify = alert.description { Err(TlsError::ConnectionClosed) } else { Err(TlsError::InternalError) } } ServerRecord::ChangeCipherSpec(_) => Err(TlsError::InternalError), ServerRecord::Handshake(ServerHandshake::NewSessionTicket(_)) => { // Ignore Ok(()) } _ => { unimplemented!() } }?; } } Ok(buf.len() - remaining) } else { Err(TlsError::MissingHandshake) } } /// Close a connection instance, returning the ownership of the config, random generator and the async I/O provider. pub async fn close(self) -> Result<(TlsContext<'a, CipherSuite, RNG>, Socket), TlsError> { let record = if self.opened { ClientRecord::Alert( Alert::new(AlertLevel::Warning, AlertDescription::CloseNotify), true, ) } else { ClientRecord::Alert( Alert::new(AlertLevel::Warning, AlertDescription::CloseNotify), false, ) }; let mut key_schedule = self.key_schedule; let mut delegate = self.delegate; let mut record_buf = self.record_buf; let rng = self.rng; let config = self.config; let (_, len) = encode_record::<CipherSuite>(&mut record_buf, &mut key_schedule, &record)?; delegate.write(&record_buf[..len]).await?; key_schedule.increment_write_counter(); Ok(( TlsContext::new_with_config(rng, record_buf, config), delegate, )) } }
true
6d17d6e6786d96e1081ce2bce52e254c1907c14b
Rust
herou/Rust-Crash-Course
/src/var.rs
UTF-8
415
3.859375
4
[ "Apache-2.0" ]
permissive
pub fn run(){ let name = "Elio"; let mut age = 37; println!("My name is {} and I am {}", name, age); age = 38; println!("My name is {} and I am {}", name, age); // Define constant const ID: i32 = 1; println!("ID: {}", ID); // Assign multiple vars let (name, last_name, age) = ("Elio", "Prifti", 38); println!("Name: {}, Last Name: {}, Age: {}", name,last_name,age); }
true
cb87e2f8261315c38964d8822acc8a4fab3d6c93
Rust
clap-rs/clap
/tests/derive_ui/clap_empty_attr.rs
UTF-8
214
2.625
3
[ "Apache-2.0", "MIT" ]
permissive
use clap::Parser; #[derive(Parser, Debug)] #[command] struct Opt {} #[derive(Parser, Debug)] struct Opt1 { #[arg = "short"] foo: u32, } fn main() { let opt = Opt::parse(); println!("{opt:?}"); }
true
7e28dfa405282f839c5f183f2b24e51d9d482dea
Rust
wbprice/perfect-good-bad-guessing-game
/src/main.rs
UTF-8
4,788
3.40625
3
[ "MIT" ]
permissive
use structopt::StructOpt; use read_input::prelude::*; use rand::Rng; #[derive(Debug, StructOpt)] struct Cli { #[structopt(short = "d", long = "digit", default_value="3")] /// Sets the number of digits used for the secret number digit: i8, #[structopt(long = "debug")] /// Turns on debug logging debug: bool, #[structopt(short = "a", long="auto")] /// Asks the CPU to play itself auto: bool } struct GuessRatings { guess: i64, perfect: i8, good: i8, bad: i8 } fn main() { let args = Cli::from_args(); if args.digit <= 0 { eprintln!("The value passed to the digit argument must be greater than zero."); std::process::exit(1); } let secret_number_min : i64 = i64::pow(10, args.digit as u32 - 1); let secret_number_max : i64 = i64::pow(10, args.digit as u32) - 1; let secret_number = rand::thread_rng() .gen_range(secret_number_min, secret_number_max); let mut guesses : Vec<GuessRatings> = Vec::new(); if args.debug { dbg!(&args); dbg!(secret_number_min); dbg!(secret_number_max); dbg!(secret_number); } loop { let guess = make_guess(secret_number_min, secret_number_max, &guesses, &args); let guess_rating = rate_guess(guess, secret_number); if args.debug { dbg!(guess); } println!("{} Perfect", guess_rating.perfect); println!("{} Good", guess_rating.good); println!("{} Bad", guess_rating.bad); if guess_rating.perfect == args.digit as i8 { if args.auto { println!("The CPU won in {} guesses!", guesses.len()); } else { println!("You won in {} guesses!", guesses.len()); } break; } else { if args.auto { println!("The CPU didn't win!"); } else { println!("You didn't win, try again!"); } guesses.push(guess_rating); } } } fn make_guess(secret_number_min: i64, secret_number_max: i64, guesses: &[GuessRatings], args: &Cli) -> i64 { if args.auto { return cpu_guess(secret_number_min, secret_number_max, guesses); } person_guess(secret_number_min, secret_number_max, args) } fn person_guess(secret_number_min: i64, secret_number_max: i64, args: &Cli) -> i64 { input() .inside_err(secret_number_min..=secret_number_max, format!("Your guess must have {} digits. Try again!", args.digit)) .msg("What is your guess? ").get() } fn cpu_guess(secret_number_min: i64, secret_number_max: i64, guesses: &[GuessRatings]) -> i64 { loop { let guess = rand::thread_rng() .gen_range(secret_number_min, secret_number_max); if guesses.iter().find(|x| x.guess == guess).is_none() { println!("The CPU guesses . . . {}", guess); return guess; } } } fn rate_guess(guess: i64, secret: i64) -> GuessRatings { let secret_string = secret.to_string(); let secret_string_vector : Vec<_> = secret_string.chars().collect(); let guess_string = guess.to_string(); let mut perfect_count = 0; let mut good_count = 0; let mut bad_count = 0; for (guess_index, guess_integer) in guess_string.chars().enumerate() { if guess_integer == secret_string_vector[guess_index] { perfect_count += 1; } else if secret_string_vector.contains(&guess_integer) { good_count += 1; } else { bad_count += 1; } } GuessRatings { guess, perfect: perfect_count, good: good_count, bad: bad_count } } #[cfg(test)] mod tests { use super::*; #[test] fn test_three_perfect() { let ratings = rate_guess(123, 123); assert_eq!(ratings.perfect, 3); assert_eq!(ratings.good, 0); assert_eq!(ratings.bad, 0); } #[test] fn test_one_perfect_two_good() { let ratings = rate_guess(102, 120); assert_eq!(ratings.perfect, 1); assert_eq!(ratings.good, 2); assert_eq!(ratings.bad, 0); } #[test] fn test_three_good() { let ratings = rate_guess(132, 321); assert_eq!(ratings.perfect, 0); assert_eq!(ratings.good, 3); assert_eq!(ratings.bad, 0); } #[test] fn test_three_bad() { let ratings = rate_guess(132, 999); assert_eq!(ratings.perfect, 0); assert_eq!(ratings.good, 0); assert_eq!(ratings.bad, 3); } #[test] fn test_one_perfect_two_bad() { let ratings = rate_guess(132, 199); assert_eq!(ratings.perfect, 1); assert_eq!(ratings.good, 0); assert_eq!(ratings.bad, 2); } }
true
a4baab0aaec63b9cdccdee2386b41f82036206cd
Rust
slelaron/rtiow
/src/image.rs
UTF-8
1,962
3.203125
3
[]
no_license
use rayon::prelude::*; use std::io::{Result, Write}; use std::marker::{Send, Sync}; use std::ops::{Index, IndexMut}; #[derive(Clone, Copy)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8, } pub struct Image { pixels: Vec<Color>, width: u32, height: u32, } impl Image { pub fn with_background(height: u32, width: u32, color: Color) -> Image { let pixels = vec![color; (width * height) as usize]; Image { pixels, width, height, } } pub fn new(height: u32, width: u32) -> Image { Image::with_background( height, width, Color { red: 0, blue: 0, green: 0, }, ) } pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } pub fn write_ppm(&self, ostream: &mut dyn Write) -> Result<()> { writeln!(ostream, "P3\n{0} {1}\n255", self.width, self.height)?; for i in 0..self.height { for j in 0..self.width { let Color { red, green, blue } = self[(i, j)]; write!(ostream, "{0} {1} {2} ", red, green, blue)?; } writeln!(ostream)?; } Ok(()) } pub fn process_in_parallel(&mut self, f: impl Fn(u32, u32) -> Color + Sync + Send) { let width = self.width(); self.pixels .par_iter_mut() .enumerate() .for_each(move |(i, item)| *item = f(i as u32 / width, i as u32 % width)); } } impl Index<(u32, u32)> for Image { type Output = Color; fn index(&self, (i, j): (u32, u32)) -> &Color { &self.pixels[(i * self.width + j) as usize] } } impl IndexMut<(u32, u32)> for Image { fn index_mut(&mut self, (i, j): (u32, u32)) -> &mut Color { &mut self.pixels[(i * self.width + j) as usize] } }
true
506e149be3c3c30781d4165869627a80222dced0
Rust
DoumanAsh/actix-http
/src/ws/client/mod.rs
UTF-8
1,019
2.734375
3
[ "MIT", "Apache-2.0" ]
permissive
mod connect; mod error; mod service; pub use self::connect::Connect; pub use self::error::ClientError; pub use self::service::{Client, DefaultClient}; #[derive(PartialEq, Hash, Debug, Clone, Copy)] pub(crate) enum Protocol { Http, Https, Ws, Wss, } impl Protocol { fn from(s: &str) -> Option<Protocol> { match s { "http" => Some(Protocol::Http), "https" => Some(Protocol::Https), "ws" => Some(Protocol::Ws), "wss" => Some(Protocol::Wss), _ => None, } } fn is_http(self) -> bool { match self { Protocol::Https | Protocol::Http => true, _ => false, } } fn is_secure(self) -> bool { match self { Protocol::Https | Protocol::Wss => true, _ => false, } } fn port(self) -> u16 { match self { Protocol::Http | Protocol::Ws => 80, Protocol::Https | Protocol::Wss => 443, } } }
true
0362b7a7da4709e0f704b7bbb354e2de04b19d38
Rust
anhdungle93/rust_tutorial
/functions/src/main.rs
UTF-8
235
3.296875
3
[]
no_license
fn main() { println!("Hello, world!"); another_function(); another_function_2(3); } fn another_function() { println!("Another function."); } fn another_function_2(x: i32) { println!("The value of x is: {}", x) }
true
3ce12cd5adf6ce4ed72a7a1452d92ddcb6d742da
Rust
jutuon/pc-ps2-controller
/src/device/command_queue.rs
UTF-8
13,242
2.6875
3
[ "MIT", "Apache-2.0" ]
permissive
use super::io::SendToDevice; use super::keyboard::driver::{ DelayMilliseconds, KeyboardScancodeSetting, RateValue, SetAllKeys, SetKeyType, }; use super::keyboard::raw::{CommandReturnData, FromKeyboard}; use arraydeque::{Array, ArrayDeque, CapacityError, Saturating}; #[derive(Debug)] pub struct CommandQueue<T: Array<Item = Command>> { commands: ArrayDeque<T, Saturating>, command_checker: CommandChecker, } impl<T: Array<Item = Command>> Default for CommandQueue<T> { fn default() -> Self { Self::new() } } impl<T: Array<Item = Command>> CommandQueue<T> { pub fn new() -> Self { Self { commands: ArrayDeque::new(), command_checker: CommandChecker::new(), } } pub fn space_available(&self, count: usize) -> bool { (self.commands.capacity() - self.commands.len()) >= count } pub fn add<U: SendToDevice>( &mut self, command: Command, device: &mut U, ) -> Result<(), CapacityError<Command>> { let result = self.commands.push_back(command); if self.command_checker.current_command().is_none() { if let Some(command) = self.commands.pop_front() { self.command_checker.send_new_command(command, device) } } result } /// Receive data only if command queue is not empty. pub fn receive_data<U: SendToDevice>( &mut self, new_data: u8, device: &mut U, ) -> Option<Status> { let result = self.command_checker.receive_data(new_data, device); if let Some(Status::CommandFinished(_)) = &result { if let Some(command) = self.commands.pop_front() { self.command_checker.send_new_command(command, device); } } result } pub fn empty(&self) -> bool { self.commands.is_empty() && self.command_checker.current_command().is_none() } } #[derive(Debug, Default)] pub struct CommandChecker { current_command: Option<Command>, } impl CommandChecker { pub fn new() -> Self { Self { current_command: None, } } pub fn current_command(&self) -> &Option<Command> { &self.current_command } pub fn send_new_command<T: SendToDevice>(&mut self, command: Command, device: &mut T) { match &command { Command::Echo { command } | Command::AckResponse { command, .. } | Command::AckResponseWithReturnTwoBytes { command, .. } | Command::SendCommandAndData { command, .. } | Command::SendCommandAndDataSingleAck { command, .. } | Command::SendCommandAndDataAndReceiveResponse { command, .. } => { device.send(*command) } } self.current_command = Some(command); } pub fn receive_data<U: SendToDevice>( &mut self, new_data: u8, device: &mut U, ) -> Option<Status> { if let Some(mut command) = self.current_command.take() { let mut command_finished = false; let mut unexpected_data = None; match &mut command { Command::Echo { .. } => { if new_data == FromKeyboard::ECHO { command_finished = true; } else if new_data == FromKeyboard::RESEND { self.send_new_command(command, device); return None; } else { unexpected_data = Some(new_data); } } Command::AckResponse { .. } => { if new_data == FromKeyboard::ACK { command_finished = true; } else if new_data == FromKeyboard::RESEND { self.send_new_command(command, device); return None; } else { unexpected_data = Some(new_data); } } Command::AckResponseWithReturnTwoBytes { state: s @ AckResponseWithReturnTwoBytesState::WaitAck, .. } => { if new_data == FromKeyboard::ACK { *s = AckResponseWithReturnTwoBytesState::WaitFirstByte; } else if new_data == FromKeyboard::RESEND { self.send_new_command(command, device); return None; } else { unexpected_data = Some(new_data); } } Command::AckResponseWithReturnTwoBytes { state: s @ AckResponseWithReturnTwoBytesState::WaitFirstByte, byte1, .. } => { *s = AckResponseWithReturnTwoBytesState::WaitSecondByte; *byte1 = new_data; } Command::AckResponseWithReturnTwoBytes { state: AckResponseWithReturnTwoBytesState::WaitSecondByte, byte2, .. } => { *byte2 = new_data; command_finished = true; } Command::SendCommandAndData { state: s @ SendCommandAndDataState::WaitAck1, data, .. } => { if new_data == FromKeyboard::ACK { *s = SendCommandAndDataState::WaitAck2; device.send(*data); } else if new_data == FromKeyboard::RESEND { self.send_new_command(command, device); return None; } else { unexpected_data = Some(new_data); } } Command::SendCommandAndData { state: SendCommandAndDataState::WaitAck2, data, .. } => { if new_data == FromKeyboard::ACK { command_finished = true; } else if new_data == FromKeyboard::RESEND { device.send(*data); } else { unexpected_data = Some(new_data); } } Command::SendCommandAndDataSingleAck { state: s @ SendCommandAndDataState::WaitAck1, data, .. } => { if new_data == FromKeyboard::ACK { *s = SendCommandAndDataState::WaitAck2; device.send(*data); } else if new_data == FromKeyboard::RESEND { self.send_new_command(command, device); return None; } else { unexpected_data = Some(new_data); } } Command::SendCommandAndDataSingleAck { state: SendCommandAndDataState::WaitAck2, data, scancode_received_after_this_command, .. } => { if new_data == FromKeyboard::RESEND { device.send(*data); } else { *scancode_received_after_this_command = new_data; command_finished = true; } } Command::SendCommandAndDataAndReceiveResponse { state: s @ SendCommandAndDataAndReceiveResponseState::WaitAck1, data, .. } => { if new_data == FromKeyboard::ACK { *s = SendCommandAndDataAndReceiveResponseState::WaitAck2; device.send(*data); } else if new_data == FromKeyboard::RESEND { self.send_new_command(command, device); return None; } else { unexpected_data = Some(new_data); } } Command::SendCommandAndDataAndReceiveResponse { state: s @ SendCommandAndDataAndReceiveResponseState::WaitAck2, data, .. } => { if new_data == FromKeyboard::ACK { *s = SendCommandAndDataAndReceiveResponseState::WaitResponse; } else if new_data == FromKeyboard::RESEND { device.send(*data); } } Command::SendCommandAndDataAndReceiveResponse { state: SendCommandAndDataAndReceiveResponseState::WaitResponse, response, .. } => { *response = new_data; command_finished = true; } } if command_finished { Some(Status::CommandFinished(command)) } else { self.current_command = Some(command); if let Some(data) = unexpected_data { Some(Status::UnexpectedData(data)) } else { Some(Status::CommandInProgress) } } } else { None } } } #[derive(Debug)] pub enum Command { Echo { command: u8, }, AckResponse { command: u8, }, AckResponseWithReturnTwoBytes { command: u8, byte1: u8, byte2: u8, state: AckResponseWithReturnTwoBytesState, }, SendCommandAndData { command: u8, data: u8, state: SendCommandAndDataState, }, SendCommandAndDataSingleAck { command: u8, data: u8, scancode_received_after_this_command: u8, state: SendCommandAndDataState, }, SendCommandAndDataAndReceiveResponse { command: u8, data: u8, response: u8, state: SendCommandAndDataAndReceiveResponseState, }, } impl Command { pub fn default_disable() -> Self { Command::AckResponse { command: CommandReturnData::DEFAULT_DISABLE, } } pub fn set_default() -> Self { Command::AckResponse { command: CommandReturnData::SET_DEFAULT, } } pub fn read_id() -> Self { Command::AckResponseWithReturnTwoBytes { command: CommandReturnData::READ_ID, byte1: 0, byte2: 0, state: AckResponseWithReturnTwoBytesState::WaitAck, } } pub fn enable() -> Self { Command::AckResponse { command: CommandReturnData::ENABLE, } } pub fn set_status_indicators(data: u8) -> Self { Command::SendCommandAndData { command: CommandReturnData::SET_STATUS_INDICATORS, data, state: SendCommandAndDataState::WaitAck1, } } pub fn scancode_set_3_set_all_keys(command: SetAllKeys) -> Self { Command::AckResponse { command: command as u8, } } pub fn scancode_set_3_set_key_type(command: SetKeyType, scancode: u8) -> Self { Command::SendCommandAndDataSingleAck { command: command as u8, data: scancode, scancode_received_after_this_command: 0, state: SendCommandAndDataState::WaitAck1, } } pub fn set_typematic_rate(delay: DelayMilliseconds, rate: RateValue) -> Self { Command::SendCommandAndData { command: CommandReturnData::SET_TYPEMATIC_RATE, data: delay as u8 | rate.value(), state: SendCommandAndDataState::WaitAck1, } } pub fn set_alternate_scancodes(scancode_setting: KeyboardScancodeSetting) -> Self { Command::SendCommandAndData { command: CommandReturnData::SELECT_ALTERNATE_SCANCODES, data: scancode_setting as u8, state: SendCommandAndDataState::WaitAck1, } } pub fn get_current_scancode_set() -> Self { Command::SendCommandAndDataAndReceiveResponse { command: CommandReturnData::SELECT_ALTERNATE_SCANCODES, data: 0, response: 0, state: SendCommandAndDataAndReceiveResponseState::WaitAck1, } } pub fn echo() -> Self { Command::Echo { command: CommandReturnData::ECHO, } } } #[derive(Debug)] pub enum Status { UnexpectedData(u8), CommandInProgress, CommandFinished(Command), } #[derive(Debug)] pub enum AckResponseWithReturnTwoBytesState { WaitAck, WaitFirstByte, WaitSecondByte, } #[derive(Debug)] pub enum SendCommandAndDataState { WaitAck1, WaitAck2, } #[derive(Debug)] pub enum SendCommandAndDataAndReceiveResponseState { WaitAck1, WaitAck2, WaitResponse, }
true
041a232c7987dc01689318760129fc1f5a2d9020
Rust
quebin31/transactions
/src/error.rs
UTF-8
541
2.984375
3
[]
no_license
use std::error::Error; use std::fmt; use std::fmt::{ Display, Formatter }; #[derive(Debug)] pub struct ConcurrencyError { message: String } impl ConcurrencyError { pub fn new(msg: &str) -> Self { ConcurrencyError { message: String::from(msg) } } } impl Error for ConcurrencyError { fn description(&self) -> &str { self.message.as_str() } } impl Display for ConcurrencyError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{:?}", self) } } pub type ResultC<T> = Result<T, ConcurrencyError>;
true
08410cb452664dfbebabe89592ad0ca3676bf978
Rust
Hilldrupca/LeetCode
/rust/Problems/Easy/two_sum/src/main.rs
UTF-8
1,393
3.859375
4
[]
no_license
use std::collections::HashMap; struct Solution {} impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { // Returns the indices of the two numbers that sum to the target value. // Assumed that each input has exactly one solution. // // Constraints: // 2 <= nums.length() <= 10**3 // -10**9 <= nums[i] <= 10**9 // -19**9 <= target <= 10**9 // only one valid answer exists let mut res: Vec<i32> = Vec::new(); let mut compliment: HashMap<i32, i32> = HashMap::new(); for (i, num) in (0..).zip(nums) { let comp = target - num; if compliment.contains_key(&comp) == true { res.push(*compliment.get(&comp).unwrap()); res.push(i); break; } compliment.insert(num, i); } res } } #[cfg(test)] mod tests { use super::*; #[test] fn test_two_sum() { assert_eq!( Solution::two_sum(vec![2,7,11,15], 9), vec![0,1] ); assert_eq!( Solution::two_sum(vec![3,2,4], 6), vec![1,2] ); assert_eq!( Solution::two_sum(vec![3,3], 6), vec![0,1] ); } }
true
d9e26164f7b3bf29d6ec18895ac6b47623986d1b
Rust
GaloisInc/crucible
/crux-mir/test/conc_eval/ops/deref3.rs
UTF-8
694
3.0625
3
[ "BSD-3-Clause" ]
permissive
#![cfg_attr(not(with_main), no_std)] // Method call via `DerefMut::deref_mut` extern crate core; use core::ops::{Deref, DerefMut}; struct MyPtr<T>(T); impl<T> Deref for MyPtr<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T> DerefMut for MyPtr<T> { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } struct S; impl S { fn foo(&self) -> bool { true } fn bar(&mut self) -> bool { true } } const ARG: i32 = 1; fn f(arg: i32) { let mut p = MyPtr(S); assert!(p.bar()); } #[cfg(with_main)] pub fn main() { println!("{:?}", f(ARG)); } #[cfg(not(with_main))] #[cfg_attr(crux, crux::test)] fn crux_test() -> () { f(ARG) }
true
c21f4fed216e0ae6a25a79aa87efeebe6c9e3b6f
Rust
gbip/stm32f429x
/src/otg_fs_global/fs_gnptxsts/mod.rs
UTF-8
2,042
2.640625
3
[ "MIT" ]
permissive
#[doc = r" Value read from the register"] pub struct R { bits: u32, } impl super::FsGnptxsts { #[doc = r" Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } } #[doc = r" Value of the field"] pub struct NptxfsavR { bits: u16, } impl NptxfsavR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u16 { self.bits } } #[doc = r" Value of the field"] pub struct NptqxsavR { bits: u8, } impl NptqxsavR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct NptxqtopR { bits: u8, } impl NptxqtopR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } impl R { #[doc = r" Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:15 - Non-periodic TxFIFO space available"] #[inline(always)] pub fn nptxfsav(&self) -> NptxfsavR { let bits = { const MASK: u16 = 65535; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u16 }; NptxfsavR { bits } } #[doc = "Bits 16:23 - Non-periodic transmit request queue space available"] #[inline(always)] pub fn nptqxsav(&self) -> NptqxsavR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; NptqxsavR { bits } } #[doc = "Bits 24:30 - Top of the non-periodic transmit request queue"] #[inline(always)] pub fn nptxqtop(&self) -> NptxqtopR { let bits = { const MASK: u8 = 127; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 }; NptxqtopR { bits } } }
true
91e67c68541cc92f009f42d745009eef4398bfa4
Rust
Axect/Peroxide
/src/numerical/spline.rs
UTF-8
24,178
3.453125
3
[ "MIT", "Apache-2.0" ]
permissive
//! Spline interpolations //! //! # Available splines //! //! * Cubic spline //! * Cubic Hermite spline //! //! # `Spline` trait //! //! ## Methods //! //! Let `T: Into<f64> + Copy` //! * `fn eval<T>(&self, x: T) -> f64` : Evaluate the spline at x //! * `fn eval_vec<T>(&self, v: &[T]) -> Vec<f64>` : Evaluate spline values for an array v //! * `fn polynomial_at<T>(&self, x: T) -> &Polynomial` : Get the polynomial at x //! * `fn number_of_polynomials(&self) -> usize` : Get the number of polynomials //! * `fn get_ranged_polynomials(&self) -> &Vec<(Range<f64>, Polynomial)>` : Get the polynomials //! * `fn eval_with_cond<F>(&self, x: f64, cond: F) -> f64` : Evaluate the spline at x, with a condition //! * `fn eval_vec_with_cond<F>(&self, v: &[f64], cond: F) -> Vec<f64>` : Evaluate spline values for an array v, with a condition //! //! # Low-level interface //! //! ## Members //! //! * `CubicSpline`: Structure for cubic spline //! * `fn from_nodes(node_x: &[f64], node_y: &[f64]) -> Self` : Create a cubic spline from nodes //! * `fn extend_with_nodes(&mut self, node_x: Vec<f64>, node_y: Vec<f64>)` : Extend the spline with nodes //! * `CubicHermiteSpline`: Structure for cubic Hermite spline //! * `fn from_nodes_with_slopes(node_x: &[f64], node_y: &[f64], m: &[f64]) -> Self` : Create a Cubic Hermite spline from nodes with slopes //! * `fn from_nodes(node_x: &[f64], node_y: &[f64], slope_method: SlopeMethod) -> Self` : Create a Cubic Hermite spline from nodes with slope estimation methods //! * `SlopeMethod`: Enum for slope estimation methods //! * `Akima`: Akima's method to estimate slopes ([Akima (1970)](https://dl.acm.org/doi/abs/10.1145/321607.321609)) //! * `Quadratic`: Using quadratic interpolation to estimate slopes //! //! ## Usage //! //! ```rust //! use peroxide::fuga::*; //! //! fn main() { //! let x = seq(0, 10, 1); //! let y = x.fmap(|t| t.sin()); //! //! let cs = CubicSpline::from_nodes(&x, &y); //! let cs_akima = CubicHermiteSpline::from_nodes(&x, &y, SlopeMethod::Akima); //! let cs_quad = CubicHermiteSpline::from_nodes(&x, &y, SlopeMethod::Quadratic); //! //! cs.polynomial_at(0f64).print(); //! cs_akima.polynomial_at(0f64).print(); //! cs_quad.polynomial_at(0f64).print(); //! // -0.1523x^3 + 0.9937x //! // 0.1259x^3 - 0.5127x^2 + 1.2283x //! // -0.0000x^3 - 0.3868x^2 + 1.2283x //! //! let new_x = seq(4, 6, 0.1); //! let new_y = new_x.fmap(|t| t.sin()); //! //! let y_cs = cs.eval_vec(&new_x); //! let y_akima = cs_akima.eval_vec(&new_x); //! let y_quad = cs_quad.eval_vec(&new_x); //! //! let mut df = DataFrame::new(vec![]); //! df.push("x", Series::new(new_x)); //! df.push("y", Series::new(new_y)); //! df.push("y_cs", Series::new(y_cs)); //! df.push("y_akima", Series::new(y_akima)); //! df.push("y_quad", Series::new(y_quad)); //! //! df.print(); //! // x y y_cs y_akima y_quad //! // r[0] 5 -0.9589 -0.9589 -0.9589 -0.9589 //! // r[1] 5.2 -0.8835 -0.8826 -0.8583 -0.8836 //! // r[2] 5.4 -0.7728 -0.7706 -0.7360 -0.7629 //! // r[3] 5.6 -0.6313 -0.6288 -0.5960 -0.6120 //! // r[4] 5.8 -0.4646 -0.4631 -0.4424 -0.4459 //! // r[5] 6 -0.2794 -0.2794 -0.2794 -0.2794 //! } //! ``` //! //! # High-level interface //! //! ## Functions //! //! * `fn cubic_spline(node_x: &[f64], node_y: &[f64]) -> CubicSpline` : Create a cubic spline from nodes //! * `fn cubic_hermite_spline(node_x: &[f64], node_y: &[f64], m: &[f64]) -> CubicHermiteSpline` : Create a cubic Hermite spline from nodes with slopes //! //! ## Usage //! //! ```rust //! use peroxide::fuga::*; //! //! fn main() { //! let x = seq(0, 10, 1); //! let y = x.fmap(|t| t.sin()); //! //! let cs = cubic_spline(&x, &y); //! let cs_akima = cubic_hermite_spline(&x, &y, SlopeMethod::Akima); //! let cs_quad = cubic_hermite_spline(&x, &y, SlopeMethod::Quadratic); //! //! cs.polynomial_at(0f64).print(); //! cs_akima.polynomial_at(0f64).print(); //! cs_quad.polynomial_at(0f64).print(); //! // -0.1523x^3 + 0.9937x //! // 0.1259x^3 - 0.5127x^2 + 1.2283x //! // -0.0000x^3 - 0.3868x^2 + 1.2283x //! //! let new_x = seq(4, 6, 0.1); //! let new_y = new_x.fmap(|t| t.sin()); //! //! let y_cs = cs.eval_vec(&new_x); //! let y_akima = cs_akima.eval_vec(&new_x); //! let y_quad = cs_quad.eval_vec(&new_x); //! //! let mut df = DataFrame::new(vec![]); //! df.push("x", Series::new(new_x)); //! df.push("y", Series::new(new_y)); //! df.push("y_cs", Series::new(y_cs)); //! df.push("y_akima", Series::new(y_akima)); //! df.push("y_quad", Series::new(y_quad)); //! //! df.print(); //! // x y y_cs y_akima y_quad //! // r[0] 5 -0.9589 -0.9589 -0.9589 -0.9589 //! // r[1] 5.2 -0.8835 -0.8826 -0.8583 -0.8836 //! // r[2] 5.4 -0.7728 -0.7706 -0.7360 -0.7629 //! // r[3] 5.6 -0.6313 -0.6288 -0.5960 -0.6120 //! // r[4] 5.8 -0.4646 -0.4631 -0.4424 -0.4459 //! // r[5] 6 -0.2794 -0.2794 -0.2794 -0.2794 //! } //! ``` //! //! # Calculus with splines //! //! ## Usage //! //! ```rust //! use peroxide::fuga::*; //! use std::f64::consts::PI; //! //! fn main() { //! let x = seq(0, 10, 1); //! let y = x.fmap(|t| t.sin()); //! //! let cs = cubic_spline(&x, &y); //! let cs_akima = cubic_hermite_spline(&x, &y, SlopeMethod::Akima); //! let cs_quad = cubic_hermite_spline(&x, &y, SlopeMethod::Quadratic); //! //! println!("============ Polynomial at x=0 ============"); //! //! cs.polynomial_at(0f64).print(); //! cs_akima.polynomial_at(0f64).print(); //! cs_quad.polynomial_at(0f64).print(); //! //! println!("============ Derivative at x=0 ============"); //! //! cs.derivative().polynomial_at(0f64).print(); //! cs_akima.derivative().polynomial_at(0f64).print(); //! cs_quad.derivative().polynomial_at(0f64).print(); //! //! println!("============ Integral at x=0 ============"); //! //! cs.integral().polynomial_at(0f64).print(); //! cs_akima.integral().polynomial_at(0f64).print(); //! cs_quad.integral().polynomial_at(0f64).print(); //! //! println!("============ Integrate from x=0 to x=pi ============"); //! //! cs.integrate((0f64, PI)).print(); //! cs_akima.integrate((0f64, PI)).print(); //! cs_quad.integrate((0f64, PI)).print(); //! //! // ============ Polynomial at x=0 ============ //! // -0.1523x^3 + 0.9937x //! // 0.1259x^3 - 0.5127x^2 + 1.2283x //! // -0.0000x^3 - 0.3868x^2 + 1.2283x //! // ============ Derivative at x=0 ============ //! // -0.4568x^2 + 0.9937 //! // 0.3776x^2 - 1.0254x + 1.2283 //! // -0.0000x^2 - 0.7736x + 1.2283 //! // ============ Integral at x=0 ============ //! // -0.0381x^4 + 0.4969x^2 //! // 0.0315x^4 - 0.1709x^3 + 0.6141x^2 //! // -0.0000x^4 - 0.1289x^3 + 0.6141x^2 //! // ============ Integrate from x=0 to x=pi ============ //! // 1.9961861265456702 //! // 2.0049920614062775 //! // 2.004327391790717 //! } //! ``` //! //! # References //! //! * Gary D. Knott, *Interpolating Splines*, Birkhäuser Boston, MA, (2000). #[allow(unused_imports)] use crate::structure::matrix::*; #[allow(unused_imports)] use crate::structure::polynomial::*; #[allow(unused_imports)] use crate::structure::vector::*; use crate::traits::num::PowOps; #[allow(unused_imports)] use crate::util::non_macro::*; use crate::util::useful::zip_range; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::cmp::{max, min}; use std::convert::{From, Into}; use std::ops::{Index, Range}; /// Trait for spline interpolation /// /// # Available Splines /// /// - `CubicSpline` /// - `CubicHermiteSpline` pub trait Spline { fn eval<T: std::convert::Into<f64> + Copy>(&self, x: T) -> f64 { let x = x.into(); self.polynomial_at(x).eval(x) } fn eval_vec<T: std::convert::Into<f64> + Copy>(&self, v: &[T]) -> Vec<f64> { let mut result = vec![0f64; v.len()]; for (i, x) in v.iter().enumerate() { result[i] = self.eval(*x); } result } fn polynomial_at<T: std::convert::Into<f64> + Copy>(&self, x: T) -> &Polynomial { let x = x.into(); let poly = self.get_ranged_polynomials(); let index = match poly.binary_search_by(|(range, _)| { if range.contains(&x) { core::cmp::Ordering::Equal } else if x < range.start { core::cmp::Ordering::Greater } else { core::cmp::Ordering::Less } }) { Ok(index) => index, Err(index) => max(0, min(index, poly.len() - 1)), }; &poly[index].1 } fn number_of_polynomials(&self) -> usize { self.get_ranged_polynomials().len() } fn get_ranged_polynomials(&self) -> &Vec<(Range<f64>, Polynomial)>; fn eval_with_cond<F: Fn(f64) -> f64>(&self, x: f64, cond: F) -> f64 { cond(self.eval(x)) } fn eval_vec_with_cond<F: Fn(f64) -> f64 + Copy>(&self, x: &[f64], cond: F) -> Vec<f64> { x.iter().map(|&x| self.eval_with_cond(x, cond)).collect() } } // ============================================================================= // High level functions // ============================================================================= /// Cubic Spline (Natural) /// /// # Description /// /// Implement traits of Natural cubic splines, by Arne Morten Kvarving. /// /// # Type /// `(&[f64], &[f64]) -> Cubic Spline` /// /// # Examples /// ``` /// #[macro_use] /// extern crate peroxide; /// use peroxide::fuga::*; /// /// fn main() { /// let x = c!(0.9, 1.3, 1.9, 2.1); /// let y = c!(1.3, 1.5, 1.85, 2.1); /// /// let s = cubic_spline(&x, &y); /// /// let new_x = c!(1, 1.5, 2.0); /// /// // Generate Cubic polynomial /// for t in new_x.iter() { /// s.polynomial_at(*t).print(); /// } /// // -0.2347x^3 + 0.6338x^2 - 0.0329x + 0.9873 /// // 0.9096x^3 - 3.8292x^2 + 5.7691x - 1.5268 /// // -2.2594x^3 + 14.2342x^2 - 28.5513x + 20.2094 /// /// // Evaluation /// for t in new_x.iter() { /// s.eval(*t).print(); /// } /// } /// ``` pub fn cubic_spline(node_x: &[f64], node_y: &[f64]) -> CubicSpline { CubicSpline::from_nodes(node_x, node_y) } pub fn cubic_hermite_spline(node_x: &[f64], node_y: &[f64], slope_method: SlopeMethod) -> CubicHermiteSpline { CubicHermiteSpline::from_nodes(node_x, node_y, slope_method) } // ============================================================================= // Cubic Spline // ============================================================================= /// Cubic Spline (Natural) /// /// # Description /// /// Implement traits of Natural cubic splines, by Arne Morten Kvarving. /// /// # Type /// `(&[f64], &[f64]) -> Cubic Spline` /// /// # Examples /// ``` /// #[macro_use] /// extern crate peroxide; /// use peroxide::fuga::*; /// /// fn main() { /// let x = c!(0.9, 1.3, 1.9, 2.1); /// let y = c!(1.3, 1.5, 1.85, 2.1); /// /// let s = CubicSpline::from_nodes(&x, &y); /// /// let new_x = c!(1, 1.5, 2.0); /// /// // Generate Cubic polynomial /// for t in new_x.iter() { /// s.polynomial_at(*t).print(); /// } /// // -0.2347x^3 + 0.6338x^2 - 0.0329x + 0.9873 /// // 0.9096x^3 - 3.8292x^2 + 5.7691x - 1.5268 /// // -2.2594x^3 + 14.2342x^2 - 28.5513x + 20.2094 /// /// // Evaluation /// for t in new_x.iter() { /// s.eval(*t).print(); /// } /// } /// ``` #[derive(Debug, Clone, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CubicSpline { polynomials: Vec<(Range<f64>, Polynomial)>, } impl Spline for CubicSpline { fn get_ranged_polynomials(&self) -> &Vec<(Range<f64>, Polynomial)> { &self.polynomials } } impl CubicSpline { /// # Examples /// ``` /// #[macro_use] /// extern crate peroxide; /// use peroxide::fuga::*; /// /// fn main() { /// let x = c!(0.9, 1.3, 1.9, 2.1); /// let y = c!(1.3, 1.5, 1.85, 2.1); /// /// let s = CubicSpline::from_nodes(&x, &y); /// /// for i in 0 .. 4 { /// println!("{}", s.eval(i as f64 / 2.0)); /// } /// } /// ``` pub fn from_nodes(node_x: &[f64], node_y: &[f64]) -> Self { let polynomials = CubicSpline::cubic_spline(node_x, node_y); CubicSpline { polynomials: zip_range(node_x, &polynomials), } } fn cubic_spline(node_x: &[f64], node_y: &[f64]) -> Vec<Polynomial> { //! Pre calculated variables //! node_x: n+1 //! node_y: n+1 //! h : n //! b : n //! v : n //! u : n //! z : n+1 let n = node_x.len() - 1; assert_eq!(n, node_y.len() - 1); // Pre-calculations let mut h = vec![0f64; n]; let mut b = vec![0f64; n]; let mut v = vec![0f64; n]; let mut u = vec![0f64; n]; for i in 0..n { if i == 0 { h[i] = node_x[i + 1] - node_x[i]; b[i] = (node_y[i + 1] - node_y[i]) / h[i]; } else { h[i] = node_x[i + 1] - node_x[i]; b[i] = (node_y[i + 1] - node_y[i]) / h[i]; v[i] = 2. * (h[i] + h[i - 1]); u[i] = 6. * (b[i] - b[i - 1]); } } // Tri-diagonal matrix let mut m = matrix(vec![0f64; (n - 1) * (n - 1)], n - 1, n - 1, Col); for i in 0..n - 2 { m[(i, i)] = v[i + 1]; m[(i + 1, i)] = h[i + 1]; m[(i, i + 1)] = h[i + 1]; } m[(n - 2, n - 2)] = v[n - 1]; // Calculate z let z_inner = m.inv() * Vec::from(&u[1..]); let mut z = vec![0f64]; z.extend(&z_inner); z.push(0f64); // Declare empty spline let mut s: Vec<Polynomial> = Vec::new(); // Main process for i in 0..n { // Memoization let t_i = node_x[i]; let t_i1 = node_x[i + 1]; let z_i = z[i]; let z_i1 = z[i + 1]; let h_i = h[i]; let y_i = node_y[i]; let y_i1 = node_y[i + 1]; let temp1 = poly(vec![1f64, -t_i]); let temp2 = poly(vec![1f64, -t_i1]); let term1 = temp1.powi(3) * (z_i1 / (6f64 * h_i)); let term2 = temp2.powi(3) * (-z_i / (6f64 * h_i)); let term3 = temp1 * (y_i1 / h_i - z_i1 * h_i / 6.); let term4 = temp2 * (-y_i / h_i + h_i * z_i / 6.0); s.push(term1 + term2 + term3 + term4); } return s; } /// Extends the spline with the given nodes. /// /// # Description /// /// The method ensures that the transition between each polynomial is smooth and that the spline /// interpolation of the new nodes is calculated around `x = 0` in order to avoid that /// successive spline extensions with large x values become inaccurate. pub fn extend_with_nodes(&mut self, node_x: Vec<f64>, node_y: Vec<f64>) { let mut ext_node_x = Vec::with_capacity(node_x.len() + 1); let mut ext_node_y = Vec::with_capacity(node_x.len() + 1); let (r, polynomial) = &self.polynomials[self.polynomials.len() - 1]; ext_node_x.push(0.0f64); ext_node_y.push(polynomial.eval(r.end)); // translating the node towards x = 0 increases accuracy tremendously let tx = r.end; ext_node_x.extend(node_x.into_iter().map(|x| x - tx)); ext_node_y.extend(node_y); let polynomials = zip_range( &ext_node_x, &CubicSpline::cubic_spline(&ext_node_x, &ext_node_y), ); self.polynomials .extend(polynomials.into_iter().map(|(r, p)| { ( Range { start: r.start + tx, end: r.end + tx, }, p.translate_x(tx), ) })); } } impl std::convert::Into<Vec<Polynomial>> for CubicSpline { fn into(self) -> Vec<Polynomial> { self.polynomials .into_iter() .map(|(_, polynomial)| polynomial) .collect() } } impl From<Vec<(Range<f64>, Polynomial)>> for CubicSpline { fn from(polynomials: Vec<(Range<f64>, Polynomial)>) -> Self { CubicSpline { polynomials } } } impl Into<Vec<(Range<f64>, Polynomial)>> for CubicSpline { fn into(self) -> Vec<(Range<f64>, Polynomial)> { self.polynomials } } impl Index<usize> for CubicSpline { type Output = (Range<f64>, Polynomial); fn index(&self, index: usize) -> &Self::Output { &self.polynomials[index] } } impl Calculus for CubicSpline { fn derivative(&self) -> Self { let mut polynomials: Vec<(Range<f64>, Polynomial)> = self.clone().into(); polynomials = polynomials .into_iter() .map(|(r, poly)| (r, poly.derivative())) .collect(); Self::from(polynomials) } fn integral(&self) -> Self { let mut polynomials: Vec<(Range<f64>, Polynomial)> = self.clone().into(); polynomials = polynomials .into_iter() .map(|(r, poly)| (r, poly.integral())) .collect(); Self::from(polynomials) } fn integrate<T: Into<f64> + Copy>(&self, interval: (T, T)) -> f64 { let (a, b) = interval; let a = a.into(); let b = b.into(); let mut s = 0f64; for (r, p) in self.polynomials.iter() { if r.start > b { break; } else if r.end < a { continue; } else { // r.start <= b, r.end >= a let x = r.start.max(a); let y = r.end.min(b); s += p.integrate((x, y)); } } s } } // ============================================================================= // Cubic Hermite Spline // ============================================================================= #[derive(Debug, Clone)] pub struct CubicHermiteSpline { polynomials: Vec<(Range<f64>, Polynomial)>, } impl Spline for CubicHermiteSpline { fn get_ranged_polynomials(&self) -> &Vec<(Range<f64>, Polynomial)> { &self.polynomials } } impl CubicHermiteSpline { pub fn from_nodes_with_slopes(node_x: &[f64], node_y: &[f64], m: &[f64]) -> Self { let mut r = vec![Range::default(); node_x.len()-1]; let mut u = vec![Polynomial::default(); node_x.len()-1]; for i in 0 .. node_x.len()-1 { let a_i = node_y[i]; let b_i = m[i]; let dx = node_x[i+1] - node_x[i]; let dy = node_y[i+1] - node_y[i]; let c_i = (3f64 * dy/dx - 2f64*m[i] - m[i+1]) / dx; let d_i = (m[i] + m[i+1] - 2f64 * dy/dx) / dx.powi(2); let p = Polynomial::new(vec![1f64, -node_x[i]]); r[i] = Range { start: node_x[i], end: node_x[i+1] }; u[i] = p.powi(3) * d_i + p.powi(2) * c_i + p.clone() * b_i; u[i].coef[3] += a_i; } CubicHermiteSpline { polynomials: r.into_iter().zip(u).collect(), } } pub fn from_nodes(node_x: &[f64], node_y: &[f64], slope_method: SlopeMethod) -> Self { match slope_method { SlopeMethod::Akima => { CubicHermiteSpline::from_nodes_with_slopes(node_x, node_y, &akima_slopes(node_x, node_y)) }, SlopeMethod::Quadratic => { CubicHermiteSpline::from_nodes_with_slopes(node_x, node_y, &quadratic_slopes(node_x, node_y)) }, } } } impl std::convert::Into<Vec<Polynomial>> for CubicHermiteSpline { fn into(self) -> Vec<Polynomial> { self.polynomials .into_iter() .map(|(_, polynomial)| polynomial) .collect() } } impl From<Vec<(Range<f64>, Polynomial)>> for CubicHermiteSpline { fn from(polynomials: Vec<(Range<f64>, Polynomial)>) -> Self { CubicHermiteSpline { polynomials } } } impl Into<Vec<(Range<f64>, Polynomial)>> for CubicHermiteSpline { fn into(self) -> Vec<(Range<f64>, Polynomial)> { self.polynomials } } impl Index<usize> for CubicHermiteSpline { type Output = (Range<f64>, Polynomial); fn index(&self, index: usize) -> &Self::Output { &self.polynomials[index] } } impl Calculus for CubicHermiteSpline { fn derivative(&self) -> Self { let mut polynomials: Vec<(Range<f64>, Polynomial)> = self.clone().into(); polynomials = polynomials .into_iter() .map(|(r, poly)| (r, poly.derivative())) .collect(); Self::from(polynomials) } fn integral(&self) -> Self { let mut polynomials: Vec<(Range<f64>, Polynomial)> = self.clone().into(); polynomials = polynomials .into_iter() .map(|(r, poly)| (r, poly.integral())) .collect(); Self::from(polynomials) } fn integrate<T: Into<f64> + Copy>(&self, interval: (T, T)) -> f64 { let (a, b) = interval; let a = a.into(); let b = b.into(); let mut s = 0f64; for (r, p) in self.polynomials.iter() { if r.start > b { break; } else if r.end < a { continue; } else { // r.start <= b, r.end >= a let x = r.start.max(a); let y = r.end.min(b); s += p.integrate((x, y)); } } s } } // ============================================================================= // Estimate Slopes // ============================================================================= #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum SlopeMethod { Akima, Quadratic, } fn akima_slopes(x: &[f64], y: &[f64]) -> Vec<f64> { if x.len() < 3 { panic!("Cubic spline need at least 3 nodes"); } let mut m = vec![0f64; x.len()]; let mut s = vec![0f64; x.len()+3]; // -2, -1, 0, ..., x.len()-1, x.len() let l_i = lagrange_polynomial(x[0..3].to_vec(), y[0..3].to_vec()); let l_f = lagrange_polynomial(x[x.len()-3..].to_vec(), y[y.len()-3..].to_vec()); let x_i = x[0] - (x[1] - x[0]) / 10f64; let x_ii = x_i - (x[1] - x[0]) / 10f64; let x_f = x[x.len()-1] + (x[x.len()-1] - x[x.len()-2]) / 10f64; let x_ff = x_f + (x[x.len()-1] - x[x.len()-2]) / 10f64; let y_i = l_i.eval(x_i); let y_ii = l_i.eval(x_ii); let y_f = l_f.eval(x_f); let y_ff = l_f.eval(x_ff); let new_x = concat(&concat(&vec![x_ii, x_i], &x.to_vec()), &vec![x_f, x_ff]); let new_y = concat(&concat(&vec![y_ii, y_i], &y.to_vec()), &vec![y_f, y_ff]); for i in 0 .. new_x.len()-1 { let dx = new_x[i+1] - new_x[i]; if dx == 0f64 { panic!("x nodes should be different!"); } s[i] = (new_y[i+1] - new_y[i]) / dx; } for i in 0 .. x.len() { let j = i+2; let ds_f = (s[j+1] - s[j]).abs(); let ds_i = (s[j-1] - s[j-2]).abs(); m[i] = if ds_f == 0f64 && ds_i == 0f64 { (s[j-1] + s[j]) / 2f64 } else { (ds_f * s[j-1] + ds_i * s[j]) / (ds_f + ds_i) }; } m } fn quadratic_slopes(x: &[f64], y: &[f64]) -> Vec<f64> { let mut m = vec![0f64; x.len()]; let q_i = lagrange_polynomial(x[0..3].to_vec(), y[0..3].to_vec()); let q_f = lagrange_polynomial(x[x.len()-3..].to_vec(), y[y.len()-3..].to_vec()); m[0] = q_i.derivative().eval(x[0]); m[x.len()-1] = q_f.derivative().eval(x[x.len()-1]); for i in 1 .. x.len()-1 { let q = lagrange_polynomial(x[i-1..i+2].to_vec(), y[i-1..i+2].to_vec()); m[i] = q.derivative().eval(x[i]); } m }
true
88b50d7ae5b05b2af3965e5aae974183f58f864b
Rust
makepad/makepad
/draw/vector/bender/tessellator/src/monotone_tessellator.rs
UTF-8
3,987
3.046875
3
[ "MIT" ]
permissive
use bender_arena::Arena; use bender_geometry::mesh::Callbacks; use bender_geometry::{LineSegment, Point}; use std::cmp::Ordering; #[derive(Clone, Debug, Default)] pub struct MonotoneTessellator { monotone_polygon_pool: Vec<MonotonePolygon>, monotone_polygon_arena: Arena<MonotonePolygon>, } impl MonotoneTessellator { pub fn new() -> Self { Self::default() } pub fn start_monotone_polygon(&mut self, index: u16, position: Point) -> usize { let mut monotone_polygon = if let Some(monotone_polygon) = self.monotone_polygon_pool.pop() { monotone_polygon } else { MonotonePolygon::new() }; monotone_polygon.start(index, position); self.monotone_polygon_arena.insert(monotone_polygon) } pub fn finish_monotone_polygon( &mut self, monotone_polygon: usize, index: u16, callbacks: &mut impl Callbacks, ) { let mut monotone_polygon = self.monotone_polygon_arena.remove(monotone_polygon); monotone_polygon.finish(index, callbacks); self.monotone_polygon_pool.push(monotone_polygon); } pub fn push_vertex( &mut self, monotone_polygon: usize, side: Side, index: u16, position: Point, callbacks: &mut impl Callbacks, ) { self.monotone_polygon_arena[monotone_polygon].push_vertex(side, index, position, callbacks); } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum Side { Lower, Upper, } impl Default for Side { fn default() -> Self { Side::Lower } } #[derive(Clone, Debug, Default)] struct MonotonePolygon { side: Side, vertex_stack: Vec<Vertex>, } impl MonotonePolygon { pub fn new() -> Self { Self::default() } pub fn start(&mut self, index: u16, position: Point) { self.vertex_stack.push(Vertex { index, position }); } pub fn finish(&mut self, index: u16, callbacks: &mut impl Callbacks) { let mut vertex_1 = self.vertex_stack.pop().unwrap(); while let Some(vertex_0) = self.vertex_stack.pop() { callbacks.triangle(vertex_0.index, vertex_1.index, index); vertex_1 = vertex_0; } } pub fn push_vertex( &mut self, side: Side, index: u16, position: Point, callbacks: &mut impl Callbacks, ) { if side == self.side { let mut vertex_1 = self.vertex_stack.pop().unwrap(); loop { let vertex_0 = if let Some(vertex_0) = self.vertex_stack.last().cloned() { vertex_0 } else { break; }; match ( LineSegment::new(vertex_0.position, position) .compare_to_point(vertex_1.position) .unwrap(), side, ) { (Ordering::Less, Side::Lower) => break, (Ordering::Equal, _) => break, (Ordering::Greater, Side::Upper) => break, _ => (), }; self.vertex_stack.pop(); callbacks.triangle(vertex_0.index, vertex_1.index, index); vertex_1 = vertex_0; } self.vertex_stack.push(vertex_1); self.vertex_stack.push(Vertex { index, position }); } else { let vertex = self.vertex_stack.pop().unwrap(); let mut vertex_1 = vertex; while let Some(vertex_0) = self.vertex_stack.pop() { callbacks.triangle(vertex_0.index, vertex_1.index, index); vertex_1 = vertex_0; } self.vertex_stack.push(vertex); self.vertex_stack.push(Vertex { index, position }); self.side = side; } } } #[derive(Clone, Copy, Debug)] struct Vertex { index: u16, position: Point, }
true
b57ac65245e5eb1712edc5d7a4f65b57fb1e3153
Rust
keithnoguchi/rustos
/examples/post11.rs
UTF-8
1,710
2.75
3
[]
no_license
//! Writing an [OS] in Rust //! //! [os]: https://os.phil-opp.com #![no_std] #![no_main] #![feature(custom_test_frameworks)] #![test_runner(rustos::test_runner)] #![reexport_test_harness_main = "test_main"] extern crate alloc; extern crate bootloader; extern crate rustos; extern crate x86_64; use alloc::{boxed::Box, rc::Rc, vec, vec::Vec}; use bootloader::{entry_point, BootInfo}; use core::panic::PanicInfo; use rustos::println; entry_point!(start_kernel); fn start_kernel(boot_info: &'static BootInfo) -> ! { println!("Welcome to the real world!"); // Initialize the kernel. rustos::init(); rustos::memory::init(boot_info); // Let's box it on heap! let x = Box::new(41); println!("x={:p}", x); // and then vector! let mut vec = Vec::new(); for i in 0..500 { vec.push(i); } println!("vec at {:p}", vec.as_slice()); // now, a reference counted vector. let reference = Rc::new(vec![1, 2, 3]); let cloned = Rc::clone(&reference); println!("current reference count is {}", Rc::strong_count(&cloned)); core::mem::drop(reference); println!("reference count is {} now", Rc::strong_count(&cloned)); // Long lived many boxes allocation! let long_lived = Box::new(1); for i in 0..rustos::HEAP_SIZE { let x = Box::new(i); assert_eq!(*x, i); } assert_eq!(*long_lived, 1); #[cfg(test)] test_main(); println!("It did not crash!!!"); rustos::hlt_loop(); } #[cfg(not(test))] #[panic_handler] fn panic(info: &PanicInfo) -> ! { println!("{}", info); rustos::hlt_loop(); } #[cfg(test)] #[panic_handler] fn panic(info: &PanicInfo) -> ! { rustos::test_panic_handler(info) }
true
54362a56bf19f6f34f28e86e604b821c095a9863
Rust
qfizik/quizx
/quizx/src/vec_graph.rs
UTF-8
12,555
2.65625
3
[ "Apache-2.0" ]
permissive
// QuiZX - Rust library for quantum circuit rewriting and optimisation // using the ZX-calculus // Copyright (C) 2021 - Aleks Kissinger // // 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. pub use crate::graph::*; use crate::scalar::*; use num::rational::Rational; use std::mem; pub type VTab<T> = Vec<Option<T>>; #[derive(Debug,Clone,PartialEq)] pub struct Graph { vdata: VTab<VData>, edata: VTab<Vec<(V,EType)>>, holes: Vec<V>, // places where a vertex has been deleted inputs: Vec<V>, outputs: Vec<V>, numv: usize, nume: usize, scalar: ScalarN, } impl Graph { /// Explicitly index neighbors of a vertex. Used for iteration. pub fn neighbor_at(&self, v: V, n: usize) -> V { if let Some(d) = &self.edata[v] { d[n].0 } else { 0 } } fn index<U>(nhd: &Vec<(V,U)>, v: V) -> Option<usize> { nhd.iter().position(|&(v0,_)| v == v0) } fn value<U: Copy>(nhd: &Vec<(V,U)>, v: V) -> Option<U> { for (v0,u) in nhd.iter() { if v == *v0 { return Some(*u); } } None } /// Removes vertex 't' from the adjacency map of 's'. This private method /// is used by remove_edge and remove_vertex to make the latter slightly /// more efficient. fn remove_half_edge(&mut self, s: V, t: V) { if let Some(Some(nhd)) = self.edata.get_mut(s) { Graph::index(&nhd,t).map(|i| nhd.swap_remove(i)); } } // Here are some simpler implementations of the vertices and edges functions, // but they can't be moved into the trait because they return "impl" types. // pub fn vertices2(&self) -> impl Iterator<Item=V> + '_ { // self.vdata.iter().enumerate().filter_map(|(v,d)| d.map(|_| v)) // } // pub fn edges2(&self) -> impl Iterator<Item=(V,V,EType)> + '_ { // self.edata // .iter() // .enumerate() // .filter_map(|(v,tab)| match tab { // Some(x) => Some(x.iter().filter_map(move |(v1,et)| // if v <= *v1 { Some((v, *v1, *et)) } else { None } // )), // None => None // }) // .flatten() // } } impl GraphLike for Graph { fn new() -> Graph { Graph { vdata: Vec::new(), edata: Vec::new(), holes: Vec::new(), inputs: Vec::new(), outputs: Vec::new(), numv: 0, nume: 0, scalar: Scalar::one(), } } fn vindex(&self) -> V { self.vdata.len() } fn num_vertices(&self) -> usize { self.numv } fn num_edges(&self) -> usize { self.nume } fn vertices(&self) -> VIter { VIter::Vec(self.numv, self.vdata.iter().enumerate()) } fn edges(&self) -> EIter { EIter::Vec(self.nume, self.edata.iter().enumerate(), None) } fn inputs(&self) -> &Vec<V> { &self.inputs } fn inputs_mut(&mut self) -> &mut Vec<V> { &mut self.inputs } fn set_inputs(&mut self, inputs: Vec<V>) { self.inputs = inputs; } fn outputs(&self) -> &Vec<V> { &self.outputs } fn set_outputs(&mut self, outputs: Vec<V>) { self.outputs = outputs; } fn outputs_mut(&mut self) -> &mut Vec<V> { &mut self.outputs } fn add_vertex(&mut self, ty: VType) -> V { self.add_vertex_with_data(VData { ty, phase: Rational::new(0,1), qubit: 0, row: 0 }) } fn add_vertex_with_data(&mut self, d: VData) -> V { self.numv += 1; if let Some(v) = self.holes.pop() { self.vdata[v] = Some(d); self.edata[v] = Some(Vec::new()); v } else { self.vdata.push(Some(d)); self.edata.push(Some(Vec::new())); self.vdata.len() - 1 } } fn remove_vertex(&mut self, v: V) { self.numv -= 1; self.holes.push(v); self.vdata[v] = None; let adj = mem::take(&mut self.edata[v]).expect("No such vertex."); for (v1,_) in adj { self.nume -= 1; self.remove_half_edge(v1,v); } } fn add_edge_with_type(&mut self, s: V, t: V, ety: EType) { self.nume += 1; // if self.connected(s,t) { panic!("introducing parallel edge!"); } if let Some(Some(nhd)) = self.edata.get_mut(s) { nhd.push((t,ety)); } else { panic!("Source vertex not found"); } if let Some(Some(nhd)) = self.edata.get_mut(t) { nhd.push((s,ety)); } else { panic!("Target vertex not found"); } } fn remove_edge(&mut self, s: V, t: V) { self.nume -= 1; self.remove_half_edge(s,t); self.remove_half_edge(t,s); } fn set_phase(&mut self, v: V, phase: Rational) { if let Some(Some(d)) = self.vdata.get_mut(v) { d.phase = phase.mod2(); } else { panic!("Vertex not found"); } } fn phase(&self, v: V) -> Rational { self.vdata[v] .expect("Vertex not found") .phase } fn add_to_phase(&mut self, v: V, phase: Rational) { if let Some(Some(d)) = self.vdata.get_mut(v) { d.phase = (d.phase + phase).mod2(); } else { panic!("Vertex not found"); } } fn set_vertex_type(&mut self, v: V, ty: VType) { if let Some(Some(d)) = self.vdata.get_mut(v) { d.ty = ty; } else { panic!("Vertex not found"); } } fn vertex_data(&self, v: V) -> VData { self.vdata[v].expect("Vertex not found") } fn vertex_type(&self, v: V) -> VType { self.vertex_data(v).ty } fn set_edge_type(&mut self, s: V, t: V, ety: EType) { if let Some(Some(nhd)) = self.edata.get_mut(s) { let i = Graph::index(&nhd, t).expect("Edge not found"); nhd[i] = (t, ety); } else { panic!("Source vertex not found"); } if let Some(Some(nhd)) = self.edata.get_mut(t) { let i = Graph::index(&nhd, s).expect("Edge not found"); nhd[i] = (s, ety); } else { panic!("Target vertex not found"); } } fn edge_type_opt(&self, s: V, t: V) -> Option<EType> { if let Some(Some(nhd)) = self.edata.get(s) { Graph::value(&nhd, t) } else { None } } fn set_coord(&mut self, v: V, coord: (i32,i32)) { if let Some(Some(d)) = self.vdata.get_mut(v) { d.qubit = coord.0; d.row = coord.1; } else { panic!("Vertex not found") } } fn coord(&mut self, v: V) -> (i32,i32) { let d = self.vdata[v].expect("Vertex not found"); (d.qubit, d.row) } fn set_qubit(&mut self, v: V, qubit: i32) { if let Some(Some(d)) = self.vdata.get_mut(v) { d.qubit = qubit; } else { panic!("Vertex not found") } } fn qubit(&self, v: V) -> i32 { self.vdata[v] .expect("Vertex not found").qubit } fn set_row(&mut self, v: V, row: i32) { if let Some(Some(d)) = self.vdata.get_mut(v) { d.row = row; } else { panic!("Vertex not found") } } fn row(&self, v: V) -> i32 { self.vdata[v] .expect("Vertex not found").row } fn neighbors(&self, v: V) -> NeighborIter { if let Some(Some(nhd)) = self.edata.get(v) { NeighborIter::Vec(nhd.iter()) } else { panic!("Vertex not found") } } fn incident_edges(&self, v: V) -> IncidentEdgeIter { if let Some(Some(nhd)) = self.edata.get(v) { IncidentEdgeIter::Vec(nhd.iter()) } else { panic!("Vertex not found") } } fn degree(&self, v: V) -> usize { if let Some(Some(nhd)) = self.edata.get(v) { nhd.len() } else { panic!("Vertex not found") } } fn scalar(&self) -> &ScalarN { &self.scalar } fn scalar_mut(&mut self) -> &mut ScalarN { &mut self.scalar } fn find_edge<F>(&self, f: F) -> Option<(V,V,EType)> where F : Fn(V,V,EType) -> bool { for (v0, nhd0) in self.edata.iter().enumerate() { if let Some(nhd) = nhd0 { for &(v1, et) in nhd.iter() { if v0 <= v1 && f(v0,v1,et) { return Some((v0,v1,et)); } } }; } None } fn find_vertex<F>(&self, f: F) -> Option<V> where F : Fn(V) -> bool { for (v, d) in self.vdata.iter().enumerate() { if d.is_some() && f(v) { return Some(v); } } None } fn contains_vertex(&self, v: V) -> bool { v < self.vdata.len() && self.vdata[v].is_some() } } #[cfg(test)] mod tests { use super::*; #[test] fn create_empty_graph() { let g = Graph::new(); assert_eq!(g.num_vertices(), 0); assert_eq!(g.num_edges(), 0); } fn simple_graph() -> (Graph,Vec<V>) { let mut g = Graph::new(); let vs = vec![ g.add_vertex(VType::B), g.add_vertex(VType::B), g.add_vertex(VType::Z), g.add_vertex(VType::Z), g.add_vertex(VType::X), g.add_vertex(VType::X), g.add_vertex(VType::B), g.add_vertex(VType::B)]; g.add_edge(vs[0], vs[2]); g.add_edge(vs[1], vs[3]); g.add_edge(vs[2], vs[4]); g.add_edge(vs[2], vs[5]); g.add_edge(vs[3], vs[4]); g.add_edge(vs[3], vs[5]); g.add_edge(vs[4], vs[6]); g.add_edge(vs[5], vs[7]); (g,vs) } #[test] fn create_simple_graph() { let (g,_) = simple_graph(); assert_eq!(g.num_vertices(), 8); assert_eq!(g.num_edges(), 8); } #[test] fn clone_graph() { let (g,_) = simple_graph(); let h = g.clone(); assert!(g.num_vertices() == h.num_vertices()); assert!(g.num_edges() == h.num_edges()); // assert!(g == h); } #[test] fn vertex_iterator() { let (g, mut expected_vs) = simple_graph(); let mut vs: Vec<_> = g.vertices().collect(); vs.sort(); expected_vs.sort(); assert_eq!(expected_vs, vs); } #[test] fn edge_iterator() { let (mut g, vs) = simple_graph(); g.set_edge_type(vs[1], vs[3], EType::H); let mut edges: Vec<_> = g.edges().collect(); let mut expected_edges = vec![ (vs[0], vs[2], EType::N), (vs[1], vs[3], EType::H), (vs[2], vs[4], EType::N), (vs[2], vs[5], EType::N), (vs[3], vs[4], EType::N), (vs[3], vs[5], EType::N), (vs[4], vs[6], EType::N), (vs[5], vs[7], EType::N), ]; edges.sort(); expected_edges.sort(); assert_eq!(expected_edges, edges); } #[test] fn smart_edges_zx() { let mut g = Graph::new(); let vs = [ g.add_vertex(VType::B), g.add_vertex(VType::Z), g.add_vertex(VType::X), g.add_vertex(VType::B)]; g.add_edge(vs[0], vs[1]); g.add_edge(vs[2], vs[3]); let mut h = g.clone(); h.add_edge_smart(vs[1], vs[2], EType::N); h.add_edge_smart(vs[1], vs[2], EType::N); assert_eq!(h.num_vertices(), 4); // assert_eq!(h.num_edges(), 2, // "Wrong edges in NN test: {:?}", // Vec::from_iter(h.edges())); let mut h = g.clone(); h.add_edge_smart(vs[1], vs[2], EType::H); h.add_edge_smart(vs[1], vs[2], EType::H); assert_eq!(h.num_vertices(), 4); // assert_eq!(h.num_edges(), 3, // "Wrong edges in HH test: {:?}", // Vec::from_iter(h.edges())); assert_eq!(h.edge_type(vs[1], vs[2]), EType::H); } }
true
6d61fed75c4bf4b591f8de9d5646e3712e39d51e
Rust
TovarishFin/eth-fabulous
/src/main.rs
UTF-8
2,254
3.1875
3
[]
no_license
use clap::{App, Arg}; use num_cpus; use regex::Regex; fn validate_hexadecimal(arg: String) -> Result<(), String> { let rgx = Regex::new("^[0-9a-fA-F]+$").unwrap(); if rgx.is_match(&arg) { Ok(()) } else { Err(String::from("search param must be hexadecimal")) } } fn validate_processors(arg: String) -> Result<(), String> { let cpus = num_cpus::get(); let cpus_arg; match arg.parse::<usize>() { Ok(result) => cpus_arg = result, Err(_) => return Err(String::from("cpus argument must be a number.")), } match cpus_arg { 0 => Err(format!( "cannot use 0 processors. computer has {} logical processors", cpus )), cpus_arg if cpus_arg > cpus => Err(format!( "cannot use more processors than computer has. computer has {} logical processors.", cpus )), _ => Ok(()), } } fn main() { let matches = App::new("Eth Fabulous") .version("0.1.0") .author("Cody Lamson <tovarishfin@gmail.com>") .about("ethereum vanity address generator") .arg( Arg::with_name("search") .short("s") .long("search") .help("value to search for when trying addresses") .takes_value(true) .required(true) .validator(validate_hexadecimal), ) .arg( Arg::with_name("cpus") .short("c") .long("cpus") .help("number of logical processors to use") .takes_value(true) .required(false) .validator(validate_processors), ) .arg( Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity"), ) .get_matches(); let search = matches.value_of("search").unwrap(); let verbosity = matches.occurrences_of("v"); let cpus = match matches.value_of("cpus") { Some(arg) => arg.parse::<usize>().unwrap(), None => num_cpus::get(), }; if let Err(e) = eth_fabulous::run(search, cpus, verbosity) { eprintln!("Application error: {}", e) } }
true
2fd28ca43a9d33c419b29615df4fcbb91f44cb7d
Rust
ptgamr/learn-rust
/ownership.rs
UTF-8
701
3.96875
4
[]
no_license
fn main() { let s = String::from("hello"); // s comes into scope takes_ownership(s); // s's value moves into the function // ... and no longer valid here let x = 5; // x comes into scope makes_copy(x); // x would move to the function // but i32 is Copy, so it's ok to // still use x afterward println!("After {}", x); // println still works here } fn takes_ownership(some_string: String) { println!("{}", some_string); } fn makes_copy(some_integer: i32) { println!("Makes copy {}", some_integer); }
true
bee8ec417127ed3cad3ba724add83b3ef34902b3
Rust
kamalmarhubi/futures-rs
/src/util.rs
UTF-8
515
2.515625
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::panic::{self, AssertUnwindSafe}; use {PollResult, PollError}; // TODO: reexport this? struct ReuseFuture; pub fn recover<F, R, E>(f: F) -> PollResult<R, E> where F: FnOnce() -> R + Send + 'static { panic::catch_unwind(AssertUnwindSafe(f)).map_err(PollError::Panicked) } pub fn reused<E>() -> PollError<E> { PollError::Panicked(Box::new(ReuseFuture)) } pub fn opt2poll<T, E>(t: Option<T>) -> PollResult<T, E> { match t { Some(t) => Ok(t), None => Err(reused()), } }
true
71a7e149fdded647b9d7781dcb36050879183985
Rust
thecristidima/AdventOfRust
/2020/src/day-13/main.rs
UTF-8
2,592
3.328125
3
[ "MIT" ]
permissive
use modinverse::modinverse; use utils::files::read_lines_iter; fn part_one(timestamp: u64, buses: &Vec<String>) -> u64 { let part_one_buses = buses .iter() .filter(|s| **s != "x") .map(|s| s.parse::<u64>().unwrap()) .collect::<Vec<_>>(); let mut time_to_wait = u64::MAX; let mut best_bus = u64::MIN; for bus in part_one_buses { let leftover = timestamp % bus; if leftover == 0 { best_bus = bus; time_to_wait = 0; break; } if bus - leftover < time_to_wait { time_to_wait = bus - leftover; best_bus = bus; } } best_bus * time_to_wait } fn chinese_remainder_theorem(buses: Vec<(i128, i128)>) -> i128 { let a_s = buses.iter().map(|x| x.0).collect::<Vec<_>>(); let m_s = buses.iter().map(|x| x.1).collect::<Vec<_>>(); let m = m_s.iter().product::<i128>(); let z_s = m_s.iter().map(|m_i| m / m_i).collect::<Vec<i128>>(); let y_s = z_s .iter() .enumerate() .map(|(idx, z_i)| modinverse(*z_i, m_s[idx]).unwrap()) .collect::<Vec<_>>(); let w_s = y_s .iter() .zip(z_s) .map(|(y_i, z_i)| (y_i * z_i) % m) .collect::<Vec<_>>(); a_s.iter() .zip(w_s) .map(|(a_i, w_i)| a_i * w_i) .sum::<i128>() % m } fn part_two(buses: &Vec<String>) -> i128 { let buses = buses .into_iter() .enumerate() .filter(|(_, val)| *val != "x") .map(|(idx, val)| { let modulo = val.parse::<i128>().unwrap(); let remainder = modulo - idx as i128; (remainder, modulo) }) .collect::<Vec<_>>(); chinese_remainder_theorem(buses) } /** * Part 1: * You can leave at $timestamp the earliest and each bus arrives every $busId minutes. * Find the earliest bus you can take and return $busId * $minutesToWait. * * Part 2: * The bus company offers you a challenge. * The first bus arrives at timestamp $t, the second at $t + 1, and so on. * * What is $t? * */ fn main() { let mut file_iter = read_lines_iter("src/day-13/input.txt"); let timestamp = file_iter.next().unwrap().unwrap().parse::<u64>().unwrap(); let buses = file_iter .next() .unwrap() .unwrap() .split(",") .map(|s| String::from(s)) .collect::<Vec<_>>(); println!("Solution for part 1: {}", part_one(timestamp, &buses)); // 246 println!("Solution for part 2: {}", part_two(&buses)); // 939490236001473 }
true
caeb29e35ba3f5aadffd68214b981073e13b8e1d
Rust
SanderHageman/advent_of_code_2020
/src/day07.rs
UTF-8
3,102
3.234375
3
[ "MIT" ]
permissive
use std::collections::HashMap; type TParsed = HashMap<String, TParsedSub>; type TParsedSub = Rule; pub fn day(input: String) -> (usize, usize) { let parsed_input = parse(&input); (part_1(&parsed_input), part_2(&parsed_input)) } fn part_1(input: &TParsed) -> usize { fn has_shiny<'a>((name, rule): &'a (&String, &Rule), input: &TParsed) -> bool { match name.as_str() { "shiny gold" => true, _ => rule .children .iter() .filter_map(|c| input.get_key_value(&c.name)) .any(|r| has_shiny(&r, input)), } } input.iter().filter(|r| has_shiny(r, input)).count() - 1 // exclude shiny gold bag } fn part_2(input: &TParsed) -> usize { fn get_required_bags<'a>(rule: &'a &Rule, input: &TParsed) -> usize { rule.children .iter() .map(|c| (c.qty, input.get(&c.name).unwrap())) .map(|(qty, r)| qty * (get_required_bags(&r, input) + 1)) .sum() } get_required_bags(&input.get("shiny gold").unwrap(), input) } fn parse(input: &str) -> TParsed { use regex::Regex; lazy_static! { static ref NAME: Regex = Regex::new(r"(\w* \w*) bags contain ").unwrap(); static ref CHILD: Regex = Regex::new(r"(?P<qty>\d+) (?P<name>\w* \w*) bag").unwrap(); } let mut result = TParsed::new(); for line in input.lines() { let name = NAME.captures(line).unwrap()[1].to_owned(); let children = CHILD .captures_iter(line) .map(|cap| Req { name: cap["name"].to_owned(), qty: cap["qty"].parse::<usize>().unwrap_or_default(), }) .collect(); result.insert(name.to_owned(), Rule { name, children }); } result } #[derive(Debug)] struct Rule { name: String, children: Vec<Req>, } #[derive(Debug)] struct Req { name: String, qty: usize, } #[test] fn test_example_1() { let input = parse(EXAMPLE_INPUT); assert_eq!(part_1(&input), 4) } #[test] fn test_example_2() { assert_eq!(part_2(&parse(EXAMPLE_INPUT)), 32); assert_eq!(part_2(&parse(EXAMPLE_INPUT2)), 126); } #[cfg(test)] const EXAMPLE_INPUT: &str = "\ light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags."; #[cfg(test)] const EXAMPLE_INPUT2: &str = "\ shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags.";
true
f3932ed2e0ef498ec712ae07633c94ba2424d7aa
Rust
Tsuguri/PSW
/keiro/src/Paths/mod.rs
UTF-8
34,099
2.75
3
[]
no_license
use Data; use Math::Vector::Vector2; use Math::Vector::Vector3; fn move_tool( result: &mut Vec<Vector3<f32>>, j: i32, previous: i32, y: &mut i32, h: f32, g: &Fn(i32, i32) -> f32, floorOffset: f32, up: &mut bool, yToWorld: &Fn(i32) -> f32, xToWorld: &Fn(i32) -> f32, height: i32, width: i32, step: u32, swap: bool, ) { let mut x: i32 = j; if x >= width { x = width - 1; } let xScene = xToWorld(x); println!("generating row {} at {} pixel with X: {}", j, y, xScene); let mut points: Vec<(i32, i32)> = vec![]; points.push((x, *y)); let mut prev = *y; loop { if *up { *y += 1; } else { *y -= 1; } if *y >= height { *y = height - 1; points.push((x, *y)); break; } if *y < 0 { *y = 0; points.push((x, *y)); //println!("y below 0"); break; } let ch = g(x, *y); if (ch != h) { //println!("not equal with: {}, {}", ch, h); points.push((x, prev)); for step in 1..step { //println!("prev: {}, next: {}", previous, j); let md: i32 = if previous < j as i32 { 1 } else { -1 }; let pt: i32 = x + (step as i32) * md as i32; if pt >= width { break; } // znalezienie najblizszej obok let mut found = false; let hh = g(pt, *y) == h; for i in 1..1000 { if *y + i < height { let hp = g(pt, *y + i); if *y + i < height && ((!hh && hp == h && !*up) || (hh && hp != h && *up)) { // jest ok w strone rufy found = true; *y = *y + i - (if *up { 1 } else { 0 }); points.push((pt, *y)); //println!("y option 1"); break; } } else { if *up { found = true; *y = height - 1; points.push((pt, *y)); //println!("y option 2"); break; } } if *y - i >= 0 { let hd = g(pt, *y - i); if *y - i >= 0 && ((hh && hd != h && !*up) || (!hh && hd == h && *up)) { //jest ok w strone rufy found = true; *y = *y - i + (if *up { 0 } else { 1 }); points.push((pt, *y)); //println!("y option 3"); break; } } else { if !*up { found = true; *y = 0; points.push((pt, *y)); //println!("y option 4"); break; } } } if (!found) { points.push((pt, *y)); println!("finished by panic at {}, {}!", pt, *y); break; } } // tutaj przechodzenie na sciezke obok break; } prev = *y; } *up = !*up; if swap { for pt in &mut points { std::mem::swap(&mut pt.0, &mut pt.1); } } // filter points let pts: Vec<Vector3<f32>> = points .iter() .map(|pt| Vector3::<f32>::new(xToWorld(pt.0), yToWorld(pt.1), floorOffset + h)).collect(); let mut prev = pts.first().unwrap().clone(); let last = pts.last().unwrap().clone(); let mut ptss = vec![]; ptss.push(prev); for pt in pts { if (pt-prev).len_squared() > 0.09 { prev = pt; ptss.push(pt); } } ptss.push(last); result.extend(ptss); } enum FilterMode { Equal, NotEqual, Less, More } fn select_scale(v: f32, mv: f32,scale: bool) -> Box<Fn(f32)->f32>{ match scale { true => Box::new(move |x| (x-mv)*v/(v+1.0)), false => Box::new(move |x| x - mv) } } fn generate_bool_map( uRes: i32, vRes: i32, result: &mut [bool], u: u32, v: u32, path: &[Vector2<f32>], inv: FilterMode, mv: f32, scale:bool ) -> Vec<i32>{ if (uRes * vRes) as usize != result.len() { panic!("wut!"); } let sc = select_scale(v as f32,mv, scale); let mut data = vec![0i32; result.len()]; { let mut set = |x: i32, y: i32, val: i32| { data[(x * vRes + y) as usize] += val; }; let mut p = path.to_vec(); p.push(path[0]); for i in 0..(p.len() - 1) { let from = p[i].clone(); let to = p[i + 1].clone(); let up = from[0] > to[0]; let fu = from[0] / (u as f32) * uRes as f32; let tu = to[0] / (u as f32) * uRes as f32; let pfu = f32::ceil(fu) as i32; let ptu = f32::ceil(tu) as i32; //let pfu = (if !up { f32::floor(fu)} else { f32::ceil(fu)}) as i32; //let ptu = (if !up { f32::floor(tu)} else { f32::ceil(tu)}) as i32; //println!("fu: {}, tu: {}, pfu: {}, ptu: {}", fu, tu, pfu, ptu); if pfu == ptu { continue; } if (from[0] - to[0]).abs() > 0.8 { let i = 0i32; let i2 = uRes-1; let h = sc((from[1] + to[1]) / 2.0); let ph = h / (v as f32) * vRes as f32; //println!("-----from: {}, to: {}, up to: {}", pfu, ptu, ph); for j in 0..vRes { if (j as f32) < ph { set(i, j, if !up { 1 } else { -1 }); set(i2, j, if !up { 1 } else { -1 }); } else { set(i, j, if !up { -1 } else { 1 }); set(i2, j, if !up { -1 } else { 1 }); } } continue; } let f = if up { ptu } else { pfu }; let t = if up { pfu } else { ptu }; //println!("from: {}, to: {}", f, t); for i in (f..t) { let ru = (i as f32) / (uRes as f32) * (u as f32); let inter = (ru - from[0]) / (to[0] - from[0]); let rv = sc((to[1] - from[1]) * inter + from[1]); let pv = rv / (v as f32) * vRes as f32; for j in 0..vRes { if (j as f32) < pv { set(i, j, if up { 1 } else { -1 }); } else { set(i, j, if up { -1 } else { 1 }); } } } } } let cl = select(inv); for i in 0..result.len() { if cl(data[i]) { result[i] = false; } } data } fn select(inv: FilterMode) -> Box<Fn(i32) -> bool> { match inv { FilterMode::Less => Box::new(|x| x<0), FilterMode::More => Box::new(|x|x>0), FilterMode::Equal => Box::new(|x| x==0), FilterMode::NotEqual => Box::new(|x| x!=0), } } fn generate_height_map( result: &mut [bool], u: i32, v: i32, surface: &Data::Surface, toolRadius: f32, ) { for up in 0..u { for vp in 0..v { let uc = (surface.u as i32 * up) as f32 / (u as f32); let vc = (surface.v as i32 * vp) as f32 / (v as f32); let q = surface.eval_dist(uc, vc, toolRadius); if q.y() < toolRadius { result[(up * v + vp) as usize] = false; } } } } fn generate_generic_details( surface: &Data::Surface, uRes: i32, vRes: i32, map: &[bool], toolRadius: f32, us: impl Iterator<Item = i32>, f: i32, t: i32, up_by: f32, ) -> Vec<Vector3<f32>> { let value = |up: i32, vp: i32| map[(up * vRes + vp) as usize]; let mut result = vec![]; for u in us { let rev = u % 2 == 0; for v in 1..(t - f) { let val = if rev { t - v } else { f + v }; if !value(u, val) { continue; } let uc = (surface.u as i32 * u) as f32 / (uRes as f32); let vc = (surface.v as i32 * val) as f32 / (vRes as f32); //println!("uv: {}, uv: {}", uc, vc); let q = surface.eval_dist(uc, vc, toolRadius); result.push(q); } } // add up if far enough let mut res2 = Vec::with_capacity(result.len()); if result.len() > 0 { for i in 0..(result.len() - 1) { let from = &result[i]; let to = &result[i + 1]; res2.push(*from); if (*to - *from).len_squared() > 0.08 { res2.push(Vector3::new(from.x(), from.y() + up_by, from.z())); res2.push(Vector3::new(to.x(), to.y() + up_by, to.z())); } res2.push(*to); } } res2 } fn generate_gatling_details( gatling: &Data::Surface, gatling_wing: &[Vector2<f32>], toolRadius: f32, ) -> Vec<Vector3<f32>> { let uRes: i32 = 40; let vRes: i32 = 60; let mut map = vec![true; (uRes * vRes) as usize]; generate_height_map(&mut map, uRes, vRes, gatling, toolRadius); generate_bool_map( uRes, vRes, &mut map, gatling.u, gatling.v, gatling_wing, FilterMode::More, 0.0, true ); generate_generic_details( gatling, uRes, vRes, &map, toolRadius, 0..uRes, 0, vRes / 2, 0.5, ) } fn generate_cockpit_details( cockpit: &Data::Surface, from_cockpit: &[Vector2<f32>], toolRadius: f32, ) -> Vec<Vector3<f32>> { let uRes: i32 = 80; let vRes: i32 = 180; let mut map = vec![true; (uRes * vRes) as usize]; generate_bool_map( uRes, vRes, &mut map, cockpit.u, cockpit.v, from_cockpit, FilterMode::Equal, 0.37, true ); generate_generic_details( cockpit, uRes, vRes, &map, toolRadius, ((uRes * 2/3)..uRes).chain(0..uRes / 3), 0, vRes / 2, 0.5, ) } fn generate_fin_details( cockpit: &Data::Surface, constraints: [&[Vector2<f32>];2], toolRadius: f32, ) -> Vec<Vector3<f32>> { let uRes: i32 = 80; let vRes: i32 = 120; let mut map = vec![true; (uRes * vRes) as usize]; generate_bool_map(uRes, vRes, &mut map, cockpit.u, cockpit.v, constraints[0], FilterMode::NotEqual, -0.4,true); generate_bool_map(uRes, vRes, &mut map, cockpit.u, cockpit.v, constraints[1], FilterMode::Less, 0.0, true); generate_generic_details( cockpit, uRes, vRes, &map, toolRadius, ((uRes / 2+10)..uRes).chain(0..uRes / 3-7), vRes / 2, vRes-4, 1.0, ) } fn generate_left_wing_details( wing: &Data::Surface, constraints: [&[Vector2<f32>]; 3], toolRadius: f32, ) -> Vec<Vector3<f32>> { let uRes: i32 = 120; let vRes: i32 = 180; let mut map = vec![true; (uRes * vRes) as usize]; generate_height_map(&mut map, uRes, vRes, wing, toolRadius); // gatling generate_bool_map(uRes, vRes, &mut map, wing.u, wing.v, constraints[0], FilterMode::Less, 0.3, true); // hull generate_bool_map(uRes, vRes, &mut map, wing.u, wing.v, constraints[1], FilterMode::Less, 0.1, true); // fin generate_bool_map(uRes, vRes, &mut map, wing.u, wing.v, constraints[2], FilterMode::Less, 0.1, true); generate_generic_details(wing, uRes, vRes, &map, toolRadius, ((uRes/2-5)..uRes), 0, vRes/2, 0.5) } fn generate_right_wing_details( wing: &Data::Surface, constraints: [&[Vector2<f32>]; 2], toolRadius: f32, ) -> Vec<Vector3<f32>> { let uRes: i32 = 120; let vRes: i32 = 220; let mut map = vec![true; (uRes * vRes) as usize]; generate_height_map(&mut map, uRes, vRes, wing, toolRadius); // hull generate_bool_map(uRes, vRes, &mut map, wing.u, wing.v, constraints[0], FilterMode::Less, -0.03, true); // fin generate_bool_map(uRes, vRes, &mut map, wing.u, wing.v, constraints[1], FilterMode::Less, -0.1, true); generate_generic_details(wing, uRes, vRes, &map, toolRadius, ((uRes/2-5)..uRes), vRes/2, vRes, 0.4) } fn generate_hull_details( hull: &Data::Surface, constraints: [&[Vector2<f32>]; 3], toolRadius: f32, ) -> Vec<Vector3<f32>> { let uRes: i32 = 100; let vRes: i32 = 220; let mut map = vec![true; (uRes * vRes) as usize]; generate_height_map(&mut map, uRes, vRes, hull, toolRadius); // fin? generate_bool_map(uRes, vRes, &mut map, hull.u, hull.v, constraints[0], FilterMode::More, 0.0, true); // cockpit generate_bool_map(uRes, vRes, &mut map, hull.u, hull.v, constraints[1], FilterMode::More, 0.5,false ); // wings generate_bool_map(uRes, vRes, &mut map, hull.u, hull.v, constraints[2], FilterMode::More, -0.1, true); generate_generic_details( hull, uRes, vRes, &map, toolRadius, (0..(uRes / 2)).rev().chain(((uRes / 2)..uRes).rev()), vRes / 6, vRes * 77 / 100, 1.0, ) } fn generate_front_details( hull: &Data::Surface, toolRadius: f32 )->Vec<Vector3<f32>> { let uRes: i32 = 60; let vRes: i32 = 120; let mut map = vec![true; (uRes * vRes) as usize]; generate_height_map(&mut map, uRes, vRes, hull, toolRadius); generate_generic_details( hull, uRes, vRes, &map, toolRadius, (0..(uRes / 2)).rev().chain(((uRes / 2)..uRes).rev()), vRes/20, vRes/7, 1.0, ) } pub fn generate_details( l: f32, r: f32, b: f32, u: f32, floorOffset: f32, materialHeight: f32, toolRadius: f32, start: (f32, f32, f32), map: glium::texture::RawImage2d<u8>, d: &Data::Scene, ) -> Vec<Vector3<f32>> { // 0 -> gatling // 1 -> body // 2 -> cockpit // 3 -> wings let gatling = &d.surfaces[0]; let body = &d.surfaces[1]; let cockpit = &d.surfaces[2]; let wings = &d.surfaces[3]; let width = map.width as i32; let height = map.height as i32; let image = map.data.into_owned(); let data: Vec<u8> = image.into_iter().step_by(4).collect(); let data: Vec<f32> = data .iter() .map(|x| (1.0 - (*x as f32) / 255.0) * 10.0) .collect(); let sceneWidth = r - l; let sceneLength = u - b; let xToWorld = |x: i32| ((x as f32) / (width as f32 - 1.0) * 1.04 - 0.02) * sceneWidth + l; let xFromWorld = |x: f32| { (((x - l) / sceneWidth + 0.02) / 1.04 * (width as f32 - 1.0)) as i32; }; let yToWorld = |y: i32| ((y as f32) / (height as f32 - 1.0) * 1.04 - 0.02) * sceneLength + b; let yFromWorld = |y: f32| { (((y - b) / sceneLength + 0.02) / 1.04 * (height as f32 - 1.0)) as i32; }; let g = |px: i32, py: i32| data[(py * width + px) as usize]; let mut result = vec![]; result.push(Vector3::new(start.0, start.2, start.1)); result.push(Vector3::new(1.0, 5.0, 8.0)); result.push(Vector3::new(1.0, floorOffset + 0.5, 8.0)); // curve: 5 albo 6 result.extend(generate_left_wing_details( wings, [&d.curves[1], &d.curves[3], &d.curves[9]], toolRadius, )); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); result.push(Vector3::new(-7.0, 5.0, 6.0)); result.extend(generate_right_wing_details( wings, [&d.curves[3], &d.curves[9]], toolRadius, )); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); result.push(Vector3::new(-2.0, 5.0, -6.0)); result.push(Vector3::new(-2.0, 0.5, -6.0)); result.extend(generate_front_details(body,toolRadius)); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); result.push(Vector3::new(-2.0, 5.0, 0.0)); result.push(Vector3::new(-2.0, 0.5, 0.0)); result.extend(generate_hull_details(body, [&d.curves[6], &d.curves[4], &d.curves[2]],toolRadius)); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); result.push(Vector3::new(1.0, 5.0, -4.0)); result.push(Vector3::new(1.0, 4.0, -4.0)); result.extend(generate_cockpit_details(cockpit, &d.curves[5], toolRadius)); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); result.push(Vector3::new(1.0, 5.0, 8.0)); result.push(Vector3::new(1.0, 3.5, 8.0)); result.extend(generate_fin_details(cockpit, [&d.curves[8], &d.curves[7]], toolRadius)); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); result.push(Vector3::new(6.0, 5.0, 0.0)); result.push(Vector3::new(6.0, 0.2, 0.0)); result.extend(generate_gatling_details(gatling, &d.curves[0], toolRadius)); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); result.push(Vector3::new(4.8, 1.0, 1.5)); // gatling-skrzydlo let len = d.curves[0].len(); let cur = &d.curves[0]; for pt in (len*34/100)..(len*13/20) { result.push(gatling.eval_dist(cur[pt][0], cur[pt][1]-0.5, toolRadius)); } let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 3.0, lst.z())); result.push(Vector3::new(0.0, 5.0, -1.0)); result.push(Vector3::new(0.0, 3.0, -1.0)); // kokpit - kadłub let len = d.curves[4].len(); let cur = &d.curves[4]; for pt in (0)..(len) { result.push(body.eval_dist(cur[pt][0], cur[pt][1]-0.5, toolRadius)); } let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 3.0, lst.z())); result.push(Vector3::new(3.0, 3.0, -0.5)); // skrzydlo - kadlub - fin - kadlub - prawe skrzydlo let cur = &d.curves[2]; let len = cur.len(); // lewe skrzydlo -> kadlub for pt in ((len*99/100)..(len)).chain((0)..(len*106/1000)) { result.push(body.eval_dist(cur[pt][0], cur[pt][1]-0.5, toolRadius)); } let cur = &d.curves[6]; let len = cur.len(); for pt in ((len*95/100)..(len)).chain((0)..(len/3)) { result.push(body.eval_dist(cur[pt][0], cur[pt][1]-0.5, toolRadius)); } let cur = &d.curves[2]; let len = cur.len(); for pt in (len*185/1000)..(len*305/1000) { result.push(body.eval_dist(cur[pt][0], cur[pt][1]-0.5, toolRadius)); } let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 3.0, lst.z())); result.push(Vector3::new(3.0, 3.0, 1.0)); // up bo koniec dużego szwu // teraz skrzydla-kokpit let cur = &d.curves[9]; let len = cur.len(); for pt in (len*2/100)..(len*31/100) { result.push(wings.eval_dist(cur[pt][0], cur[pt][1]-0.5, toolRadius)); } let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); let get = |surf: &Data::Surface, u, v, rad| { let p = surf.evaluate(u as f32, v as f32-0.5); let p2 = surf.evaluate(u as f32-0.05, v as f32-0.5); let p3 = surf.evaluate(u as f32+0.05, v as f32-0.5); let p4 = surf.evaluate(u as f32, v as f32-0.55); let p5 = surf.evaluate(u as f32, v as f32-0.45); let du = (p3-p2)* 10.0; let dv = (p5-p4)* 10.0; let n = Vector3::<f32>::cross(&du,&dv).normalized() * rad; //let n = (( p3 + p2 - p*2.0)*0.5).normalized()*rad; let g = p+n; g }; let mut rr = vec![]; let u = cockpit.u as f32 - 1.0; for i in 140..190 { //result.push(cockpit.evaluate(u, i as f32 / 100.0 * cockpit.v as f32)); let g = get(cockpit, u, i as f32 / 200.0 * cockpit.v as f32, toolRadius); rr.push(Vector3::new(0.0, g.y(), g.z())); } let f = rr[0]; result.push(Vector3::new(f.x(), 5.0, f.z()-0.5)); result.push(Vector3::new(f.x(), f.y(), f.z()-0.5)); result.extend(rr.iter()); drop(rr); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); let mut rr = vec![]; let v = wings.v as f32 - 3.5; for i in 130..150 { let g = get(wings, i as f32 / 200.0 * wings.u as f32, v, toolRadius); rr.push(g); } let f = rr[0]; result.push(Vector3::new(f.x(), 5.0, f.z()+0.5)); result.push(Vector3::new(f.x(), f.y(), f.z()+0.5)); result.extend(rr.iter()); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); let mut rr = vec![]; let v = 4.0; for i in (135..198).chain(2..25) { let g = get(body, i as f32 / 200.0 * body.u as f32, v, toolRadius); rr.push(g); } let f = rr[0]; result.push(Vector3::new(f.x()+0.5, 5.0, f.z())); result.push(Vector3::new(f.x()+0.5, toolRadius+0.01, f.z())); result.extend(rr.iter()); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); let flag = true; for elem in &mut result { let tmp = *elem; if flag { *elem = Vector3::new( tmp.x(), tmp.z(), f32::max(floorOffset + tmp.y() - toolRadius, floorOffset), ); } else { *elem = Vector3::new(tmp.x(), tmp.y(), tmp.z()); } } let mut prev = result.first().unwrap().clone(); let last = result.last().unwrap().clone(); let mut ptss = vec![]; ptss.push(prev); for pt in result{ if (pt-prev).len_squared() > 0.01 { prev = pt; ptss.push(pt); } } ptss.push(last); ptss } fn parallel_contour(pts: &[Vector3<f32>], ind: impl Iterator<Item = i32>, rad: f32){ let mut result :Vec<Vector3<f32>>= vec![]; let mut prev = None; for i in ind { match prev { None => { prev = Some(pts[i as usize]); }, Some(pt) => { } } } } pub fn generate_contour( l: f32, r: f32, b: f32, u: f32, floorOffset: f32, materialHeight: f32, toolRadius: f32, start: (f32, f32, f32), cuts: &Data::Scene, scene: &Data::Scene ) -> Vec<Vector3<f32>> { let gatling = &scene.surfaces[0]; let body = &scene.surfaces[1]; let cockpit = &scene.surfaces[2]; let wings = &scene.surfaces[3]; let mut result = vec![]; let wingsBack = &cuts.curves[1]; let wingsFront = &cuts.curves[3]; let gatlingCut = &cuts.curves[4]; let hullBack = &cuts.curves[6]; let hullFront = &cuts.curves[8]; result.push(Vector3::new(start.0, start.2, start.1)); result.push(Vector3::new(-8.0, 5.0, 5.5)); result.push(Vector3::new(-8.0, 0.0, 5.5)); let get = |surf: &Data::Surface, u, v, rad| { let p = surf.evaluate(u as f32, v as f32-0.5); let p = Vector3::new(p.x(), 0.0, p.z()); let n = surf.normal(u as f32, v as f32-0.5); let n = Vector3::new(n.x(), 0.0, n.z()).normalized() * rad; p+n }; for elem in wingsBack.iter().skip(25) { result.push(get(wings, elem[0], elem[1], toolRadius)); } let p = result.last().unwrap().clone(); let pp = result[result.len()-2].clone(); result.push(p + (p-pp).normalized()); for elem in wingsFront.iter().take(386) { result.push(get(wings, elem[0], elem[1], toolRadius)); } let p = result.last().unwrap().clone(); let pp = result[result.len()-2].clone(); result.push(p + (p-pp).normalized()*0.5); for elem in wingsFront.iter().skip(440).take(140) { result.push(get(wings, elem[0], elem[1], toolRadius)); } let mut rr = vec![]; for elem in gatlingCut.iter().rev().skip(40).take(70) { rr.push(get(gatling, elem[0], elem[1], toolRadius)); } result.extend(rr.iter().rev()); drop(rr); let p = result.last().unwrap().clone(); let pp = result[result.len()-2].clone(); result.push(p + (p-pp).normalized()*0.6); let mut rr = vec![]; for elem in gatlingCut.iter().take(10) { rr.push(get(gatling, elem[0], elem[1], toolRadius)); } let p = rr[0].clone(); let pp = rr[1].clone(); result.push(p + (p-pp).normalized()*0.6); result.extend(rr.iter().rev()); drop(rr); for elem in wingsFront.iter().skip(720).take(200) { result.push(get(wings, elem[0], elem[1], toolRadius)); } let mut rr = vec![]; for elem in hullBack.iter().take(485) { rr.push(get(body, elem[0], elem[1], toolRadius)); } result.extend(rr.iter().rev()); drop(rr); let p = result.last().unwrap().clone(); let pp = result[result.len()-2].clone(); result.push(p + (p-pp).normalized()*0.5); for elem in hullFront.iter().rev() { result.push(get(body, elem[0], elem[1], toolRadius)); } let p = result.last().unwrap().clone(); let pp = result[result.len()-2].clone(); result.push(p + (p-pp).normalized()*0.4); for elem in hullBack.iter().rev().take(540) { result.push(get(body, elem[0], elem[1], toolRadius)); } for elem in wingsFront.iter().skip(1280).take(500) { result.push(get(wings, elem[0], elem[1], toolRadius)); } let p = result.last().unwrap().clone(); let pp = result[result.len()-2].clone(); result.push(p + (p-pp).normalized()*0.4); let mut rr = vec![]; for elem in (50..92) { rr.push(get(wings, elem as f32 / 100.0 * wings.u as f32, wings.v as f32 - 0.01, toolRadius)); } result.extend(rr.iter().rev()); drop(rr); let p = result.last().unwrap().clone(); let pp = result[result.len()-2].clone(); result.push(p + (p-pp).normalized()*0.4); let lst = result.last().unwrap().clone(); result.push(Vector3::new(lst.x(), 5.0, lst.z())); let flag = true; for elem in &mut result { let tmp = *elem; if flag { *elem = Vector3::new( tmp.x(), tmp.z(), //f32::max(floorOffset + tmp.y(), floorOffset), floorOffset+tmp.y(), ); } else { *elem = Vector3::new(tmp.x(), tmp.y(), tmp.z()); } } let mut prev = result.first().unwrap().clone(); let last = result.last().unwrap().clone(); let mut ptss = vec![]; ptss.push(prev); for pt in result{ if (pt-prev).len_squared() > 0.01 { prev = pt; ptss.push(pt); } } ptss.push(last); ptss.push(Vector3::new(start.0, start.1, start.2)); ptss } pub fn generate_flat( l: f32, r: f32, b: f32, u: f32, floorOffset: f32, materialHeight: f32, toolRadius: f32, start: (f32, f32, f32), map: glium::texture::RawImage2d<u8>, ) -> Vec<Vector3<f32>> { let width = map.width as i32; let height = map.height as i32; let image = map.data.into_owned(); let data: Vec<u8> = image.into_iter().step_by(4).collect(); let data: Vec<f32> = data .iter() .map(|x| (1.0 - (*x as f32) / 255.0) * 10.0) .collect(); let sceneWidth = r - l; let sceneLength = u - b; let xToWorld = |x: i32| ((x as f32) / (width as f32 - 1.0) * 1.06 - 0.03) * sceneWidth + l; let yToWorld = |y: i32| ((y as f32) / (height as f32 - 1.0) * 1.06 - 0.03) * sceneLength + b; let rows = ((r - l) / (1.8 * toolRadius)).ceil() as u32; let step = (map.width as f32 / rows as f32).floor() as u32-9; println!("will make {} rows with step {}", rows, step); let mut result = vec![]; result.push(Vector3::new(start.0, start.1, start.2)); result.push(Vector3::new(-8.5, -8.5, materialHeight + 0.1)); result.push(Vector3::new(-8.5, -8.5, floorOffset)); /*println!("x0 = {}", xToWorld(0)); println!("x0 = {}", xToWorld((width-1) as u32)); */ // tutaj generowanie plaskich sciezek let mut up = true; let mut y: i32 = 0; let g = |px: i32, py: i32| data[(py * width + px) as usize]; let h = g(0, 0); // to jest docelowa wartosc wszedzie gdzie wchodzimy let mut prev: i32 = -1; for i in 0..(rows + 1) { move_tool( &mut result, (i * step + 15) as i32, prev * (step as i32) + 15, &mut y, h, &g, floorOffset, &mut up, &yToWorld, &xToWorld, height, width, step, false, ); prev = i as i32; } up = false; for i in (0..(rows+1)).rev() { move_tool( &mut result, (i * step) as i32, prev * (step as i32), &mut y, h, &g, floorOffset, &mut up, &yToWorld, &xToWorld, height, width, step, false, ); prev = i as i32; } let p = *result.last().unwrap(); result.push(Vector3::new(p.x(), p.y(), materialHeight + 1.0)); result.push(Vector3::new(start.0, start.1, start.2)); println!("generated {} points", result.len()); result } pub fn generate_rough( l: f32, r: f32, b: f32, u: f32, floorOffset: f32, materialHeight: f32, toolRadius: f32, start: (f32, f32, f32), map: glium::texture::RawImage2d<u8>, ) -> Vec<Vector3<f32>> { let width = map.width; let height = map.height; let image = map.data.into_owned(); let data: Vec<u8> = image.into_iter().step_by(4).collect(); let data: Vec<f32> = data .iter() .map(|x| (1.0 - (*x as f32) / 255.0) * 10.0) .collect(); let sceneWidth = r - l; let sceneLength = u - b; println!("first: {}", data[0]); let xToWorld = |x: u32| (x as f32 / width as f32) * sceneWidth + l; let yToWorld = |y: u32| (y as f32 / height as f32) * sceneLength + b; let rows = ((r - l) / (1.1 * toolRadius)).ceil() as u32; let step = (map.width as f32 / rows as f32).floor() as u32; println!("generating {} rows", rows); let mut result = vec![]; let mut upperResult = vec![]; upperResult.push(Vector3::new(start.0, start.1, start.2)); upperResult.push(Vector3::new(-8.0, -8.0, 6.0)); result.push(Vector3::new(-8.0, -8.0, 6.0)); // generate from starto to (l,b) here // dolna warstwa for i in 0..(rows + 1) { let mut x = (i * step); if x >= width { x = width - 1; } let x = x; let xScene = (i * step) as f32 / (width as f32) * sceneWidth + l; println!("generating row {} at {} pixel with X: {}", i, x, xScene); let mut points = vec![]; let mut upperPoints = vec![]; let mut prev = 0; let g = |y: u32| data[(y * width + x) as usize]; let upper_g = |y: u32| f32::max(2.3, data[(y * width + x) as usize]); let mut prevPt = g(0); let mut upperPrev = upper_g(0); // starting point of pass points.push((x, 0)); upperPoints.push((x, 0)); for j in (10..height).step_by(6) { let h = g(j); let h2 = upper_g(j); if (h != prevPt) { points.push((x, j)); } if (h2 != upperPrev) { upperPoints.push((x, j)); } prev = j; prevPt = h; upperPrev = h2; } points.push((x, height - 1)); upperPoints.push((x, height - 1)); if i % 2 == 0 { result.extend(points.iter().map(|pt| { Vector3::<f32>::new( xToWorld(pt.0), yToWorld(pt.1), floorOffset + g(pt.1) - toolRadius, ) })); upperResult.extend(upperPoints.iter().map(|pt| { Vector3::<f32>::new( xToWorld(pt.0), yToWorld(pt.1), floorOffset + upper_g(pt.1) - toolRadius, ) })); } else { result.extend(points.iter().rev().map(|pt| { Vector3::<f32>::new( xToWorld(pt.0), yToWorld(pt.1), floorOffset + g(pt.1) - toolRadius, ) })); upperResult.extend(upperPoints.iter().rev().map(|pt| { Vector3::<f32>::new( xToWorld(pt.0), yToWorld(pt.1), floorOffset + upper_g(pt.1) - toolRadius, ) })); }; } result.push(Vector3::new(8.0, 8.0, 6.0)); result.push(Vector3::new(-8.0, -8.0, 6.0)); result.push(Vector3::new(start.0, start.1, start.2)); upperResult.push(Vector3::new(8.0, 8.0, 6.0)); println!("upper: {}, lower: {}", upperResult.len(), result.len()); upperResult.extend(result.iter()); let mut prev = upperResult.first().unwrap().clone(); let last = upperResult.last().unwrap().clone(); let mut ptss = vec![]; ptss.push(prev); for pt in upperResult { if (pt-prev).len_squared() > 0.09 { prev = pt; ptss.push(pt); } } ptss.push(last); println!("Result size: {}", ptss.len()); ptss }
true
bce98dae7b781a8d88ebd050cd9270ebe8bc39a3
Rust
Keksoj/suivre_le_rust_book
/04_Ownership/borrowing/src/main.rs
UTF-8
1,387
3.625
4
[]
no_license
// 2019-01-01 // On veut à nouveau calculer la longueur d'une chaine de caractères. // Seulement, on va chercher à ne pas prendre l'ownership de la variable. // Pour agrémenter le game, j'ai rajouté une invite à l'utilisateur. // importer la bibliothèque entrée/sortie use std::io; fn main() { println!("Tapez une chaîne de caractères !"); // Définir la variable s1 comme une chaîne de caractères let mut s1 = String::new(); // récupérer l'entrée tapée par l'utilisateur dans la variable s1 io::stdin() .read_line(&mut s1) .expect("Pas pu lire l'entrée"); // Ici il faut encore nettoyer la variable pour enlever le retour à la ligne. // Appel de la fonction calcule_longueur() let len = calcule_longueur(&s1); println!("La longueur de la chaîne '{}' est de {} caractères.", s1, len); } // Contrairement au programme ownership_length, on ne renvoie pas la variable. // La variable n'est qu'empruntée. // L'input est défini entre parenthèse. Il s'appelle s, c'est une chaîne. // L'ampersand fait de s une RÉFÉRENCE qui pointera vers s1 // L'output est un entier positif. usize signifie u64 pour une archi 64 bits fn calcule_longueur(s: &String) -> usize { // la fonction len() calcule et retourne la longueur de s s.len() } // On sort du scope, s est dropé, mais pas s1
true
4d59e4d0100ea64b93af5fba5c9c6d9a6905e0e0
Rust
emanon-was/wip-rust
/src/pound/cfg/service/session.rs
UTF-8
1,102
3.109375
3
[]
no_license
use pound::cfg::Block; use pound::fmt::Decode; use pound::fmt::Indent; #[allow(dead_code)] pub enum Session { Kind(SessionKind), ID(String), TTL(i32), } #[allow(dead_code)] pub enum SessionKind { IP, Basic, URL, Params, Cookie, Header, } impl Decode for SessionKind { fn decode(&self) -> String { match &self { SessionKind::IP => "IP", SessionKind::Basic => "BASIC", SessionKind::URL => "URL", SessionKind::Params => "PARM", SessionKind::Cookie => "COOKIE", SessionKind::Header => "HEADER", }.to_string() } } impl Decode for Session { fn decode(&self) -> String { match &self { Session::Kind(t) => format!("Type\t{}", t.decode()), Session::ID(s) => format!("ID\t{}", s.decode()), Session::TTL(i) => format!("TTL\t{}", i.decode()), } } } impl Decode for Block<Session> { fn decode(&self) -> String { let Block(v) = self; return format!("Session\n{}\nEnd", v.decode().indent()); } }
true
fcc7176e8e8fe9af1b803dca76a80da5a30db0d3
Rust
plzhang4321/os_summer
/LearningRust/src/sword_09.rs
UTF-8
909
3.25
3
[]
no_license
#[derive(Default)] struct CQueue { q: Vec<i32>, k: Vec<i32>, } impl CQueue { fn new() -> Self { Default::default() } fn append_tail(&mut self, value: i32) { self.q.push(value); } fn delete_head(&mut self) -> i32 { match self.k.pop() { Some(n) => n, None => { self.q.reverse(); self.k.append(&mut self.q); self.k.pop().unwrap_or(-1) } } } } // python3 //class CQueue: // def __init__(self): // self.A = [] // self.B = [] // // def appendTail(self, value: int) -> None: // self.A.append(value) // // def deleteHead(self) -> int: // if self.B: // return self.B.pop() // if not self.A: // return -1 // while self.A: // self.B.append(self.A.pop()) // return self.B.pop()
true
d089f84a6aa5c4e91575207133bf29c1bae267d4
Rust
truelossless/crocolang
/src/crocoi/node/multiplicate_node.rs
UTF-8
771
2.609375
3
[ "MIT" ]
permissive
use crate::{ ast::node::MultiplicateNode, crocoi::{utils::get_value, CrocoiNode, ICodegen, INodeResult, ISymbol}, }; use crate::error::CrocoError; use crate::token::LiteralEnum::*; impl CrocoiNode for MultiplicateNode { #[cfg(feature = "crocoi")] fn crocoi(&mut self, codegen: &mut ICodegen) -> Result<INodeResult, CrocoError> { let value = match ( get_value(&mut self.left, codegen, &self.code_pos)?, get_value(&mut self.right, codegen, &self.code_pos)?, ) { (Fnum(f1), Fnum(f2)) => Fnum(f1 * f2), (Num(n1), Num(n2)) => Num(n1 * n2), _ => return Err(CrocoError::multiplicate_error(&self.code_pos)), }; Ok(INodeResult::Value(ISymbol::Primitive(value))) } }
true
35256163290e982f40a284fe6adc0cc8de111645
Rust
nficca/tubes
/tests/lib.rs
UTF-8
1,591
2.96875
3
[]
no_license
extern crate tubes; use std::thread; use tubes::{Payload, Tubes}; #[test] fn it_works() { let mut tubes = Tubes::new().add_tube("foo").add_tube("bar"); let foo_receiver = tubes.subscribe("foo").unwrap(); let foo_receiver2 = tubes.subscribe("foo").unwrap(); let bar_receiver = tubes.subscribe("bar").unwrap(); let payload = Payload::new("thing"); tubes.send("foo", &payload); assert_eq!(bar_receiver.try_recv().is_err(), true); assert_eq!(foo_receiver.try_recv().unwrap(), payload); assert_eq!(foo_receiver2.try_recv().unwrap(), payload); } #[test] fn it_maintains_payload_ordering() { let mut tubes = Tubes::new().add_tube("foo"); let foo_receiver = tubes.subscribe("foo").unwrap(); let payload_a = Payload::new(1); let payload_b = Payload::new(2); tubes.send("foo", &payload_b); tubes.send("foo", &payload_a); assert_eq!(foo_receiver.try_recv().unwrap(), payload_b); assert_eq!(foo_receiver.try_recv().unwrap(), payload_a); } #[test] fn it_works_async() { let mut tubes = Tubes::new().add_tube("foo"); let base_payload = Payload::new(()); let mut receivers = vec![]; let mut children = vec![]; for _ in 0..10 { receivers.push(tubes.subscribe("foo").unwrap()); } tubes.send("foo", &base_payload); for receiver in receivers { let payload = base_payload.clone(); children.push(thread::spawn(move || { assert_eq!(receiver.try_recv().unwrap(), payload); })); } for child in children { child.join().unwrap(); } }
true
334cf5381d59328f8de0ef9da2e3017e0ad59614
Rust
ivfranco/notes
/Dragon_Book/chapter_9/data_flow/src/utils.rs
UTF-8
491
3.109375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
use std::hash::Hash; pub fn sorted<'a, I, T: 'a>(set: I) -> Vec<T> where I: IntoIterator<Item = T>, T: Ord + Hash + Clone, { let mut sorted: Vec<_> = set.into_iter().collect(); sorted.sort(); sorted } pub fn filter_indices<'a, I: 'a, T, F: 'a>(iter: I, p: F) -> impl Iterator<Item = usize> + 'a where I: IntoIterator<Item = T>, F: Fn(T) -> bool, { iter.into_iter() .enumerate() .filter_map(move |(i, t)| if p(t) { Some(i) } else { None }) }
true
fa7cf0ffa11f74235b6d556a5e11ddd0911577d5
Rust
desto-git/rust-test
/src/entity.rs
UTF-8
522
3.3125
3
[ "Unlicense" ]
permissive
use types::Coordinate; use traits::Drawable; pub struct Entity { position: Coordinate<u8>, sprite: Coordinate<u8>, } impl Entity { pub fn new( position: Coordinate<u8>, sprite: Coordinate<u8> ) -> Entity { Entity { position: position, sprite: sprite, } } pub fn set_position( &mut self, position: Coordinate<u8> ){ self.position = position; } } impl Drawable for Entity { fn get_position( &self ) -> Coordinate<u8> { self.position } fn get_sprite( &self ) -> Coordinate<u8> { self.sprite } }
true
e935376a810900dade48477fef3b403c9598ab28
Rust
eupn/axp173-rs
/src/irq.rs
UTF-8
4,416
2.96875
3
[ "MIT" ]
permissive
//! Interrupts (IRQs). use bit_field::BitField; use embedded_hal::blocking::i2c::{Write, WriteRead}; use crate::{Axp173, Axp173Result, Error, OperationResult}; /// An AXP173 interrupt. #[derive(Debug, Copy, Clone)] #[allow(missing_docs)] // TODO: document IRQs pub enum Irq { AcinOvervoltage, AcinPluggedIn, AcinUnplugged, VbusOvervoltage, VbusPluggedIn, VbusUnplugged, VbusUndervoltage, BatteryPlugged, BatteryUnplugged, EnteredBattRecoveryMode, ExitedBattRecoveryMode, BatteryCharging, BatteryCharged, BatteryOverheat, BatteryTooCold, ChipOverheat, InsufficientChargeCurrent, Dcdc1Undervoltage, Dcdc2Undervoltage, Ldo4Undervoltage, // Irq21, // Reserved ButtonShortPress, ButtonLongPress, // Irq24, // Reserved // Irq25, // Reserved VbusEffective, VbusInvalid, VbusSessionValid, VbusSessionInvalid, LowBatteryWarning, } impl Irq { #[rustfmt::skip] // To preserve table formatting pub(crate) fn to_reg_and_bit(&self) -> (u8, usize) { match self { Irq::AcinOvervoltage => (0x44, 7), Irq::AcinPluggedIn => (0x44, 6), Irq::AcinUnplugged => (0x44, 5), Irq::VbusOvervoltage => (0x44, 4), Irq::VbusPluggedIn => (0x44, 3), Irq::VbusUnplugged => (0x44, 2), Irq::VbusUndervoltage => (0x44, 1), Irq::BatteryPlugged => (0x45, 7), Irq::BatteryUnplugged => (0x45, 6), Irq::EnteredBattRecoveryMode => (0x45, 5), Irq::ExitedBattRecoveryMode => (0x45, 4), Irq::BatteryCharging => (0x45, 3), Irq::BatteryCharged => (0x45, 2), Irq::BatteryOverheat => (0x45, 1), Irq::BatteryTooCold => (0x45, 0), Irq::ChipOverheat => (0x46, 7), Irq::InsufficientChargeCurrent => (0x46, 6), Irq::Dcdc1Undervoltage => (0x46, 5), Irq::Dcdc2Undervoltage => (0x46, 4), Irq::Ldo4Undervoltage => (0x46, 3), // Irq21 is reserved Irq::ButtonShortPress => (0x46, 1), Irq::ButtonLongPress => (0x46, 0), // Irq24 is reserved // Irq25 is reserved Irq::VbusEffective => (0x47, 5), Irq::VbusInvalid => (0x47, 4), Irq::VbusSessionValid => (0x47, 3), Irq::VbusSessionInvalid => (0x47, 2), Irq::LowBatteryWarning => (0x47, 0), } } } impl<I, E> Axp173<I> where I: WriteRead<Error = E> + Write<Error = E>, { /// Enables or disables (masks) selected IRQ. pub fn set_irq(&mut self, irq: Irq, enabled: bool) -> OperationResult<E> { let (status_reg, bit) = irq.to_reg_and_bit(); let mask_reg = status_reg - 4; // Convert status register to mask register let mut bits = self.read_u8(mask_reg).map_err(Error::I2c)?; bits.set_bit(bit, enabled); self.write_u8(mask_reg, bits).map_err(Error::I2c)?; Ok(()) } /// Clears previously fired selected IRQ. pub fn clear_irq(&mut self, irq: Irq) -> OperationResult<E> { let (status_reg, bit) = irq.to_reg_and_bit(); let mut bits = self.read_u8(status_reg).map_err(Error::I2c)?; bits.set_bit(bit, true); // Clear the IRQ by writing '1' bit self.write_u8(status_reg, bits).map_err(Error::I2c)?; Ok(()) } /// Clears ALL pending IRQs. pub fn clear_all_irq(&mut self) -> OperationResult<E> { self.write_u8(0x44, 0xff).map_err(Error::I2c)?; self.write_u8(0x45, 0xff).map_err(Error::I2c)?; self.write_u8(0x46, 0xff).map_err(Error::I2c)?; self.write_u8(0x47, 0xff).map_err(Error::I2c)?; Ok(()) } /// Checks whether selected IRQ has fired or not. /// Note: one should clear the IRQ after checking or it will fire indefinitely pub fn check_irq(&mut self, irq: Irq) -> Axp173Result<bool, E> { let (status_reg, bit) = irq.to_reg_and_bit(); let reg_val = self.read_u8(status_reg).map_err(Error::I2c)?; Ok(reg_val.get_bit(bit)) } }
true
c96f3e3792a7a40f8db8a67bd9eda2b43077663b
Rust
jmulcahy/advent-of-code-2017
/day1/src/bin/main.rs
UTF-8
546
2.703125
3
[]
no_license
extern crate day2; extern crate day1; use std::error::Error; fn main() { let filename = "input.txt"; let input = match day2::read_file(filename) { Err(why) => panic!("couldn't open {}: {}", filename, why.description()), Ok(input) => input }; let data = match day1::parse_input(&input) { Some(data) => data, _ => panic!("failed to parse input after reading"), }; println!("Result 1:\n{}", day1::process1(data.as_slice())); println!("Result 2:\n{}", day1::process2(data.as_slice())); }
true
9f15e75e26d84aa607e322654077448004e4c792
Rust
algebraicdb/algebraicdb
/algebraicdb/src/table/pattern_iter.rs
UTF-8
2,294
2.84375
3
[]
no_license
use super::{Cell, Table}; use crate::pattern::CompiledPattern; use crate::types::TypeMap; #[derive(Clone, Copy)] pub struct RowPatternIter<'p, 'ts, 'tb> { pattern: &'p CompiledPattern, types: &'ts TypeMap, table: &'tb Table, row: usize, } #[derive(Clone, Copy)] pub struct CellPatternIter<'p, 'ts, 'tb> { pattern: &'p CompiledPattern, types: &'ts TypeMap, data: &'tb [u8], cursor: usize, row: usize, } impl<'p, 'ts, 'tb> RowPatternIter<'p, 'ts, 'tb> { pub fn new(pattern: &'p CompiledPattern, table: &'tb Table, types: &'ts TypeMap) -> Self { RowPatternIter { pattern, table, row: 0, types, } } pub fn row(&self) -> usize { self.row } } impl<'p, 'ts, 'tb> CellPatternIter<'p, 'ts, 'tb> { pub fn row(&self) -> usize { self.row } } impl<'p, 'ts, 'tb> Iterator for RowPatternIter<'p, 'ts, 'tb> { type Item = CellPatternIter<'p, 'ts, 'tb>; fn next(&mut self) -> Option<Self::Item> { 'outer: loop { if self.row >= self.table.row_count() { return None; } let row = self.table.get_row(self.row); self.row += 1; for (i, value) in &self.pattern.matches { for j in 0..value.len() { if row.data[i + j] != value[j] { continue 'outer; } } } return Some(CellPatternIter { cursor: 0, row: self.row - 1, pattern: self.pattern, types: self.types, data: row.data, }); } } } impl<'p, 'ts, 'tb> Iterator for CellPatternIter<'p, 'ts, 'tb> { type Item = (&'p str, Cell<'tb, 'ts>); fn next(&mut self) -> Option<Self::Item> { self.pattern .bindings .get(self.cursor) .map(|(index, type_id, ident)| { self.cursor += 1; let t = &self.types[type_id]; let type_size = t.size_of(self.types); let cell = Cell::new(*type_id, &self.data[*index..*index + type_size], self.types); (ident.as_str(), cell) }) } }
true
9b506ae204c16212f6adae58b0c5869fac66fd1c
Rust
srijs/rust-cfn
/src/aws/dlm.rs
UTF-8
74,085
2.59375
3
[ "MIT" ]
permissive
//! Types for the `DLM` service. /// The [`AWS::DLM::LifecyclePolicy`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dlm-lifecyclepolicy.html) resource type. #[derive(Debug, Default)] pub struct LifecyclePolicy { properties: LifecyclePolicyProperties } /// Properties for the `LifecyclePolicy` resource. #[derive(Debug, Default)] pub struct LifecyclePolicyProperties { /// Property [`Description`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dlm-lifecyclepolicy.html#cfn-dlm-lifecyclepolicy-description). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub description: Option<::Value<String>>, /// Property [`ExecutionRoleArn`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dlm-lifecyclepolicy.html#cfn-dlm-lifecyclepolicy-executionrolearn). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub execution_role_arn: Option<::Value<String>>, /// Property [`PolicyDetails`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dlm-lifecyclepolicy.html#cfn-dlm-lifecyclepolicy-policydetails). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub policy_details: Option<::Value<self::lifecycle_policy::PolicyDetails>>, /// Property [`State`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dlm-lifecyclepolicy.html#cfn-dlm-lifecyclepolicy-state). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub state: Option<::Value<String>>, /// Property [`Tags`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dlm-lifecyclepolicy.html#cfn-dlm-lifecyclepolicy-tags). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub tags: Option<::ValueList<::Tag>>, } impl ::serde::Serialize for LifecyclePolicyProperties { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref description) = self.description { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Description", description)?; } if let Some(ref execution_role_arn) = self.execution_role_arn { ::serde::ser::SerializeMap::serialize_entry(&mut map, "ExecutionRoleArn", execution_role_arn)?; } if let Some(ref policy_details) = self.policy_details { ::serde::ser::SerializeMap::serialize_entry(&mut map, "PolicyDetails", policy_details)?; } if let Some(ref state) = self.state { ::serde::ser::SerializeMap::serialize_entry(&mut map, "State", state)?; } if let Some(ref tags) = self.tags { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Tags", tags)?; } ::serde::ser::SerializeMap::end(map) } } impl<'de> ::serde::Deserialize<'de> for LifecyclePolicyProperties { fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<LifecyclePolicyProperties, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = LifecyclePolicyProperties; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type LifecyclePolicyProperties") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut description: Option<::Value<String>> = None; let mut execution_role_arn: Option<::Value<String>> = None; let mut policy_details: Option<::Value<self::lifecycle_policy::PolicyDetails>> = None; let mut state: Option<::Value<String>> = None; let mut tags: Option<::ValueList<::Tag>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "Description" => { description = ::serde::de::MapAccess::next_value(&mut map)?; } "ExecutionRoleArn" => { execution_role_arn = ::serde::de::MapAccess::next_value(&mut map)?; } "PolicyDetails" => { policy_details = ::serde::de::MapAccess::next_value(&mut map)?; } "State" => { state = ::serde::de::MapAccess::next_value(&mut map)?; } "Tags" => { tags = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(LifecyclePolicyProperties { description: description, execution_role_arn: execution_role_arn, policy_details: policy_details, state: state, tags: tags, }) } } d.deserialize_map(Visitor) } } impl ::Resource for LifecyclePolicy { type Properties = LifecyclePolicyProperties; const TYPE: &'static str = "AWS::DLM::LifecyclePolicy"; fn properties(&self) -> &LifecyclePolicyProperties { &self.properties } fn properties_mut(&mut self) -> &mut LifecyclePolicyProperties { &mut self.properties } } impl ::private::Sealed for LifecyclePolicy {} impl From<LifecyclePolicyProperties> for LifecyclePolicy { fn from(properties: LifecyclePolicyProperties) -> LifecyclePolicy { LifecyclePolicy { properties } } } pub mod lifecycle_policy { //! Property types for the `LifecyclePolicy` resource. /// The [`AWS::DLM::LifecyclePolicy.Action`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-action.html) property type. #[derive(Debug, Default)] pub struct Action { /// Property [`CrossRegionCopy`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-action.html#cfn-dlm-lifecyclepolicy-action-crossregioncopy). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub cross_region_copy: ::ValueList<CrossRegionCopyAction>, /// Property [`Name`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-action.html#cfn-dlm-lifecyclepolicy-action-name). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub name: ::Value<String>, } impl ::codec::SerializeValue for Action { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; ::serde::ser::SerializeMap::serialize_entry(&mut map, "CrossRegionCopy", &self.cross_region_copy)?; ::serde::ser::SerializeMap::serialize_entry(&mut map, "Name", &self.name)?; ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for Action { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<Action, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = Action; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type Action") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut cross_region_copy: Option<::ValueList<CrossRegionCopyAction>> = None; let mut name: Option<::Value<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "CrossRegionCopy" => { cross_region_copy = ::serde::de::MapAccess::next_value(&mut map)?; } "Name" => { name = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(Action { cross_region_copy: cross_region_copy.ok_or(::serde::de::Error::missing_field("CrossRegionCopy"))?, name: name.ok_or(::serde::de::Error::missing_field("Name"))?, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.CreateRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html) property type. #[derive(Debug, Default)] pub struct CreateRule { /// Property [`CronExpression`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html#cfn-dlm-lifecyclepolicy-createrule-cronexpression). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub cron_expression: Option<::Value<String>>, /// Property [`Interval`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html#cfn-dlm-lifecyclepolicy-createrule-interval). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub interval: Option<::Value<u32>>, /// Property [`IntervalUnit`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html#cfn-dlm-lifecyclepolicy-createrule-intervalunit). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub interval_unit: Option<::Value<String>>, /// Property [`Location`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html#cfn-dlm-lifecyclepolicy-createrule-location). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub location: Option<::Value<String>>, /// Property [`Times`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html#cfn-dlm-lifecyclepolicy-createrule-times). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub times: Option<::ValueList<String>>, } impl ::codec::SerializeValue for CreateRule { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref cron_expression) = self.cron_expression { ::serde::ser::SerializeMap::serialize_entry(&mut map, "CronExpression", cron_expression)?; } if let Some(ref interval) = self.interval { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Interval", interval)?; } if let Some(ref interval_unit) = self.interval_unit { ::serde::ser::SerializeMap::serialize_entry(&mut map, "IntervalUnit", interval_unit)?; } if let Some(ref location) = self.location { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Location", location)?; } if let Some(ref times) = self.times { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Times", times)?; } ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for CreateRule { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<CreateRule, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = CreateRule; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type CreateRule") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut cron_expression: Option<::Value<String>> = None; let mut interval: Option<::Value<u32>> = None; let mut interval_unit: Option<::Value<String>> = None; let mut location: Option<::Value<String>> = None; let mut times: Option<::ValueList<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "CronExpression" => { cron_expression = ::serde::de::MapAccess::next_value(&mut map)?; } "Interval" => { interval = ::serde::de::MapAccess::next_value(&mut map)?; } "IntervalUnit" => { interval_unit = ::serde::de::MapAccess::next_value(&mut map)?; } "Location" => { location = ::serde::de::MapAccess::next_value(&mut map)?; } "Times" => { times = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(CreateRule { cron_expression: cron_expression, interval: interval, interval_unit: interval_unit, location: location, times: times, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.CrossRegionCopyAction`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyaction.html) property type. #[derive(Debug, Default)] pub struct CrossRegionCopyAction { /// Property [`EncryptionConfiguration`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyaction.html#cfn-dlm-lifecyclepolicy-crossregioncopyaction-encryptionconfiguration). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub encryption_configuration: ::Value<EncryptionConfiguration>, /// Property [`RetainRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyaction.html#cfn-dlm-lifecyclepolicy-crossregioncopyaction-retainrule). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub retain_rule: Option<::Value<CrossRegionCopyRetainRule>>, /// Property [`Target`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyaction.html#cfn-dlm-lifecyclepolicy-crossregioncopyaction-target). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub target: ::Value<String>, } impl ::codec::SerializeValue for CrossRegionCopyAction { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; ::serde::ser::SerializeMap::serialize_entry(&mut map, "EncryptionConfiguration", &self.encryption_configuration)?; if let Some(ref retain_rule) = self.retain_rule { ::serde::ser::SerializeMap::serialize_entry(&mut map, "RetainRule", retain_rule)?; } ::serde::ser::SerializeMap::serialize_entry(&mut map, "Target", &self.target)?; ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for CrossRegionCopyAction { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<CrossRegionCopyAction, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = CrossRegionCopyAction; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type CrossRegionCopyAction") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut encryption_configuration: Option<::Value<EncryptionConfiguration>> = None; let mut retain_rule: Option<::Value<CrossRegionCopyRetainRule>> = None; let mut target: Option<::Value<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "EncryptionConfiguration" => { encryption_configuration = ::serde::de::MapAccess::next_value(&mut map)?; } "RetainRule" => { retain_rule = ::serde::de::MapAccess::next_value(&mut map)?; } "Target" => { target = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(CrossRegionCopyAction { encryption_configuration: encryption_configuration.ok_or(::serde::de::Error::missing_field("EncryptionConfiguration"))?, retain_rule: retain_rule, target: target.ok_or(::serde::de::Error::missing_field("Target"))?, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.CrossRegionCopyRetainRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyretainrule.html) property type. #[derive(Debug, Default)] pub struct CrossRegionCopyRetainRule { /// Property [`Interval`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyretainrule.html#cfn-dlm-lifecyclepolicy-crossregioncopyretainrule-interval). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub interval: ::Value<u32>, /// Property [`IntervalUnit`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyretainrule.html#cfn-dlm-lifecyclepolicy-crossregioncopyretainrule-intervalunit). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub interval_unit: ::Value<String>, } impl ::codec::SerializeValue for CrossRegionCopyRetainRule { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; ::serde::ser::SerializeMap::serialize_entry(&mut map, "Interval", &self.interval)?; ::serde::ser::SerializeMap::serialize_entry(&mut map, "IntervalUnit", &self.interval_unit)?; ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for CrossRegionCopyRetainRule { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<CrossRegionCopyRetainRule, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = CrossRegionCopyRetainRule; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type CrossRegionCopyRetainRule") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut interval: Option<::Value<u32>> = None; let mut interval_unit: Option<::Value<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "Interval" => { interval = ::serde::de::MapAccess::next_value(&mut map)?; } "IntervalUnit" => { interval_unit = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(CrossRegionCopyRetainRule { interval: interval.ok_or(::serde::de::Error::missing_field("Interval"))?, interval_unit: interval_unit.ok_or(::serde::de::Error::missing_field("IntervalUnit"))?, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.CrossRegionCopyRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyrule.html) property type. #[derive(Debug, Default)] pub struct CrossRegionCopyRule { /// Property [`CmkArn`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyrule.html#cfn-dlm-lifecyclepolicy-crossregioncopyrule-cmkarn). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub cmk_arn: Option<::Value<String>>, /// Property [`CopyTags`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyrule.html#cfn-dlm-lifecyclepolicy-crossregioncopyrule-copytags). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub copy_tags: Option<::Value<bool>>, /// Property [`Encrypted`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyrule.html#cfn-dlm-lifecyclepolicy-crossregioncopyrule-encrypted). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub encrypted: ::Value<bool>, /// Property [`RetainRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyrule.html#cfn-dlm-lifecyclepolicy-crossregioncopyrule-retainrule). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub retain_rule: Option<::Value<CrossRegionCopyRetainRule>>, /// Property [`Target`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyrule.html#cfn-dlm-lifecyclepolicy-crossregioncopyrule-target). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub target: Option<::Value<String>>, /// Property [`TargetRegion`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-crossregioncopyrule.html#cfn-dlm-lifecyclepolicy-crossregioncopyrule-targetregion). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub target_region: Option<::Value<String>>, } impl ::codec::SerializeValue for CrossRegionCopyRule { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref cmk_arn) = self.cmk_arn { ::serde::ser::SerializeMap::serialize_entry(&mut map, "CmkArn", cmk_arn)?; } if let Some(ref copy_tags) = self.copy_tags { ::serde::ser::SerializeMap::serialize_entry(&mut map, "CopyTags", copy_tags)?; } ::serde::ser::SerializeMap::serialize_entry(&mut map, "Encrypted", &self.encrypted)?; if let Some(ref retain_rule) = self.retain_rule { ::serde::ser::SerializeMap::serialize_entry(&mut map, "RetainRule", retain_rule)?; } if let Some(ref target) = self.target { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Target", target)?; } if let Some(ref target_region) = self.target_region { ::serde::ser::SerializeMap::serialize_entry(&mut map, "TargetRegion", target_region)?; } ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for CrossRegionCopyRule { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<CrossRegionCopyRule, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = CrossRegionCopyRule; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type CrossRegionCopyRule") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut cmk_arn: Option<::Value<String>> = None; let mut copy_tags: Option<::Value<bool>> = None; let mut encrypted: Option<::Value<bool>> = None; let mut retain_rule: Option<::Value<CrossRegionCopyRetainRule>> = None; let mut target: Option<::Value<String>> = None; let mut target_region: Option<::Value<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "CmkArn" => { cmk_arn = ::serde::de::MapAccess::next_value(&mut map)?; } "CopyTags" => { copy_tags = ::serde::de::MapAccess::next_value(&mut map)?; } "Encrypted" => { encrypted = ::serde::de::MapAccess::next_value(&mut map)?; } "RetainRule" => { retain_rule = ::serde::de::MapAccess::next_value(&mut map)?; } "Target" => { target = ::serde::de::MapAccess::next_value(&mut map)?; } "TargetRegion" => { target_region = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(CrossRegionCopyRule { cmk_arn: cmk_arn, copy_tags: copy_tags, encrypted: encrypted.ok_or(::serde::de::Error::missing_field("Encrypted"))?, retain_rule: retain_rule, target: target, target_region: target_region, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.EncryptionConfiguration`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-encryptionconfiguration.html) property type. #[derive(Debug, Default)] pub struct EncryptionConfiguration { /// Property [`CmkArn`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-encryptionconfiguration.html#cfn-dlm-lifecyclepolicy-encryptionconfiguration-cmkarn). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub cmk_arn: Option<::Value<String>>, /// Property [`Encrypted`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-encryptionconfiguration.html#cfn-dlm-lifecyclepolicy-encryptionconfiguration-encrypted). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub encrypted: ::Value<bool>, } impl ::codec::SerializeValue for EncryptionConfiguration { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref cmk_arn) = self.cmk_arn { ::serde::ser::SerializeMap::serialize_entry(&mut map, "CmkArn", cmk_arn)?; } ::serde::ser::SerializeMap::serialize_entry(&mut map, "Encrypted", &self.encrypted)?; ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for EncryptionConfiguration { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<EncryptionConfiguration, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = EncryptionConfiguration; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type EncryptionConfiguration") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut cmk_arn: Option<::Value<String>> = None; let mut encrypted: Option<::Value<bool>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "CmkArn" => { cmk_arn = ::serde::de::MapAccess::next_value(&mut map)?; } "Encrypted" => { encrypted = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(EncryptionConfiguration { cmk_arn: cmk_arn, encrypted: encrypted.ok_or(::serde::de::Error::missing_field("Encrypted"))?, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.EventParameters`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-eventparameters.html) property type. #[derive(Debug, Default)] pub struct EventParameters { /// Property [`DescriptionRegex`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-eventparameters.html#cfn-dlm-lifecyclepolicy-eventparameters-descriptionregex). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub description_regex: Option<::Value<String>>, /// Property [`EventType`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-eventparameters.html#cfn-dlm-lifecyclepolicy-eventparameters-eventtype). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub event_type: ::Value<String>, /// Property [`SnapshotOwner`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-eventparameters.html#cfn-dlm-lifecyclepolicy-eventparameters-snapshotowner). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub snapshot_owner: ::ValueList<String>, } impl ::codec::SerializeValue for EventParameters { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref description_regex) = self.description_regex { ::serde::ser::SerializeMap::serialize_entry(&mut map, "DescriptionRegex", description_regex)?; } ::serde::ser::SerializeMap::serialize_entry(&mut map, "EventType", &self.event_type)?; ::serde::ser::SerializeMap::serialize_entry(&mut map, "SnapshotOwner", &self.snapshot_owner)?; ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for EventParameters { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<EventParameters, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = EventParameters; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type EventParameters") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut description_regex: Option<::Value<String>> = None; let mut event_type: Option<::Value<String>> = None; let mut snapshot_owner: Option<::ValueList<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "DescriptionRegex" => { description_regex = ::serde::de::MapAccess::next_value(&mut map)?; } "EventType" => { event_type = ::serde::de::MapAccess::next_value(&mut map)?; } "SnapshotOwner" => { snapshot_owner = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(EventParameters { description_regex: description_regex, event_type: event_type.ok_or(::serde::de::Error::missing_field("EventType"))?, snapshot_owner: snapshot_owner.ok_or(::serde::de::Error::missing_field("SnapshotOwner"))?, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.EventSource`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-eventsource.html) property type. #[derive(Debug, Default)] pub struct EventSource { /// Property [`Parameters`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-eventsource.html#cfn-dlm-lifecyclepolicy-eventsource-parameters). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub parameters: Option<::Value<EventParameters>>, /// Property [`Type`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-eventsource.html#cfn-dlm-lifecyclepolicy-eventsource-type). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub r#type: ::Value<String>, } impl ::codec::SerializeValue for EventSource { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref parameters) = self.parameters { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Parameters", parameters)?; } ::serde::ser::SerializeMap::serialize_entry(&mut map, "Type", &self.r#type)?; ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for EventSource { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<EventSource, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = EventSource; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type EventSource") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut parameters: Option<::Value<EventParameters>> = None; let mut r#type: Option<::Value<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "Parameters" => { parameters = ::serde::de::MapAccess::next_value(&mut map)?; } "Type" => { r#type = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(EventSource { parameters: parameters, r#type: r#type.ok_or(::serde::de::Error::missing_field("Type"))?, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.FastRestoreRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-fastrestorerule.html) property type. #[derive(Debug, Default)] pub struct FastRestoreRule { /// Property [`AvailabilityZones`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-fastrestorerule.html#cfn-dlm-lifecyclepolicy-fastrestorerule-availabilityzones). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub availability_zones: Option<::ValueList<String>>, /// Property [`Count`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-fastrestorerule.html#cfn-dlm-lifecyclepolicy-fastrestorerule-count). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub count: Option<::Value<u32>>, /// Property [`Interval`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-fastrestorerule.html#cfn-dlm-lifecyclepolicy-fastrestorerule-interval). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub interval: Option<::Value<u32>>, /// Property [`IntervalUnit`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-fastrestorerule.html#cfn-dlm-lifecyclepolicy-fastrestorerule-intervalunit). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub interval_unit: Option<::Value<String>>, } impl ::codec::SerializeValue for FastRestoreRule { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref availability_zones) = self.availability_zones { ::serde::ser::SerializeMap::serialize_entry(&mut map, "AvailabilityZones", availability_zones)?; } if let Some(ref count) = self.count { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Count", count)?; } if let Some(ref interval) = self.interval { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Interval", interval)?; } if let Some(ref interval_unit) = self.interval_unit { ::serde::ser::SerializeMap::serialize_entry(&mut map, "IntervalUnit", interval_unit)?; } ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for FastRestoreRule { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<FastRestoreRule, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = FastRestoreRule; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type FastRestoreRule") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut availability_zones: Option<::ValueList<String>> = None; let mut count: Option<::Value<u32>> = None; let mut interval: Option<::Value<u32>> = None; let mut interval_unit: Option<::Value<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "AvailabilityZones" => { availability_zones = ::serde::de::MapAccess::next_value(&mut map)?; } "Count" => { count = ::serde::de::MapAccess::next_value(&mut map)?; } "Interval" => { interval = ::serde::de::MapAccess::next_value(&mut map)?; } "IntervalUnit" => { interval_unit = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(FastRestoreRule { availability_zones: availability_zones, count: count, interval: interval, interval_unit: interval_unit, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.Parameters`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-parameters.html) property type. #[derive(Debug, Default)] pub struct Parameters { /// Property [`ExcludeBootVolume`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-parameters.html#cfn-dlm-lifecyclepolicy-parameters-excludebootvolume). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub exclude_boot_volume: Option<::Value<bool>>, /// Property [`NoReboot`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-parameters.html#cfn-dlm-lifecyclepolicy-parameters-noreboot). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub no_reboot: Option<::Value<bool>>, } impl ::codec::SerializeValue for Parameters { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref exclude_boot_volume) = self.exclude_boot_volume { ::serde::ser::SerializeMap::serialize_entry(&mut map, "ExcludeBootVolume", exclude_boot_volume)?; } if let Some(ref no_reboot) = self.no_reboot { ::serde::ser::SerializeMap::serialize_entry(&mut map, "NoReboot", no_reboot)?; } ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for Parameters { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<Parameters, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = Parameters; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type Parameters") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut exclude_boot_volume: Option<::Value<bool>> = None; let mut no_reboot: Option<::Value<bool>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "ExcludeBootVolume" => { exclude_boot_volume = ::serde::de::MapAccess::next_value(&mut map)?; } "NoReboot" => { no_reboot = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(Parameters { exclude_boot_volume: exclude_boot_volume, no_reboot: no_reboot, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.PolicyDetails`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-policydetails.html) property type. #[derive(Debug, Default)] pub struct PolicyDetails { /// Property [`Actions`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-policydetails.html#cfn-dlm-lifecyclepolicy-policydetails-actions). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub actions: Option<::ValueList<Action>>, /// Property [`EventSource`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-policydetails.html#cfn-dlm-lifecyclepolicy-policydetails-eventsource). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub event_source: Option<::Value<EventSource>>, /// Property [`Parameters`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-policydetails.html#cfn-dlm-lifecyclepolicy-policydetails-parameters). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub parameters: Option<::Value<Parameters>>, /// Property [`PolicyType`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-policydetails.html#cfn-dlm-lifecyclepolicy-policydetails-policytype). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub policy_type: Option<::Value<String>>, /// Property [`ResourceLocations`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-policydetails.html#cfn-dlm-lifecyclepolicy-policydetails-resourcelocations). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub resource_locations: Option<::ValueList<String>>, /// Property [`ResourceTypes`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-policydetails.html#cfn-dlm-lifecyclepolicy-policydetails-resourcetypes). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub resource_types: Option<::ValueList<String>>, /// Property [`Schedules`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-policydetails.html#cfn-dlm-lifecyclepolicy-policydetails-schedules). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub schedules: Option<::ValueList<Schedule>>, /// Property [`TargetTags`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-policydetails.html#cfn-dlm-lifecyclepolicy-policydetails-targettags). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub target_tags: Option<::ValueList<::Tag>>, } impl ::codec::SerializeValue for PolicyDetails { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref actions) = self.actions { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Actions", actions)?; } if let Some(ref event_source) = self.event_source { ::serde::ser::SerializeMap::serialize_entry(&mut map, "EventSource", event_source)?; } if let Some(ref parameters) = self.parameters { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Parameters", parameters)?; } if let Some(ref policy_type) = self.policy_type { ::serde::ser::SerializeMap::serialize_entry(&mut map, "PolicyType", policy_type)?; } if let Some(ref resource_locations) = self.resource_locations { ::serde::ser::SerializeMap::serialize_entry(&mut map, "ResourceLocations", resource_locations)?; } if let Some(ref resource_types) = self.resource_types { ::serde::ser::SerializeMap::serialize_entry(&mut map, "ResourceTypes", resource_types)?; } if let Some(ref schedules) = self.schedules { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Schedules", schedules)?; } if let Some(ref target_tags) = self.target_tags { ::serde::ser::SerializeMap::serialize_entry(&mut map, "TargetTags", target_tags)?; } ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for PolicyDetails { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<PolicyDetails, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = PolicyDetails; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type PolicyDetails") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut actions: Option<::ValueList<Action>> = None; let mut event_source: Option<::Value<EventSource>> = None; let mut parameters: Option<::Value<Parameters>> = None; let mut policy_type: Option<::Value<String>> = None; let mut resource_locations: Option<::ValueList<String>> = None; let mut resource_types: Option<::ValueList<String>> = None; let mut schedules: Option<::ValueList<Schedule>> = None; let mut target_tags: Option<::ValueList<::Tag>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "Actions" => { actions = ::serde::de::MapAccess::next_value(&mut map)?; } "EventSource" => { event_source = ::serde::de::MapAccess::next_value(&mut map)?; } "Parameters" => { parameters = ::serde::de::MapAccess::next_value(&mut map)?; } "PolicyType" => { policy_type = ::serde::de::MapAccess::next_value(&mut map)?; } "ResourceLocations" => { resource_locations = ::serde::de::MapAccess::next_value(&mut map)?; } "ResourceTypes" => { resource_types = ::serde::de::MapAccess::next_value(&mut map)?; } "Schedules" => { schedules = ::serde::de::MapAccess::next_value(&mut map)?; } "TargetTags" => { target_tags = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(PolicyDetails { actions: actions, event_source: event_source, parameters: parameters, policy_type: policy_type, resource_locations: resource_locations, resource_types: resource_types, schedules: schedules, target_tags: target_tags, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.RetainRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-retainrule.html) property type. #[derive(Debug, Default)] pub struct RetainRule { /// Property [`Count`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-retainrule.html#cfn-dlm-lifecyclepolicy-retainrule-count). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub count: Option<::Value<u32>>, /// Property [`Interval`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-retainrule.html#cfn-dlm-lifecyclepolicy-retainrule-interval). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub interval: Option<::Value<u32>>, /// Property [`IntervalUnit`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-retainrule.html#cfn-dlm-lifecyclepolicy-retainrule-intervalunit). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub interval_unit: Option<::Value<String>>, } impl ::codec::SerializeValue for RetainRule { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref count) = self.count { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Count", count)?; } if let Some(ref interval) = self.interval { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Interval", interval)?; } if let Some(ref interval_unit) = self.interval_unit { ::serde::ser::SerializeMap::serialize_entry(&mut map, "IntervalUnit", interval_unit)?; } ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for RetainRule { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<RetainRule, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = RetainRule; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type RetainRule") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut count: Option<::Value<u32>> = None; let mut interval: Option<::Value<u32>> = None; let mut interval_unit: Option<::Value<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "Count" => { count = ::serde::de::MapAccess::next_value(&mut map)?; } "Interval" => { interval = ::serde::de::MapAccess::next_value(&mut map)?; } "IntervalUnit" => { interval_unit = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(RetainRule { count: count, interval: interval, interval_unit: interval_unit, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.Schedule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html) property type. #[derive(Debug, Default)] pub struct Schedule { /// Property [`CopyTags`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html#cfn-dlm-lifecyclepolicy-schedule-copytags). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub copy_tags: Option<::Value<bool>>, /// Property [`CreateRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html#cfn-dlm-lifecyclepolicy-schedule-createrule). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub create_rule: Option<::Value<CreateRule>>, /// Property [`CrossRegionCopyRules`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html#cfn-dlm-lifecyclepolicy-schedule-crossregioncopyrules). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub cross_region_copy_rules: Option<::ValueList<CrossRegionCopyRule>>, /// Property [`FastRestoreRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html#cfn-dlm-lifecyclepolicy-schedule-fastrestorerule). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub fast_restore_rule: Option<::Value<FastRestoreRule>>, /// Property [`Name`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html#cfn-dlm-lifecyclepolicy-schedule-name). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub name: Option<::Value<String>>, /// Property [`RetainRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html#cfn-dlm-lifecyclepolicy-schedule-retainrule). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub retain_rule: Option<::Value<RetainRule>>, /// Property [`ShareRules`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html#cfn-dlm-lifecyclepolicy-schedule-sharerules). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub share_rules: Option<::ValueList<ShareRule>>, /// Property [`TagsToAdd`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html#cfn-dlm-lifecyclepolicy-schedule-tagstoadd). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub tags_to_add: Option<::ValueList<::Tag>>, /// Property [`VariableTags`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-schedule.html#cfn-dlm-lifecyclepolicy-schedule-variabletags). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub variable_tags: Option<::ValueList<::Tag>>, } impl ::codec::SerializeValue for Schedule { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref copy_tags) = self.copy_tags { ::serde::ser::SerializeMap::serialize_entry(&mut map, "CopyTags", copy_tags)?; } if let Some(ref create_rule) = self.create_rule { ::serde::ser::SerializeMap::serialize_entry(&mut map, "CreateRule", create_rule)?; } if let Some(ref cross_region_copy_rules) = self.cross_region_copy_rules { ::serde::ser::SerializeMap::serialize_entry(&mut map, "CrossRegionCopyRules", cross_region_copy_rules)?; } if let Some(ref fast_restore_rule) = self.fast_restore_rule { ::serde::ser::SerializeMap::serialize_entry(&mut map, "FastRestoreRule", fast_restore_rule)?; } if let Some(ref name) = self.name { ::serde::ser::SerializeMap::serialize_entry(&mut map, "Name", name)?; } if let Some(ref retain_rule) = self.retain_rule { ::serde::ser::SerializeMap::serialize_entry(&mut map, "RetainRule", retain_rule)?; } if let Some(ref share_rules) = self.share_rules { ::serde::ser::SerializeMap::serialize_entry(&mut map, "ShareRules", share_rules)?; } if let Some(ref tags_to_add) = self.tags_to_add { ::serde::ser::SerializeMap::serialize_entry(&mut map, "TagsToAdd", tags_to_add)?; } if let Some(ref variable_tags) = self.variable_tags { ::serde::ser::SerializeMap::serialize_entry(&mut map, "VariableTags", variable_tags)?; } ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for Schedule { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<Schedule, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = Schedule; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type Schedule") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut copy_tags: Option<::Value<bool>> = None; let mut create_rule: Option<::Value<CreateRule>> = None; let mut cross_region_copy_rules: Option<::ValueList<CrossRegionCopyRule>> = None; let mut fast_restore_rule: Option<::Value<FastRestoreRule>> = None; let mut name: Option<::Value<String>> = None; let mut retain_rule: Option<::Value<RetainRule>> = None; let mut share_rules: Option<::ValueList<ShareRule>> = None; let mut tags_to_add: Option<::ValueList<::Tag>> = None; let mut variable_tags: Option<::ValueList<::Tag>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "CopyTags" => { copy_tags = ::serde::de::MapAccess::next_value(&mut map)?; } "CreateRule" => { create_rule = ::serde::de::MapAccess::next_value(&mut map)?; } "CrossRegionCopyRules" => { cross_region_copy_rules = ::serde::de::MapAccess::next_value(&mut map)?; } "FastRestoreRule" => { fast_restore_rule = ::serde::de::MapAccess::next_value(&mut map)?; } "Name" => { name = ::serde::de::MapAccess::next_value(&mut map)?; } "RetainRule" => { retain_rule = ::serde::de::MapAccess::next_value(&mut map)?; } "ShareRules" => { share_rules = ::serde::de::MapAccess::next_value(&mut map)?; } "TagsToAdd" => { tags_to_add = ::serde::de::MapAccess::next_value(&mut map)?; } "VariableTags" => { variable_tags = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(Schedule { copy_tags: copy_tags, create_rule: create_rule, cross_region_copy_rules: cross_region_copy_rules, fast_restore_rule: fast_restore_rule, name: name, retain_rule: retain_rule, share_rules: share_rules, tags_to_add: tags_to_add, variable_tags: variable_tags, }) } } d.deserialize_map(Visitor) } } /// The [`AWS::DLM::LifecyclePolicy.ShareRule`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-sharerule.html) property type. #[derive(Debug, Default)] pub struct ShareRule { /// Property [`TargetAccounts`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-sharerule.html#cfn-dlm-lifecyclepolicy-sharerule-targetaccounts). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub target_accounts: Option<::ValueList<String>>, /// Property [`UnshareInterval`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-sharerule.html#cfn-dlm-lifecyclepolicy-sharerule-unshareinterval). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub unshare_interval: Option<::Value<u32>>, /// Property [`UnshareIntervalUnit`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-sharerule.html#cfn-dlm-lifecyclepolicy-sharerule-unshareintervalunit). /// /// Update type: _Mutable_. /// AWS CloudFormation doesn't replace the resource when you change this property. pub unshare_interval_unit: Option<::Value<String>>, } impl ::codec::SerializeValue for ShareRule { fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let mut map = ::serde::Serializer::serialize_map(s, None)?; if let Some(ref target_accounts) = self.target_accounts { ::serde::ser::SerializeMap::serialize_entry(&mut map, "TargetAccounts", target_accounts)?; } if let Some(ref unshare_interval) = self.unshare_interval { ::serde::ser::SerializeMap::serialize_entry(&mut map, "UnshareInterval", unshare_interval)?; } if let Some(ref unshare_interval_unit) = self.unshare_interval_unit { ::serde::ser::SerializeMap::serialize_entry(&mut map, "UnshareIntervalUnit", unshare_interval_unit)?; } ::serde::ser::SerializeMap::end(map) } } impl ::codec::DeserializeValue for ShareRule { fn deserialize<'de, D: ::serde::Deserializer<'de>>(d: D) -> Result<ShareRule, D::Error> { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = ShareRule; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "a struct of type ShareRule") } fn visit_map<A: ::serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { let mut target_accounts: Option<::ValueList<String>> = None; let mut unshare_interval: Option<::Value<u32>> = None; let mut unshare_interval_unit: Option<::Value<String>> = None; while let Some(__cfn_key) = ::serde::de::MapAccess::next_key::<String>(&mut map)? { match __cfn_key.as_ref() { "TargetAccounts" => { target_accounts = ::serde::de::MapAccess::next_value(&mut map)?; } "UnshareInterval" => { unshare_interval = ::serde::de::MapAccess::next_value(&mut map)?; } "UnshareIntervalUnit" => { unshare_interval_unit = ::serde::de::MapAccess::next_value(&mut map)?; } _ => {} } } Ok(ShareRule { target_accounts: target_accounts, unshare_interval: unshare_interval, unshare_interval_unit: unshare_interval_unit, }) } } d.deserialize_map(Visitor) } } }
true
cdcdb82cf4114cdc554b1ac63a2a40393c8dd0d7
Rust
chengyi818/kata
/Language/rust/grammer/trait_demo/static_dispatch_trait_demo_01/src/main.rs
UTF-8
572
3.328125
3
[]
no_license
#[allow(dead_code)] struct Cat { name: String, age: i32, } impl Cat { fn new(name: String, age: i32) -> Self { Self { name, age } } } trait Animal { fn name(&self) -> &'static str; // fn by_ref(&self) -> &Self; } impl Animal for Cat { fn name(&self) -> &'static str { "Cat" } // fn by_ref(&self) -> &Self // where // Self: Sized, // { // self // } } fn main() { let cat = Cat::new("kitty".to_string(), 2); let animal: &dyn Animal = &cat; println!("cat: {}", animal.name()); }
true
7174777629d69b4a2afaf113cb472eb075734122
Rust
hawkw/mycelium
/util/src/macros.rs
UTF-8
3,501
2.640625
3
[ "MIT" ]
permissive
macro_rules! loom_const_fn { ( $(#[$meta:meta])* $vis:vis fn $name:ident($($arg:ident: $T:ty),*) -> $Ret:ty $body:block ) => { $(#[$meta])* #[cfg(not(loom))] $vis const fn $name($($arg: $T),*) -> $Ret $body $(#[$meta])* #[cfg(loom)] $vis fn $name($($arg: $T),*) -> $Ret $body } } /// Indicates unreachable code that we are confident is *truly* unreachable. /// /// This is essentially a compromise between `core::unreachable!()` and /// `core::hint::unreachable_unchecked()`. In debug mode builds and in tests, /// this expands to `unreachable!()`, causing a panic. However, in release mode /// non-test builds, this expands to `unreachable_unchecked`. Thus, this is a /// somewhat safer form of `unreachable_unchecked` that will allow cases where /// `unreachable_unchecked` would be invalid to be detected early. /// /// Nonetheless, this must still be used with caution! If code is not adequately /// tested, it is entirely possible for the `unreachable_unchecked` to be /// reached in a scenario that was not reachable in tests. #[macro_export] macro_rules! unreachable_unchecked { () => ({ #[cfg(any(test, debug_assertions))] panic!( "internal error: entered unreachable code \n\", /!\\ EXTREMELY SERIOUS WARNING: in release mode, this would have been \n\ \x32 `unreachable_unchecked`! This could result in undefine behavior. \n\ \x32 Please double- or triple-check any assumptions about code which \n\ \x32 could lead to this being triggered." ); #[allow(unreachable_code)] // lol { core::hint::unreachable_unchecked(); } }); ($msg:expr) => ({ $crate::unreachable_unchecked!("{}", $msg) }); ($msg:expr,) => ({ $crate::unreachable_unchecked!($msg) }); ($fmt:expr, $($arg:tt)*) => ({ #[cfg(any(test, debug_assertions))] panic!( concat!( "internal error: entered unreachable code: ", $fmt, "\n/!\\ EXTREMELY SERIOUS WARNING: in release mode, this would have been \n\ \x32 `unreachable_unchecked`! This could result in undefine behavior. \n\ \x32 Please double- or triple-check any assumptions about code which \n\ \x32 could lead to this being triggered." ), $($arg)* ); #[allow(unreachable_code)] // lol { core::hint::unreachable_unchecked(); } }); } #[cfg(test)] macro_rules! test_dbg { ($x:expr) => { match $x { x => { test_trace!( location = %core::panic::Location::caller(), "{} = {x:?}", stringify!($x) ); x } } }; } #[cfg(not(test))] macro_rules! test_dbg { ($x:expr) => { $x }; } #[cfg(all(test, not(loom)))] macro_rules! test_trace { ($($arg:tt)+) => { tracing::trace!($($arg)+); }; } #[cfg(all(test, loom))] macro_rules! test_trace { ($($arg:tt)+) => { tracing_01::trace!($($arg)+); }; } #[cfg(all(test, not(loom)))] macro_rules! test_info { ($($arg:tt)+) => { tracing::trace!($($arg)+); }; } #[cfg(all(test, loom))] macro_rules! test_info { ($($arg:tt)+) => { tracing_01::trace!($($arg)+); }; }
true
a526dd222d9fb221344c84df28521a1a98c20095
Rust
arbimo/postnu
/src/labels.rs
UTF-8
12,201
3.046875
3
[]
no_license
use crate::algebra::*; use std::fmt::{Display, Error, Formatter}; #[derive(Clone, Copy, Debug)] pub struct Wait<N, W> { pub node: N, pub delay: W, } #[derive(Clone, Debug)] pub struct Lab<N, W> { pub root: Option<N>, pub scalar: W, pub waits: Vec<Wait<N, W>>, } impl<N, W> Lab<N, W> where N: Ord + Copy + PartialEq, W: FloatLike, { pub fn from_scalar(w: W) -> Self { Lab { root: None, scalar: w, waits: vec![], } } pub fn new(root: Option<N>, scalar: W, min_terms: &[(N, W)]) -> Self { Lab { root, scalar, waits: min_terms .iter() .map(|(n, w)| Wait { node: *n, delay: *w, }) .collect(), } } pub fn new_from_vec(root: Option<N>, scalar: W, waits: Vec<Wait<N, W>>) -> Self { Lab { root, scalar, waits, } } pub fn as_pure_scalar(&self) -> Option<W> { if self.waits.is_empty() { Some(self.scalar) } else { None } } fn add_to_all(&mut self, d: W) { self.scalar += d; for e in &mut self.waits { e.delay += d } } pub fn normalize(&mut self) { // sort by increasing node number // then, for each node, sort its delays in increasing order self.waits.sort_by_key(|w| w.node); } fn assert_valid(&self) { debug_assert!(self.impl_check_valid()); } fn impl_check_valid(&self) -> bool { let mut tmp = self.waits.clone(); tmp.sort_by_key(|w| w.node); // assert!(self.waits == tmp, "Not sorted"); tmp.dedup_by_key(|w| w.node); // assert!(self.waits == tmp, "Duplicated labels"); true } fn compare<F>(a: &Self, b: &Self, cmp: F) -> Dominance where F: Fn(W, W) -> std::cmp::Ordering, { use std::cmp::Ordering::*; a.assert_valid(); b.assert_valid(); let mut state = Dominance::init(); match cmp(a.scalar, b.scalar) { Less => state.left_win(), Greater => state.right_win(), Equal => (), } let mut ai = 0; let mut bi = 0; loop { println!("{} / {}", ai, bi); if ai == a.waits.len() && bi == b.waits.len() { return state; } else if ai == a.waits.len() { // ai has less disjuncts and is tighter on those state.left_win(); return state; } else if bi == b.waits.len() { // ai has less disjuncts and is tighter on those state.right_win(); return state; } else { let aw = a.waits[ai]; let bw = b.waits[bi]; if aw.node == bw.node { match cmp(aw.delay, bw.delay) { Less => state.left_win(), Greater => state.right_win(), Equal => (), } ai += 1; bi += 1; } else if aw.node < bw.node { // right is missing a node state.right_win(); ai += 1; } else { // left is missing a node state.left_win(); bi += 1; } } } } } struct Dominance { // true if part of the left term strictly dominates the correspond right part // corollary: if false : left is subsumed by right left: bool, // true if part of the right term strictly dominates the correspond left part // corollary: if false : right is subsumed by left right: bool, } impl Dominance { fn init() -> Self { Dominance { left: false, right: false, } } fn left_win(&mut self) { self.left = true; } fn right_win(&mut self) { self.right = true; } pub fn identical(&self) -> bool { !self.left && !self.right } pub fn left_dominates(&self) -> bool { self.left && !self.right } pub fn right_dominates(&self) -> bool { !self.left && self.right } pub fn none_dominates(&self) -> bool { self.left && self.right } } #[derive(Clone, Debug)] pub enum Label<N, W> { Min(Lab<N, W>), Max(Lab<N, W>), } impl<N, W> Label<N, W> where N: Copy + Ord, W: FloatLike, { pub fn from_scalar(w: W) -> Self { let ret = if w < W::zero() { Label::Min(Lab::from_scalar(-w)) } else { Label::Max(Lab::from_scalar(w)) }; ret.check(); ret } pub fn negative(root: Option<N>, scalar: W, min_terms: &[(N, W)]) -> Self { Label::Min(Lab::new(root, scalar, min_terms)) } pub fn min(root: Option<N>, scalar: W, min_terms: Vec<Wait<N, W>>) -> Self { Label::Min(Lab::new_from_vec(root, scalar, min_terms)) } pub fn positive(root: Option<N>, scalar: W, min_terms: &[(N, W)]) -> Self { Label::Max(Lab::new(root, scalar, min_terms)) } pub fn max(root: Option<N>, scalar: W, min_terms: Vec<Wait<N, W>>) -> Self { Label::Max(Lab::new_from_vec(root, scalar, min_terms)) } pub fn is_min(&self) -> bool { match self { Label::Min(_) => true, Label::Max(_) => false, } } pub fn is_max(&self) -> bool { !self.is_min() } pub fn tighten(&mut self) { match self { Label::Min(l) => { for w in &mut l.waits { if w.delay < W::zero() { w.delay = W::zero(); } } } Label::Max(l) => { l.waits.retain(|w| w.delay >= W::zero()); } } self.check(); } pub fn label(&self) -> &Lab<N, W> { match self { Label::Min(l) => l, Label::Max(l) => l, } } pub fn label_mut(&mut self) -> &mut Lab<N, W> { match self { Label::Min(l) => l, Label::Max(l) => l, } } pub fn root(&self) -> Option<N> { self.label().root } pub fn scalar(&self) -> W { self.label().scalar } pub fn add_to_all_terms(&mut self, w: W) { // self.check(); self.label_mut().add_to_all(w); self.tighten(); self.check(); } pub fn subsumes(&self, other: &Self) -> bool { match (self, other) { (Label::Min(la), Label::Min(lb)) => { let comparison = Lab::compare(la, lb, |a, b| W::cmp(&a, &b).reverse()); comparison.identical() || comparison.left_dominates() } (Label::Max(la), Label::Max(lb)) => { let comparison = Lab::compare(la, lb, |a, b| W::cmp(&a, &b)); comparison.identical() || comparison.left_dominates() } (Label::Min(_), Label::Max(_)) => true, (Label::Max(_), Label::Min(_)) => false, } } pub fn check(&self) { debug_assert!(self.scalar() >= W::zero()); debug_assert!(self.is_max() || self.scalar() > W::zero()); debug_assert!(self.label().waits.iter().all(|w| w.delay >= W::zero())); } } //impl<N, W> Display for Label<N, W> //where // N: ToIndex + Copy, // W: Display, //{ // fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { // match self { // Label::Min(Lab { // root: _, // scalar: delay, // waits, // }) => { // if waits.is_empty() { // write!(f, "- {}", delay)?; // } else { // write!(f, "- min {} [ ", delay)?; // for w in waits { // write!(f, "({}, {}) ", w.node.to_index(), w.delay)?; // } // write!(f, "]")?; // } // } // Label::Max(Lab { // root: _, // scalar: delay, // waits, // }) => { // if waits.is_empty() { // write!(f, " {}", delay)?; // } else { // write!(f, " max {} [ ", delay)?; // for w in waits { // write!(f, "({}, {}) ", w.node.to_index(), w.delay)?; // } // write!(f, "]")?; // } // } // } // Result::Ok(()) // } //} impl<N, W> Display for Label<N, W> where N: Display + Copy, W: Display, { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match self { Label::Min(Lab { root: _, scalar: delay, waits, }) => { if waits.is_empty() { write!(f, "- {}", delay)?; } else { write!(f, "- min {} [ ", delay)?; for w in waits { write!(f, "({}, {}) ", w.node, w.delay)?; } write!(f, "]")?; } } Label::Max(Lab { root: _, scalar: delay, waits, }) => { if waits.is_empty() { write!(f, " {}", delay)?; } else { write!(f, " max {} [ ", delay)?; for w in waits { write!(f, "({}, {}) ", w.node, w.delay)?; } write!(f, "]")?; } } } Result::Ok(()) } } #[cfg(test)] mod tests { use super::*; type L = Label<i32, i32>; #[test] fn dominance() { let a: L = Label::from_scalar(1); let b: L = Label::from_scalar(2); let c: L = Label::from_scalar(-1); let d: L = Label::from_scalar(-2); assert!(a.subsumes(&b)); assert!(a.subsumes(&a)); assert!(!b.subsumes(&a)); assert!(d.subsumes(&c)); assert!(!c.subsumes(&d)); assert!(!a.subsumes(&c)); assert!(c.subsumes(&a)); let p1 = Label::positive(None, 1, &[(1, 4)]); let p2 = Label::positive(None, 1, &[(1, 3)]); // assert!(p2.subsumes(&p1)); assert!(!p1.subsumes(&p2)); let p1 = Label::positive(None, 1, &[(1, 4), (2, 4)]); // those strictly dominate p1 let p2 = Label::positive(None, 1, &[(1, 3), (2, 4)]); let p3 = Label::positive(None, 1, &[(1, 4), (2, 3)]); let p4 = Label::positive(None, 1, &[(1, 4)]); let p5 = Label::positive(None, 0, &[(1, 4), (2, 4)]); for (i, other) in [p2, p3, p4, p5].iter().enumerate() { assert!(other.subsumes(&p1), "p{}", i + 2); assert!(!p1.subsumes(&other), "!(p1 subsumes p{})", i + 2); } // none dominate the other let p12 = Label::positive(None, 0, &[(1, 5), (2, 4)]); let p13 = Label::positive(None, 0, &[(1, 5), (2, 4), (3, 2)]); for (i, other) in [p12, p13].iter().enumerate() { assert!(!other.subsumes(&p1), "{}", i); assert!(!p1.subsumes(&other), "{}", i); } let p1 = Label::negative(None, 1, &[(1, 4), (2, 4)]); // those strictly dominate p1 let p2 = Label::negative(None, 1, &[(1, 3), (2, 4)]); let p3 = Label::negative(None, 1, &[(1, 4), (2, 3)]); let p4 = Label::negative(None, 1, &[(1, 4), (2, 4), (3, 4)]); let p5 = Label::negative(None, 0, &[(1, 4), (2, 4)]); for (i, other) in [p2, p3, p4, p5].iter().enumerate() { assert!(!other.subsumes(&p1), "p{}", i + 2); assert!(p1.subsumes(&other), "!(p1 subsumes p{})", i + 2); } } }
true
cb2da0608ff701ea5cfafe7f91d2b83313cbac99
Rust
Ogeon/rust-wiringpi
/src/lib.rs
UTF-8
20,365
2.78125
3
[ "MIT" ]
permissive
#![doc(html_root_url = "http://ogeon.github.io/docs/rust-wiringpi/master/")] #![cfg_attr(feature = "strict", deny(warnings))] extern crate libc; use std::marker::PhantomData; use pin::{Pin, Pwm, GpioClock, RequiresRoot}; macro_rules! impl_pins { ($($name:ident),+) => ( $( #[derive(Clone, Copy)] pub struct $name; impl Pin for $name {} )+ ) } macro_rules! impl_pwm { ($($name:ident: $pwm:expr),+) => ( $( impl Pwm for $name { #[inline] fn pwm_pin() -> PwmPin<$name> { PwmPin::new($pwm) } } )+ ) } macro_rules! impl_clock { ($($name:ident: $pwm:expr),+) => ( $( impl GpioClock for $name { #[inline] fn clock_pin() -> ClockPin<$name> { ClockPin::new($pwm) } } )+ ) } macro_rules! require_root { ($($name:ident),+) => ( $( impl RequiresRoot for $name {} )+ ) } mod bindings; pub mod thread { use bindings; use libc; ///This attempts to shift your program (or thread in a multi-threaded ///program) to a higher priority and enables a real-time scheduling. /// ///The priority parameter should be from 0 (the default) to 99 (the ///maximum). This won’t make your program go any faster, but it will give ///it a bigger slice of time when other programs are running. The priority ///parameter works relative to others – so you can make one program ///priority 1 and another priority 2 and it will have the same effect as ///setting one to 10 and the other to 90 (as long as no other programs are ///running with elevated priorities) /// ///The return value is `true` for success and `false` for error. If an ///error is returned, the program should then consult the _errno_ global ///variable, as per the usual conventions. /// ///_Note_: Only programs running as root can change their priority. If ///called from a non-root program then nothing happens. pub fn priority(priority: u8) -> bool { unsafe { bindings::piHiPri(priority as libc::c_int) >= 0 } } } pub mod pin { use bindings; use libc; use self::Value::{Low, High}; use std::marker::PhantomData; const INPUT: libc::c_int = 0; const OUTPUT: libc::c_int = 1; const PWM_OUTPUT: libc::c_int = 2; const GPIO_CLOCK: libc::c_int = 3; //const SOFT_PWM_OUTPUT: libc::c_int = 4; //const SOFT_TONE_OUTPUT: libc::c_int = 5; //const PWM_TONE_OUTPUT: libc::c_int = 6; ///This returns the BCM_GPIO pin number of the supplied **wiringPi** pin. /// ///It takes the board revision into account. pub fn wpi_to_gpio_number(wpi_number: u16) -> u16 { unsafe { bindings::wpiPinToGpio(wpi_number as libc::c_int) as u16 } } ///This returns the BCM_GPIO pin number of the supplied physical pin on ///the P1 connector. pub fn phys_to_gpio_number(phys_number: u16) -> u16 { unsafe { bindings::physPinToGpio(phys_number as libc::c_int) as u16 } } impl_pins!(WiringPi, Gpio, Phys, Sys); impl_pwm!(WiringPi: 1, Gpio: 18, Phys: 12); impl_clock!(WiringPi: 7, Gpio: 4, Phys: 7); require_root!(WiringPi, Gpio, Phys); pub trait Pin {} pub trait Pwm: RequiresRoot + Sized { fn pwm_pin() -> PwmPin<Self>; } pub trait GpioClock: RequiresRoot + Sized { fn clock_pin() -> ClockPin<Self>; } pub trait RequiresRoot: Pin {} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Value { Low = 0, High } #[derive(Debug, Clone, Copy)] pub enum Edge { ///No setup is performed, it is assumed the trigger has already been set up previosuly Setup = 0, Falling = 1, Rising = 2, Both = 3 } #[derive(Debug, Clone, Copy)] pub enum Pull { Off = 0, Down, Up } #[derive(Debug, Clone, Copy)] pub enum PwmMode { MarkSpace = 0, Balanced } pub struct InputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> InputPin<P> { pub fn new(pin: libc::c_int) -> InputPin<P> { unsafe { bindings::pinMode(pin, INPUT); } InputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &InputPin(number, _) = self; number } ///This function returns the value read at the given pin. /// ///It will be `High` or `Low` (1 or 0) depending on the logic level at the pin. pub fn digital_read(&self) -> Value { let value = unsafe { bindings::digitalRead(self.number()) }; if value == 0 { Low } else { High } } ///This returns the value read on the supplied analog input pin. You ///will need to register additional analog modules to enable this ///function for devices such as the Gertboard, quick2Wire analog ///board, etc. pub fn analog_read(&self) -> u16 { unsafe { bindings::analogRead(self.number()) as u16 } } /// This will register an "Interrupt" to be called when the pin changes state /// Note the quotes around Interrupt, because the current implementation in the C /// library seems to be a dedicated thread that polls the gpio device driver, /// and this callback is called from that thread synchronously, so it's not something that /// you would call a real interrupt in an embedded environement. /// /// The callback function does not need to be reentrant. /// /// The callback must be an actual function (not a closure!), and must be using /// the extern "C" modifier so that it can be passed to the wiringpi library, /// and called from C code. /// /// Unfortunately the C implementation does not allow userdata to be passed around, /// so the callback must be able to determine what caused the interrupt just by the /// function that was invoked. /// /// See https://github.com/Ogeon/rust-wiringpi/pull/28 for /// ideas on how to work around these limitations if you find them too constraining. /// /// ``` /// use wiringpi; /// /// extern "C" fn change_state() { /// println!("Look ma, I'm being called from an another thread"); /// } /// /// fn main() { /// let pi = wiringpi::setup(); /// let pin = pi.output_pin(0); /// /// pin.register_isr(Edge::Falling, Some(change_state)); /// /// thread::sleep(60000); /// } /// /// ``` /// /// pub fn register_isr(&self, edge: Edge, f: Option<extern "C" fn()>) { unsafe { bindings::wiringPiISR(self.number(), edge as i32, f); } } } impl<P: Pin + RequiresRoot> InputPin<P> { ///This sets the pull-up or pull-down resistor mode on the given pin. /// ///Unlike the Arduino, the BCM2835 has both pull-up an down internal ///resistors. The parameter pud should be; `Off`, (no pull up/down), ///`Down` (pull to ground) or `Up` (pull to 3.3v) pub fn pull_up_dn_control(&self, pud: Pull) { unsafe { bindings::pullUpDnControl(self.number(), pud as libc::c_int); } } pub fn into_output(self) -> OutputPin<P> { let InputPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let InputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + Pwm> InputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let InputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> InputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let InputPin(number, _) = self; ClockPin::new(number) } } /// A pin with software controlled PWM output. /// /// Due to limitations of the chip only one pin is able to do /// hardware-controlled PWM output. The `SoftPwmPin`s on the /// other hand allow for all GPIOs to output PWM signals. /// /// The pulse width of the signal will be 100μs with a value range /// of [0,100] \(where `0` is a constant low and `100` is a /// constant high) resulting in a frequenzy of 100 Hz. /// /// **Important**: In order to use software PWM pins *wiringPi* /// has to be setup in GPIO mode via `setup_gpio()`. pub struct SoftPwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + RequiresRoot> SoftPwmPin<P> { /// Configures the given `pin` to output a software controlled PWM /// signal. pub fn new(pin: libc::c_int) -> SoftPwmPin<P> { unsafe { bindings::softPwmCreate(pin, 0, 100); } SoftPwmPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &SoftPwmPin(number, _) = self; number } /// Sets the duty cycle. /// /// `value` has to be in the interval [0,100]. pub fn pwm_write(&self, value: libc::c_int) { unsafe { bindings::softPwmWrite(self.number(), value); } } /// Stops the software handling of this pin. /// /// _Note_: In order to control this pin via software PWM again /// it will need to be recreated using `new()`. pub fn pwm_stop(self) { unsafe { bindings::softPwmStop(self.number()); } } pub fn into_input(self) -> InputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); OutputPin::new(number) } } impl<P: Pin + Pwm> SoftPwmPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); PwmPin::new(number) } } impl<P: Pin + GpioClock> SoftPwmPin<P> { pub fn into_clock(self) -> ClockPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); ClockPin::new(number) } } pub struct OutputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> OutputPin<P> { pub fn new(pin: libc::c_int) -> OutputPin<P> { unsafe { bindings::pinMode(pin, OUTPUT); } OutputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &OutputPin(number, _) = self; number } ///Writes the value `High` or `Low` (1 or 0) to the given pin which must have been previously set as an output. pub fn digital_write(&self, value: Value) { unsafe { bindings::digitalWrite(self.number(), value as libc::c_int); } } ///This writes the given value to the supplied analog pin. You will ///need to register additional analog modules to enable this function ///for devices such as the Gertboard. pub fn analog_write(&self, value: u16) { unsafe { bindings::analogWrite(self.number(), value as libc::c_int); } } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let OutputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_input(self) -> InputPin<P> { let OutputPin(number, _) = self; InputPin::new(number) } } impl<P: Pin + Pwm> OutputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let OutputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> OutputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let OutputPin(number, _) = self; ClockPin::new(number) } } ///To understand more about the PWM system, you’ll need to read the Broadcom ARM peripherals manual. pub struct PwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + Pwm> PwmPin<P> { pub fn new(pin: libc::c_int) -> PwmPin<P> { unsafe { bindings::pinMode(pin, PWM_OUTPUT); } PwmPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &PwmPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let PwmPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let PwmPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let PwmPin(number, _) = self; SoftPwmPin::new(number) } ///Writes the value to the PWM register for the given pin. /// ///The value must be between 0 and 1024. pub fn write(&self, value: u16) { unsafe { bindings::pwmWrite(self.number(), value as libc::c_int); } } ///The PWM generator can run in 2 modes – "balanced" and "mark:space". /// ///The mark:space mode is traditional, however the default mode in the ///Pi is "balanced". You can switch modes by supplying the parameter: ///`Balanced` or `MarkSpace`. pub fn set_mode(&self, mode: PwmMode) { unsafe { bindings::pwmSetMode(mode as libc::c_int); } } ///This sets the range register in the PWM generator. The default is 1024. pub fn set_range(&self, value: u16) { unsafe { bindings::pwmSetRange(value as libc::c_uint); } } ///This sets the divisor for the PWM clock. pub fn set_clock(&self, value: u16) { unsafe { bindings::pwmSetClock(value as libc::c_int); } } } pub struct ClockPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + GpioClock> ClockPin<P> { pub fn new(pin: libc::c_int) -> ClockPin<P> { unsafe { bindings::pinMode(pin, GPIO_CLOCK); } ClockPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &ClockPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let ClockPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let ClockPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let ClockPin(number, _) = self; SoftPwmPin::new(number) } ///Set the freuency on a GPIO clock pin. pub fn frequency(&self, freq: u16) { unsafe { bindings::gpioClockSet(self.number(), freq as libc::c_int); } } } } ///This initialises the wiringPi system and assumes that the calling program ///is going to be using the **wiringPi** pin numbering scheme. /// ///This is a simplified numbering scheme which provides a mapping from virtual ///pin numbers 0 through 16 to the real underlying Broadcom GPIO pin numbers. ///See the pins page for a table which maps the **wiringPi** pin number to the ///Broadcom GPIO pin number to the physical location on the edge connector. /// ///This function needs to be called with root privileges. pub fn setup() -> WiringPi<pin::WiringPi> { unsafe { bindings::wiringPiSetup(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the Broadcom GPIO pin numbers directly with no re-mapping. /// ///This function needs to be called with root privileges. pub fn setup_gpio() -> WiringPi<pin::Gpio> { unsafe { bindings::wiringPiSetupGpio(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the physical pin numbers _on the P1 connector only_. /// ///This function needs to be called with root privileges. pub fn setup_phys() -> WiringPi<pin::Phys> { unsafe { bindings::wiringPiSetupPhys(); } WiringPi(PhantomData) } ///This initialises the wiringPi system but uses the /sys/class/gpio interface ///rather than accessing the hardware directly. /// ///This can be called as a non-root user provided the GPIO pins have been ///exported before-hand using the gpio program. Pin number in this mode is the ///native Broadcom GPIO numbers. /// ///_Note_: In this mode you can only use the pins which have been exported via ///the /sys/class/gpio interface. You must export these pins before you call ///your program. You can do this in a separate shell-script, or by using the ///system() function from inside your program. /// ///Also note that some functions have no effect when using this mode as ///they’re not currently possible to action unless called with root ///privileges. pub fn setup_sys() -> WiringPi<pin::Sys> { unsafe { bindings::wiringPiSetupSys(); } WiringPi(PhantomData) } ///This returns the board revision of the Raspberry Pi. /// ///It will be either 1 or 2. Some of the BCM_GPIO pins changed number and ///function when moving from board revision 1 to 2, so if you are using ///BCM_GPIO pin numbers, then you need to be aware of the differences. pub fn board_revision() -> i32 { unsafe { bindings::piBoardRev() } } pub struct WiringPi<Pin>(PhantomData<Pin>); impl<P: Pin> WiringPi<P> { pub fn input_pin(&self, pin: u16) -> pin::InputPin<P> { let pin = pin as libc::c_int; pin::InputPin::new(pin) } pub fn output_pin(&self, pin: u16) -> pin::OutputPin<P> { let pin = pin as libc::c_int; pin::OutputPin::new(pin) } ///This returns a number representing the number if milliseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 49 days. pub fn millis(&self) -> u32 { unsafe { bindings::millis() } } ///This returns a number representing the number if microseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 71 minutes. pub fn micros(&self) -> u32 { unsafe { bindings::micros() } } ///This writes the 8-bit byte supplied to the first 8 GPIO pins. It’s the ///fastest way to set all 8 bits at once to a particular value, although ///it still takes two write operations to the Pi’s GPIO hardware. pub fn digital_write_byte(&self, byte: u8) { unsafe { bindings::digitalWriteByte(byte as libc::c_int); } } } impl<P: Pwm + Pin> WiringPi<P> { pub fn pwm_pin(&self) -> pin::PwmPin<P> { Pwm::pwm_pin() } } impl<P: GpioClock + Pin> WiringPi<P> { pub fn clock_pin(&self) -> pin::ClockPin<P> { GpioClock::clock_pin() } } impl<P: Pin + RequiresRoot> WiringPi<P> { pub fn soft_pwm_pin(&self, pin: u16) -> pin::SoftPwmPin<P> { let pin = pin as libc::c_int; pin::SoftPwmPin::new(pin) } }
true
3b7acb8df1c4ece5c45dc7d519409e9da5f9a85a
Rust
julienduchesne/challenges
/backend/src/groups/advent_of_code_2020/day20.rs
UTF-8
14,797
2.96875
3
[]
no_license
use std::collections::HashSet; use anyhow::Result; use ndarray::{Array, Array2, Axis}; use num_integer::Roots; use rand::seq::SliceRandom; use crate::groups::challenge_config::ChallengeConfig; pub struct Day20 {} trait FlipRotate { fn rotate(&mut self); fn flip_horizontal(&mut self); fn flip_vertical(&mut self); } impl FlipRotate for Array2<bool> { fn rotate(&mut self) { let clone = self.clone(); for ((x, y), item) in clone.indexed_iter() { self[(y, clone.nrows() - x - 1)] = *item; } } fn flip_horizontal(&mut self) { let clone = self.clone(); for ((x, y), item) in clone.indexed_iter() { self[(x, clone.nrows() - y - 1)] = *item; } } fn flip_vertical(&mut self) { let clone = self.clone(); for ((x, y), item) in clone.indexed_iter() { self[(clone.nrows() - x - 1, y)] = *item; } } } #[derive(Clone)] struct Tile { id: usize, array: Array2<bool>, adjacent: [Option<usize>; 4], } impl Tile { fn parse(tile: &str) -> Result<Self> { let array_lines: Vec<&str> = tile.split(":").nth(1).unwrap().trim().split("\n").collect(); let n = array_lines.len(); let mut array: Array2<bool> = Array2::from_shape_fn((n, n), |_| false); for (i, mut row) in array.axis_iter_mut(Axis(0)).enumerate() { row.assign(&Array::from( array_lines[i] .trim() .chars() .map(|x| match x { '#' => true, _ => false, }) .collect::<Vec<bool>>(), )); } return Ok(Self { id: tile.split(":").nth(0).unwrap().trim().parse::<usize>()?, array: array, adjacent: [None, None, None, None], }); } // top, right, bottom, left fn get_sides(&self) -> Vec<Vec<bool>> { return [ self.array.row(0), self.array.column(self.array.ncols() - 1), self.array.row(self.array.nrows() - 1), self.array.column(0), ] .iter() .map(|x| x.iter().map(|e| *e).collect::<Vec<bool>>()) .collect(); } fn rotate(&mut self) { self.array.rotate(); self.adjacent = [ self.adjacent[3], self.adjacent[0], self.adjacent[1], self.adjacent[2], ]; } fn flip_vertical(&mut self) { self.array.flip_vertical(); self.adjacent = [ self.adjacent[2], self.adjacent[1], self.adjacent[0], self.adjacent[3], ]; } fn flip_horizontal(&mut self) { self.array.flip_horizontal(); self.adjacent = [ self.adjacent[0], self.adjacent[3], self.adjacent[2], self.adjacent[1], ]; } } impl ChallengeConfig for Day20 { fn title(&self) -> &str { return "Day 20: Jurassic Jigsaw"; } fn solve(&self, input: &str) -> Result<String> { let mut tiles: Vec<Tile> = input .split("Tile") .map(|x| x.trim()) .filter(|x| !x.is_empty()) .map(Tile::parse) .collect::<Result<_, _>>()?; // Find adjacent tiles let tiles_clone = tiles.clone(); for tile in tiles.iter_mut() { for other_tile in &tiles_clone { for (i, side) in tile.get_sides().iter().enumerate() { if other_tile.id == tile.id { continue; } let other_sides = other_tile.get_sides(); if other_sides.contains(&side.iter().rev().map(|x| *x).collect()) || other_sides.contains(side) { tile.adjacent[i] = Some(other_tile.id); } } } } let corner_tiles: Vec<&Tile> = tiles .iter() .filter(|t| t.adjacent.iter().filter(|x| x.is_none()).count() == 2) .collect(); let part_one: usize = corner_tiles.iter().map(|x| x.id).product::<usize>(); // Includes corners let side_tiles: Vec<&Tile> = tiles .iter() .filter(|t| t.adjacent.iter().filter(|x| x.is_none()).count() >= 1) .collect(); // Calculate array of array let size = tiles.len().sqrt(); let mut array_of_tiles: Array2<usize> = Array2::zeros((size, size)); let mut handled: HashSet<usize> = HashSet::new(); for x in 0..size { for y in 0..size { let new_value: usize; if x == 0 && y == 0 { new_value = corner_tiles.iter().next().unwrap().id; } else if x == 0 { let previous = array_of_tiles.get((0, y - 1)).unwrap().clone(); new_value = side_tiles .iter() .find(|t| !handled.contains(&t.id) && t.adjacent.contains(&Some(previous))) .unwrap() .id; } else if y == 0 { let previous_x = array_of_tiles.get((x - 1, y)).unwrap().clone(); new_value = side_tiles .iter() .find(|t| { !handled.contains(&t.id) && t.adjacent.contains(&Some(previous_x)) }) .unwrap() .id; } else { let previous_x = array_of_tiles.get((x - 1, y)).unwrap().clone(); let previous_y = array_of_tiles.get((x, y - 1)).unwrap().clone(); new_value = tiles .iter() .find(|t| { !handled.contains(&t.id) && t.adjacent.contains(&Some(previous_x)) && t.adjacent.contains(&Some(previous_y)) }) .unwrap() .id; } handled.insert(new_value); array_of_tiles[(x, y)] = new_value; } } // Flip and rotate tiles in the array of tiles for ((x, y), tile_id) in array_of_tiles.indexed_iter() { // top, right, bottom, left let mut previous_x = size; let mut previous_y = size; if x != 0 { previous_x = x - 1; } if y != 0 { previous_y = y - 1; } let expected = [ array_of_tiles.get((previous_x, y)), array_of_tiles.get((x, y + 1)), array_of_tiles.get((x + 1, y)), array_of_tiles.get((x, previous_y)), ]; let tile = tiles.iter_mut().find(|t| t.id == *tile_id).unwrap(); while (0..3).any(|x| tile.adjacent[x].as_ref() != expected[x]) { // Random flip and rotate till it works :shrug: match (vec![0, 1, 2]).choose(&mut rand::thread_rng()).unwrap() { 0 => tile.flip_horizontal(), 1 => tile.flip_vertical(), 2 => tile.rotate(), _ => {} }; } } let tile_size = tiles[0].array.ncols(); let final_array_size = size * (tile_size - 2); let mut final_array: Array2<bool> = Array2::from_shape_fn((final_array_size, final_array_size), |_| false); for ((tile_x, tile_y), tile_id) in array_of_tiles.indexed_iter() { let tile = tiles.iter().find(|t| t.id == *tile_id).unwrap(); for ((x, y), item) in tile.array.indexed_iter() { if x == 0 || x == tile_size - 1 || y == 0 || y == tile_size - 1 { continue; } final_array[( tile_x * (tile_size - 2) + x - 1, tile_y * (tile_size - 2) + y - 1, )] = *item; } } let mut sea_monsters = 0; let mut monster_shape: Array2<bool> = Array2::from_shape_fn((3, 20), |_| false); monster_shape[(0, 18)] = true; monster_shape[(1, 0)] = true; monster_shape[(1, 5)] = true; monster_shape[(1, 6)] = true; monster_shape[(1, 11)] = true; monster_shape[(1, 12)] = true; monster_shape[(1, 17)] = true; monster_shape[(1, 18)] = true; monster_shape[(1, 19)] = true; monster_shape[(2, 1)] = true; monster_shape[(2, 4)] = true; monster_shape[(2, 7)] = true; monster_shape[(2, 10)] = true; monster_shape[(2, 13)] = true; monster_shape[(2, 16)] = true; while sea_monsters == 0 { for ((x, y), item) in final_array.indexed_iter() { if x == 0 || *item == false || y + 20 > final_array.ncols() { continue; } let mut good = true; for ((m_x, m_y), m_val) in monster_shape.indexed_iter() { if *m_val == false { continue; } if final_array[(x + m_x - 1, y + m_y)] != true { good = false; break; } } if good { sea_monsters += 1; } } if sea_monsters == 0 { match (vec![0, 1, 2]).choose(&mut rand::thread_rng()).unwrap() { 0 => final_array.rotate(), 1 => final_array.flip_vertical(), 2 => final_array.flip_horizontal(), _ => {} }; } } let part_two: usize = final_array.iter().filter(|x| **x).count() - sea_monsters * 15; return Ok(format!("Part 1: {}\nPart 2: {}", part_one, part_two).to_string()); } } #[cfg(test)] mod tests { use ndarray::arr2; use rstest::rstest; use super::*; #[rstest( tiles, expected, case( "Tile 2311: ..##.#..#. ##..#..... #...##..#. ####.#...# ##.##.###. ##...#.### .#.#.#..## ..#....#.. ###...#.#. ..###..### Tile 1951: #.##...##. #.####...# .....#..## #...###### .##.#....# .###.##### ###.##.##. .###....#. ..#.#..#.# #...##.#.. Tile 1171: ####...##. #..##.#..# ##.#..#.#. .###.####. ..###.#### .##....##. .#...####. #.##.####. ####..#... .....##... Tile 1427: ###.##.#.. .#..#.##.. .#.##.#..# #.#.#.##.# ....#...## ...##..##. ...#.##### .#.####.#. ..#..###.# ..##.#..#. Tile 1489: ##.#.#.... ..##...#.. .##..##... ..#...#... #####...#. #..#.#.#.# ...#.#.#.. ##.#...##. ..##.##.## ###.##.#.. Tile 2473: #....####. #..#.##... #.##..#... ######.#.# .#...#.#.# .######### .###.#..#. ########.# ##...##.#. ..###.#.#. Tile 2971: ..#.#....# #...###... #.#.###... ##.##..#.. .#####..## .#..####.# #..#.#..#. ..####.### ..#.#.###. ...#.#.#.# Tile 2729: ...#.#.#.# ####.#.... ..#.#..... ....#..#.# .##..##.#. .#.####... ####.#.#.. ##.####... ##..#.##.. #.##...##. Tile 3079: #.#.#####. .#..###### ..#....... ######.... ####.#..#. .#...#.##. #.#####.## ..#.###... ..#....... ..#.###...", "Part 1: 20899048083289\nPart 2: 273" ) )] fn solve(tiles: &str, expected: &str) { let day = Day20 {}; assert_eq!(day.solve(tiles).unwrap(), expected); } #[rstest( tile, expected, case( Tile{id: 1, adjacent: [Some(2), Some(3), None, None], array: arr2(&[[true, false, false], [false, false, false], [true, true, true]])}, Tile{id: 1, adjacent: [None, Some(3), Some(2), None], array: arr2(&[[true, true, true], [false, false, false], [true, false, false]])}, ) )] fn flip_vertical(tile: Tile, expected: Tile) { let mut test = tile.clone(); test.flip_vertical(); assert_eq!(test.adjacent, expected.adjacent); assert_eq!(test.array, expected.array); } #[rstest( tile, expected, case( Tile{id: 1, adjacent: [Some(2), Some(3), None, None], array: arr2(&[[true, false, false], [false, false, false], [true, true, true]])}, Tile{id: 1, adjacent: [Some(2), None, None, Some(3)], array: arr2(&[[false, false, true], [false, false, false], [true, true, true]])}, ) )] fn flip_horizontal(tile: Tile, expected: Tile) { let mut test = tile.clone(); test.flip_horizontal(); assert_eq!(test.adjacent, expected.adjacent); assert_eq!(test.array, expected.array); } #[rstest( tile, expected, case( Tile{id: 1, adjacent: [Some(2), Some(3), None, None], array: arr2(&[[true, false, false], [false, false, false], [true, true, true]])}, Tile{id: 1, adjacent: [None, Some(2), Some(3), None], array: arr2(&[[true, false, true], [true, false, false], [true, false, false]])}, ) )] fn rotate(tile: Tile, expected: Tile) { let mut test = tile.clone(); test.rotate(); assert_eq!(test.adjacent, expected.adjacent); assert_eq!(test.array, expected.array); } }
true
42f1f24e02eea09f23a0cdd23b76a51bb37b399f
Rust
ThePants999/advent-of-code-2020
/src/day6.rs
UTF-8
1,034
3.015625
3
[ "CC0-1.0" ]
permissive
use std::collections::HashSet; use crate::utils; pub fn day6(input_lines: &[String]) -> (u64, u64) { let groups = utils::group_lines_split_by_empty_line(input_lines); let (unions, intersections): (Vec<HashSet<char>>, Vec<HashSet<char>>) = groups.iter().map(|group| group_responses(group)).unzip(); let part1 = unions.iter().map(|set| set.len()).sum::<usize>() as u64; let part2 = intersections.iter().map(|set| set.len()).sum::<usize>() as u64; (part1,part2) } fn group_responses(group: &[String]) -> (HashSet<char>, HashSet<char>) { let mut union: HashSet<char> = HashSet::new(); let mut intersection: HashSet<char> = HashSet::new(); union.extend(group[0].chars()); intersection.extend(group[0].chars()); for response in group[1..].iter() { let mut new_set: HashSet<char> = HashSet::new(); for c in response.chars() { union.insert(c); new_set.insert(c); } intersection.retain(|c| new_set.contains(c)); } (union, intersection) }
true
730174af1856580c07279b70f078e0f6506c478c
Rust
regendo/advent-of-code-2019
/day13/src/main.rs
UTF-8
8,207
3.1875
3
[]
no_license
use day09; use std::{collections::HashMap, fmt::Display, io}; use std::{convert::TryFrom, error::Error}; trait Decider: io::BufRead { fn decide_on_move(&mut self, player_position: (i32, i32), ball_position: (i32, i32)); } impl Decider for io::BufReader<io::Stdin> { fn decide_on_move(&mut self, player_position: (i32, i32), ball_position: (i32, i32)) { // Intentionally left blank. () } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Move { Stay, Left, Right, } impl TryFrom<i32> for Move { type Error = String; fn try_from(value: i32) -> Result<Self, Self::Error> { Ok(match value { -1 => Move::Left, 0 => Move::Stay, 1 => Move::Right, _ => return Err(format!("Unexpected value {}", value)), }) } } struct AI { next_move: Move, previous_ball_position: Option<(i32, i32)>, } impl Default for AI { fn default() -> Self { Self { next_move: Move::Stay, previous_ball_position: None, } } } impl Decider for AI { fn decide_on_move(&mut self, player_position: (i32, i32), ball_position: (i32, i32)) { if let Some(prev) = self.previous_ball_position { // >0 -> ball to my right; <0 -> ball to my left; =0 -> ball above me let ball_relative_x = ball_position.0 - player_position.0; // >0 -> ball moves toward right; etc let ball_movement = ball_position.0 - prev.0; // if ball_relative_x == ball_movement { // Ball moves away from me -> I move toward the ball self.next_move = Move::try_from(ball_relative_x.signum()).unwrap(); // } else { // Turns out we don't even need this // } } else { // We don't react on the first turn. This works in practice. self.next_move = Move::Stay; } self.previous_ball_position = Some(ball_position); } } impl io::Read for AI { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { // We just need to have the method for the trait, we don't actually use it. unimplemented!() } } impl io::BufRead for AI { fn fill_buf(&mut self) -> io::Result<&[u8]> { // We just need to have the method for the trait, we don't actually use it. unimplemented!() } fn consume(&mut self, amt: usize) { // We just need to have the method for the trait, we don't actually use it. unimplemented!() } fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { match self.next_move { Move::Stay => { buf.push_str("\n"); Ok(1) } Move::Left => { buf.push_str("\u{1b}[D\n"); Ok(4) } Move::Right => { buf.push_str("\u{1b}[C\n"); Ok(4) } } } } struct GameInput { inner: Box<dyn Decider>, } impl GameInput { fn observe_state(&mut self, player_position: (i32, i32), ball_position: (i32, i32)) { self .inner .as_mut() .decide_on_move(player_position, ball_position); } } impl io::Read for GameInput { #[allow(unused_variables)] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { // We just need to have the method for the trait, we don't actually use it. unimplemented!() } } impl io::BufRead for GameInput { fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() } fn consume(&mut self, amt: usize) { self.inner.consume(amt); } fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { let mut inner_buffer = String::new(); loop { inner_buffer.clear(); let res = self.inner.read_line(&mut inner_buffer); match (&res, &*inner_buffer) { (Err(_), _) | (Ok(0), _) => { buf.push_str(&inner_buffer); return res; } (Ok(4), "\u{1b}[D\n") => { // Left Arrow buf.push_str("-1\n"); return Ok(3); } (Ok(4), "\u{1b}[C\n") => { // Right Arrow buf.push_str("1\n"); return Ok(2); } (Ok(1), "\n") => { // Just Enter buf.push_str("0\n"); return Ok(2); } (Ok(_), _) => { // try again println!("Move with the Left/Right arrows (or don't), then confirm with Enter."); } } } } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Instruction { DrawTile((i32, i32), Tile), Score(i32), } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Tile { Empty, Wall, Block, HorizontalPaddle, Ball, } impl Display for Tile { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { // Empty and Wall are double-width because so are all the emoji Tile::Empty => " ", Tile::Ball => "⚽", Tile::Wall => "▮▮", Tile::Block => "🎁", Tile::HorizontalPaddle => "🏃", } ) } } impl TryFrom<i32> for Tile { type Error = String; fn try_from(value: i32) -> Result<Self, Self::Error> { match value { 0 => Ok(Tile::Empty), 1 => Ok(Tile::Wall), 2 => Ok(Tile::Block), 3 => Ok(Tile::HorizontalPaddle), 4 => Ok(Tile::Ball), _ => Err(format!("Unexpected tile value {}", value)), } } } fn parse_output(raw_output: Vec<u8>) -> Result<Vec<Instruction>, Box<dyn Error>> { let text_output = String::from_utf8(raw_output)?; let mut sanitized_output = text_output .lines() .filter_map(|line| i32::from_str_radix(line.trim(), 10).ok()) .peekable(); let mut instructions = Vec::new(); while let Some(_) = sanitized_output.peek() { match ( sanitized_output.next(), sanitized_output.next(), sanitized_output.next(), ) { (Some(-1), Some(0), Some(score)) => instructions.push(Instruction::Score(score)), (Some(x), Some(y), Some(code)) => { instructions.push(Instruction::DrawTile((x, y), Tile::try_from(code)?)) } _ => Err("Leftover values!")?, } } Ok(instructions) } fn part_1() -> Result<(), Box<dyn Error>> { let mut program = day09::load_program("input.txt", 0xFFFF)?; let mut output = Vec::new(); day09::execute_program(&mut program, io::empty(), &mut output)?; let mut canvas: HashMap<(i32, i32), Tile> = HashMap::new(); let instructions = parse_output(output)?; instructions.iter().for_each(|instruction| { if let Instruction::DrawTile((x, y), tile) = instruction { *canvas.entry((*x, *y)).or_insert(Tile::Empty) = *tile; } }); println!( "{} block tiles visible.", canvas.values().filter(|tile| **tile == Tile::Block).count() ); Ok(()) } fn part_2(reader: Box<dyn Decider>) -> Result<(), Box<dyn Error>> { let mut program = day09::load_program("input.txt", 0xFFFF)?; program[0] = 2; let mut output = Vec::new(); let mut input = GameInput { inner: reader }; let mut idx = 0_usize; let mut state = day09::State::new(); let mut canvas: HashMap<(i32, i32), Tile> = HashMap::new(); let mut score = 0; let mut max_x = 9; let mut max_y = 9; loop { match day09::execute_step(&mut program, &mut idx, &mut state, &mut input, &mut output)? { day09::Opcode::Halt => break, _ => { let next_op = program[idx]; match day09::parse_instruction(next_op as u128) { Ok((day09::Opcode::Input, _)) | Ok((day09::Opcode::Halt, _)) => { if let Ok(instructions) = parse_output(output.clone()) { for instruction in instructions { match instruction { Instruction::Score(value) => score = value, Instruction::DrawTile((x, y), tile) => { *canvas.entry((x, y)).or_insert(Tile::Empty) = tile; if x > max_x { max_x = x; } if y > max_y { max_y = y; } } } } println!("Score: {}", score); let mut player_position = (0, 0); let mut ball_position = (0, 0); for y in 0..=max_y { for x in 0..=max_x { let entry = canvas.get(&(x, y)); print!( "{}", match entry { Some(tile) => *tile, None => Tile::Empty, } ); match entry { Some(Tile::Ball) => ball_position = (x, y), Some(Tile::HorizontalPaddle) => player_position = (x, y), _ => (), } } println!(); } input.observe_state(player_position, ball_position); } } Ok((_, _)) => (), Err(_) => (), } } } } Ok(()) } fn main() -> Result<(), Box<dyn Error>> { // part_1()?; // let reader = Box::new(io::BufReader::new(io::stdin())); let reader = Box::new(AI::default()); part_2(reader)?; Ok(()) }
true
48f4ef8c3a3a51584b80100b4ecafe683664ef89
Rust
akiles/embassy
/embassy-stm32/src/subghz/tx_params.rs
UTF-8
6,000
2.96875
3
[ "Apache-2.0", "MIT" ]
permissive
/// Power amplifier ramp time for FSK, MSK, and LoRa modulation. /// /// Argument of [`set_ramp_time`][`super::TxParams::set_ramp_time`]. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[repr(u8)] pub enum RampTime { /// 10µs Micros10 = 0x00, /// 20µs Micros20 = 0x01, /// 40µs Micros40 = 0x02, /// 80µs Micros80 = 0x03, /// 200µs Micros200 = 0x04, /// 800µs Micros800 = 0x05, /// 1.7ms Micros1700 = 0x06, /// 3.4ms Micros3400 = 0x07, } impl From<RampTime> for u8 { fn from(rt: RampTime) -> Self { rt as u8 } } impl From<RampTime> for core::time::Duration { fn from(rt: RampTime) -> Self { match rt { RampTime::Micros10 => core::time::Duration::from_micros(10), RampTime::Micros20 => core::time::Duration::from_micros(20), RampTime::Micros40 => core::time::Duration::from_micros(40), RampTime::Micros80 => core::time::Duration::from_micros(80), RampTime::Micros200 => core::time::Duration::from_micros(200), RampTime::Micros800 => core::time::Duration::from_micros(800), RampTime::Micros1700 => core::time::Duration::from_micros(1700), RampTime::Micros3400 => core::time::Duration::from_micros(3400), } } } #[cfg(feature = "time")] impl From<RampTime> for embassy_time::Duration { fn from(rt: RampTime) -> Self { match rt { RampTime::Micros10 => embassy_time::Duration::from_micros(10), RampTime::Micros20 => embassy_time::Duration::from_micros(20), RampTime::Micros40 => embassy_time::Duration::from_micros(40), RampTime::Micros80 => embassy_time::Duration::from_micros(80), RampTime::Micros200 => embassy_time::Duration::from_micros(200), RampTime::Micros800 => embassy_time::Duration::from_micros(800), RampTime::Micros1700 => embassy_time::Duration::from_micros(1700), RampTime::Micros3400 => embassy_time::Duration::from_micros(3400), } } } /// Transmit parameters, output power and power amplifier ramp up time. /// /// Argument of [`set_tx_params`][`super::SubGhz::set_tx_params`]. #[derive(Debug, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct TxParams { buf: [u8; 3], } impl TxParams { /// Optimal power setting for +15dBm output power with the low-power PA. /// /// This must be used with [`PaConfig::LP_15`](super::PaConfig::LP_15). pub const LP_15: TxParams = TxParams::new().set_power(0x0E); /// Optimal power setting for +14dBm output power with the low-power PA. /// /// This must be used with [`PaConfig::LP_14`](super::PaConfig::LP_14). pub const LP_14: TxParams = TxParams::new().set_power(0x0E); /// Optimal power setting for +10dBm output power with the low-power PA. /// /// This must be used with [`PaConfig::LP_10`](super::PaConfig::LP_10). pub const LP_10: TxParams = TxParams::new().set_power(0x0D); /// Optimal power setting for the high-power PA. /// /// This must be used with one of: /// /// * [`PaConfig::HP_22`](super::PaConfig::HP_22) /// * [`PaConfig::HP_20`](super::PaConfig::HP_20) /// * [`PaConfig::HP_17`](super::PaConfig::HP_17) /// * [`PaConfig::HP_14`](super::PaConfig::HP_14) pub const HP: TxParams = TxParams::new().set_power(0x16); /// Create a new `TxParams` struct. /// /// This is the same as `default`, but in a `const` function. /// /// # Example /// /// ``` /// use stm32wlxx_hal::subghz::TxParams; /// /// const TX_PARAMS: TxParams = TxParams::new(); /// assert_eq!(TX_PARAMS, TxParams::default()); /// ``` pub const fn new() -> TxParams { TxParams { buf: [super::OpCode::SetTxParams as u8, 0x00, 0x00], } } /// Set the output power. /// /// For low power selected in [`set_pa_config`]: /// /// * 0x0E: +14 dB /// * ... /// * 0x00: 0 dB /// * ... /// * 0xEF: -17 dB /// * Others: reserved /// /// For high power selected in [`set_pa_config`]: /// /// * 0x16: +22 dB /// * ... /// * 0x00: 0 dB /// * ... /// * 0xF7: -9 dB /// * Others: reserved /// /// # Example /// /// Set the output power to 0 dB. /// /// ``` /// use stm32wlxx_hal::subghz::{RampTime, TxParams}; /// /// const TX_PARAMS: TxParams = TxParams::new().set_power(0x00); /// # assert_eq!(TX_PARAMS.as_slice()[1], 0x00); /// ``` /// /// [`set_pa_config`]: super::SubGhz::set_pa_config #[must_use = "set_power returns a modified TxParams"] pub const fn set_power(mut self, power: u8) -> TxParams { self.buf[1] = power; self } /// Set the Power amplifier ramp time for FSK, MSK, and LoRa modulation. /// /// # Example /// /// Set the ramp time to 200 microseconds. /// /// ``` /// use stm32wlxx_hal::subghz::{RampTime, TxParams}; /// /// const TX_PARAMS: TxParams = TxParams::new().set_ramp_time(RampTime::Micros200); /// # assert_eq!(TX_PARAMS.as_slice()[2], 0x04); /// ``` #[must_use = "set_ramp_time returns a modified TxParams"] pub const fn set_ramp_time(mut self, rt: RampTime) -> TxParams { self.buf[2] = rt as u8; self } /// Extracts a slice containing the packet. /// /// # Example /// /// ``` /// use stm32wlxx_hal::subghz::{RampTime, TxParams}; /// /// const TX_PARAMS: TxParams = TxParams::new() /// .set_ramp_time(RampTime::Micros80) /// .set_power(0x0E); /// assert_eq!(TX_PARAMS.as_slice(), &[0x8E, 0x0E, 0x03]); /// ``` pub const fn as_slice(&self) -> &[u8] { &self.buf } } impl Default for TxParams { fn default() -> Self { Self::new() } }
true
92a105b843ce43e793cd9d5c46e1443c881e5dea
Rust
cjab/uoc
/src/uoc.rs
UTF-8
4,844
2.546875
3
[]
no_license
extern crate byteorder; extern crate argparse; extern crate sdl2; mod tile_data; mod index; mod art; mod anim; mod texture; mod color; use tile_data::TileData; use texture::TextureData; use art::ArtData; use anim::AnimationFile; use argparse::{ArgumentParser, Store}; use sdl2::event::Event; use sdl2::surface::Surface; use sdl2::pixels::PixelFormatEnum; struct Options { asset_type: String, index: usize, } fn get_land(index: usize) -> (Vec<u8>, u32, u32) { let art_data = match ArtData::new("data/") { Ok(art) => art, Err(err) => panic!("Error: {:?}", err) }; let tile_data = match TileData::new("data/tiledata.mul") { Ok(data) => data, Err(err) => panic!("Error: {:?}", err) }; let data = tile_data.get_land_tile(index).unwrap(); println!("DATA: {:?}", data); let land_tile = match art_data.get_land(index) { Ok(tile) => tile, Err(err) => panic!("Error: {:?}", err) }; let tile_data = land_tile.as_rgb(); let width = land_tile.width() as u32; let height = land_tile.height() as u32; (tile_data, width, height) } fn get_static(index: usize) -> (Vec<u8>, u32, u32) { let art_data = match ArtData::new("data/") { Ok(art) => art, Err(err) => panic!("Error: {:?}", err) }; let static_tile = match art_data.get_static(index) { Ok(tile) => tile, Err(err) => panic!("Error: {:?}", err) }; let tile_data = match TileData::new("data/tiledata.mul") { Ok(data) => data, Err(err) => panic!("Error: {:?}", err) }; let data = tile_data.get_land_tile(index).unwrap(); println!("DATA: {:?}", data); let width = static_tile.width() as u32; let height = static_tile.height() as u32; (static_tile.as_rgb(), width, height) } fn get_texture(index: usize) -> (Vec<u8>, u32, u32) { let texture_data = match TextureData::new("data/") { Ok(r) => r, Err(err) => panic!("{:?}", err) }; let tile = match texture_data.get(index) { Ok(tile) => tile, Err(err) => panic!("Error: {:?}", err) }; let tile_data = tile.as_rgb(); let width = tile.width() as u32; let height = tile.width() as u32; (tile_data, width, height) } fn get_animation(index: usize) -> (Vec<u8>, u32, u32) { let animation_file = match AnimationFile::new("data/") { Ok(file) => file, Err(err) => panic!("Error: {:?}", err) }; println!("INDEX: {}", index); let animation = match animation_file.get_animation(index) { Ok(anim) => anim, Err(err) => panic!("Error: {:?}", err) }; let frame = animation.get_frame(0).unwrap(); let width = frame.width() as u32; let height = frame.height() as u32; (frame.as_rgb(), width, height) } fn main() { let mut options = Options { asset_type: String::new(), index: 0 as usize }; { let mut parser = ArgumentParser::new(); parser.refer(&mut options.asset_type) .add_argument("asset type", Store, "Type of asset"); parser.refer(&mut options.index) .add_argument("id", Store, "The id of the asset"); parser.parse_args_or_exit(); } let (mut asset_data, width, height) = match options.asset_type.as_ref() { "land" => get_land(options.index), "texture" => get_texture(options.index), "static" => get_static(options.index), "animation" => get_animation(options.index), _ => panic!("Unknown asset type!") }; let mut ctx = sdl2::init().unwrap(); let mut video = ctx.video().unwrap(); let window = match video.window("UOC", width * 5, height * 5).position_centered().opengl().build() { Ok(window) => window, Err(err) => panic!("Failed to created window: {}", err) }; let mut renderer = match window.renderer().build() { Ok(renderer) => renderer, Err(err) => panic!("Failed to create renderer: {}", err) }; let surface = match Surface::from_data(&mut asset_data[..], width, height, 3 * width, PixelFormatEnum::RGB24) { Ok(surface) => surface, Err(err) => panic!("Failed to load surface: {}", err) }; let texture = match renderer.create_texture_from_surface(&surface) { Ok(texture) => texture, Err(err) => panic!("Failed to convert surface: {:?}", err) }; let _ = renderer.clear(); let _ = renderer.copy(&texture, None, None); let _ = renderer.present(); let mut events = ctx.event_pump().unwrap(); 'event: loop { for event in events.poll_iter() { match event { Event::Quit{..} => break 'event, _ => continue } } } } #[test] fn it_works() { }
true
e11af4d382e6f0f6f6b07ec93b30bb8d4e952265
Rust
oliverlee/dominion
/dominion/src/dominion/arena/effect/moneylender.rs
UTF-8
3,038
3.203125
3
[]
no_license
use super::prelude::*; pub(super) const EFFECT: &Effect = &Effect::Conditional( func, "You may trash a Copper from your hand. If you do, +$3.", ); fn func(arena: &mut Arena, player_id: usize, cards: &[CardKind]) -> Result<Outcome> { let error = Err(Error::UnresolvedActionEffect(&EFFECT.description())); if player_id != arena.current_player_id { return error; } if cards.is_empty() { Ok(Outcome::None) } else if (cards.len() == 1) && (cards[0] == CardKind::Copper) { current_player!(arena) .hand .move_card(&mut arena.trash, cards[0]) .map(|_| { arena.turn.as_action_phase_mut().unwrap().remaining_copper += 3; Outcome::None }) .or(error) } else { error } } #[cfg(test)] mod test { use super::super::test_util; use super::*; use crate::dominion::types::Error; use crate::dominion::CardKind; #[test] fn trash_nothing() { let mut arena = test_util::setup_arena(); let player_id = arena.current_player_id; let cards = []; assert_eq!(func(&mut arena, player_id, &cards), Ok(Outcome::None)); assert_eq!(arena.trash, cardvec![]); } #[test] fn trash_non_copper() { let mut arena = test_util::setup_arena(); let player_id = arena.current_player_id; let cards = [CardKind::Silver]; arena.current_player_mut().hand.push(cards[0]); assert_eq!( func(&mut arena, player_id, &cards), Err(Error::UnresolvedActionEffect(EFFECT.description())) ); assert_eq!(arena.trash, cardvec![]); } #[test] fn trash_copper_but_empty_hand() { let mut arena = test_util::setup_arena(); let player_id = arena.current_player_id; let cards = [CardKind::Copper]; arena.current_player_mut().hand.clear(); assert_eq!( func(&mut arena, player_id, &cards), Err(Error::UnresolvedActionEffect(EFFECT.description())) ); assert_eq!(arena.trash, cardvec![]); } #[test] fn trash_copper() { let mut arena = test_util::setup_arena(); let player_id = arena.current_player_id; let cards = [CardKind::Copper]; arena.current_player_mut().hand.clear(); arena.current_player_mut().hand.push(cards[0]); assert_eq!(func(&mut arena, player_id, &cards), Ok(Outcome::None)); assert_eq!(arena.current_player().hand, cardvec![]); assert_eq!(arena.trash, cardvec![CardKind::Copper]); } #[test] fn trash_multiple_cards() { let mut arena = test_util::setup_arena(); let player_id = arena.current_player_id; let cards = [CardKind::Copper, CardKind::Copper]; assert_eq!( func(&mut arena, player_id, &cards), Err(Error::UnresolvedActionEffect(EFFECT.description())) ); assert_eq!(arena.trash, cardvec![]); } }
true
c48d18ed9c76b385801d4070713143faa2362c46
Rust
skyser2003/ditto_bot_rust
/src/slack/test.rs
UTF-8
1,974
2.90625
3
[]
no_license
use super::*; #[test] pub fn test_deserialize_basic_message() { serde_json::from_str::<Message>( r#"{ "type": "message", "channel": "C2147483705", "user": "U2147483697", "text": "Hello world", "ts": "1355517523.000005" }"#, ) .unwrap(); } #[test] pub fn test_deserialize_unicode_basic_message() { let deserialized = serde_json::from_str::<Message>( r#"{ "type": "message", "channel": "C2147483705", "user": "U2147483697", "text": "\uadf8\uc544\uc544", "ts": "1355517523.000005" }"#, ) .unwrap(); if let Message::BasicMessage(msg) = deserialized { assert_eq!(&msg.common.text, "그아아"); } else { panic!("deserialized one must be a BasicMessage!"); } } #[test] pub fn test_serde_enum() { assert_eq!( serde_json::from_str::<TextObjectType>("\"plain_text\"").unwrap(), TextObjectType::PlainText ); assert_eq!( serde_json::from_str::<TextObjectType>("\"mrkdwn\"").unwrap(), TextObjectType::Markdown ); assert_eq!( serde_json::to_string(&TextObjectType::PlainText).unwrap(), "\"plain_text\"" ); assert_eq!( serde_json::to_string(&TextObjectType::Markdown).unwrap(), "\"mrkdwn\"" ); } #[test] pub fn test_deserialize_bot_message() { serde_json::from_str::<Message>( r#"{ "type": "message", "subtype": "bot_message", "ts": "1358877455.000010", "text": "Pushing is the answer", "bot_id": "BB12033", "username": "github", "icons": {} }"#, ) .unwrap(); } #[test] pub fn test_deserialize_normal_message() { serde_json::from_str::<Message>( r#"{ "type": "message", "ts": "1358877455.000010", "channel": "aaaa", "text": "Pushing is the answer", "user": "github" }"#, ) .unwrap(); }
true
fb23d61ea78e4a7762269aa89ec333350b4ab48c
Rust
xrelkd/caracal
/tests/common/mod.rs
UTF-8
3,763
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
use std::time::{Duration, Instant}; use caracal::{ ClipboardLoad, ClipboardLoadExt, ClipboardStore, ClipboardStoreExt, ClipboardSubscribe, ClipboardWait, Error, }; pub trait ClipboardTester { type Clipboard: 'static + Clone + Sync + Send + ClipboardSubscribe + ClipboardLoad + ClipboardStore; fn new_clipboard(&self) -> Self::Clipboard; fn run(&self) -> Result<(), Error> { self.test_clean()?; for i in 0..20 { let data_size = 1 << i; println!("test with data size: {}", data_size); self.test_store_and_load(data_size)?; println!("passed, test with data size: {}", data_size); } self.test_subscribe()?; Ok(()) } fn test_store_and_load(&self, len: usize) -> Result<(), Error> { let clipboard = self.new_clipboard(); let mime = mime::TEXT_PLAIN_UTF_8; let original_data = vec!['A' as u8; len]; clipboard.store(mime.clone(), &original_data)?; for _ in 0..5 { let loaded_data = clipboard.load(&mime)?; assert_eq!(loaded_data.len(), original_data.len()); assert_eq!(loaded_data, original_data); } Ok(()) } fn test_clean(&self) -> Result<(), Error> { let data = "This is a string"; let clipboard = self.new_clipboard(); clipboard.store(mime::TEXT_PLAIN_UTF_8, data.as_bytes())?; assert!(!clipboard.load(&mime::TEXT_PLAIN_UTF_8)?.is_empty()); clipboard.clear()?; assert!(clipboard.is_empty()); Ok(()) } fn test_subscribe(&self) -> Result<(), Error> { let clipboard = self.new_clipboard(); clipboard.clear()?; let observer = std::thread::spawn({ let subscriber = clipboard.subscribe()?; let clipboard = clipboard.clone(); move || -> Result<String, Error> { loop { let _ = subscriber.wait(); match clipboard.load_string() { Ok(data) => return Ok(data), Err(Error::Empty) => continue, Err(Error::MatchMime { .. }) => continue, Err(err) => return Err(err), } } } }); let observer2 = std::thread::spawn({ let subscriber = clipboard.subscribe()?; let clipboard = clipboard.clone(); move || -> Result<String, Error> { loop { let _ = subscriber.wait(); match clipboard.load_string() { Ok(data) => return Ok(data), Err(Error::Empty) => continue, Err(Error::MatchMime { .. }) => continue, Err(err) => return Err(err), } } } }); let observer3 = std::thread::spawn({ let subscriber = clipboard.subscribe()?; move || -> Result<(), Error> { while let Ok(_) = subscriber.wait() {} Ok(()) } }); std::thread::sleep(Duration::from_millis(100)); let input = format!("{:?}", Instant::now()); clipboard.store_string(&input)?; let output = observer.join().unwrap()?; assert_eq!(input.len(), output.len()); assert_eq!(input, output); let output2 = observer2.join().unwrap()?; assert_eq!(input.len(), output2.len()); assert_eq!(input, output2); println!("drop clipboard"); drop(clipboard); observer3.join().unwrap()?; Ok(()) } }
true
9f5805ff0f94d028a8c67a58d49a7c6fd702ed33
Rust
arcnmx/memento
/src/arm/eabi.rs
UTF-8
2,964
2.578125
3
[]
no_license
use core::ptr; #[no_mangle] #[inline] pub unsafe extern fn __aeabi_memset(dst: *mut u8, len: usize, v: u32) { let v = v as u8; for off in 0..len { ptr::write(dst.offset(off as isize), v); } } #[no_mangle] #[inline] pub unsafe extern fn __aeabi_memset4(dst: *mut u32, len: usize, v: u32) { let v = v & 0xff; let v = (v << 24) | (v << 16) | (v << 8) | v; for off in 0..len / 4 { ptr::write(dst.offset(off as isize), v); } } #[no_mangle] #[inline] pub unsafe extern fn __aeabi_memset8(dst: *mut u64, len: usize, v: u32) { __aeabi_memset4(dst as *mut _, len, v); } #[no_mangle] #[inline] pub unsafe extern fn __aeabi_memclr(dst: *mut u8, len: usize) { __aeabi_memset(dst, len, 0); } #[no_mangle] #[inline] pub unsafe extern fn __aeabi_memclr4(dst: *mut u32, len: usize) { __aeabi_memset4(dst, len, 0); } #[no_mangle] #[inline] pub unsafe extern fn __aeabi_memclr8(dst: *mut u64, len: usize) { __aeabi_memset8(dst, len, 0); } #[no_mangle] #[inline] pub unsafe extern fn __aeabi_memcpy(dst: *mut u8, src: *const u8, len: usize) { for off in 0..len { ptr::write(dst.offset(off as isize), *src.offset(off as isize)); } } #[no_mangle] #[inline] pub unsafe extern fn __aeabi_memcpy4(dst: *mut u32, src: *const u32, len: usize) { for off in 0..len / 4 { ptr::write(dst.offset(off as isize), *src.offset(off as isize)); } } #[no_mangle] #[inline] pub unsafe extern fn __aeabi_memcpy8(dst: *mut u64, src: *const u64, len: usize) { for off in 0..len / 8 { ptr::write(dst.offset(off as isize), *src.offset(off as isize)); } } unsafe fn __aeabi_uidivmod() { asm!(" .thumb_func .global __aeabi_uidiv __aeabi_uidiv: .thumb_func .global __aeabi_uidivmod __aeabi_uidivmod: cmp r1, #0 bne L_no_div0 bl __aeabi_idiv0 L_no_div0: @ Shift left the denominator until it is greater than the numerator movs r2, #1 @ counter movs r3, #0 @ result cmp r0, r1 bls L_sub_loop0 adds r1, #0 @ dont shift if denominator would overflow bmi L_sub_loop0 L_denom_shift_loop: lsls r2, #1 lsls r1, #1 bmi L_sub_loop0 cmp r0, r1 bhi L_denom_shift_loop L_sub_loop0: cmp r0, r1 bcc L_dont_sub0 @ if (num>denom) subs r0, r0, r1 @ numerator -= denom orrs r3, r2 @ result(r3) |= bitmask(r2) L_dont_sub0: lsrs r1, #1 @ denom(r1) >>= 1 lsrs r2, #1 @ bitmask(r2) >>= 1 bne L_sub_loop0 mov r1, r0 @ remainder(r1) = numerator(r0) mov r0, r3 @ quotient(r0) = result(r3) bx lr .thumb_func .global __aeabi_idiv __aeabi_idiv: cmp r0, #0 bge L_num_pos rsbs r0, r0, #0 @ num = -num cmp r1, #0 bge L_neg_result rsbs r1, r1, #0 @ den = -den bl __aeabi_uidivmod L_num_pos: cmp r1, #0 blt L_no_div bl __aeabi_uidivmod L_no_div: rsbs r1, r1, #0 @ den = -den L_neg_result: push {lr} bl __aeabi_uidivmod rsbs r0, r0, #0 @ quot = -quot pop {pc} .thumb_func .global __aeabi_idiv0 __aeabi_idiv0: .thumb_func .global __aeabi_ldiv0 __aeabi_ldiv0: bx lr "::::"volatile"); }
true
1ad82f182590dbfdd7c82df2577fd974c95bb795
Rust
brady131313/rustta
/rustta_bindgen/src/meta/group_table.rs
UTF-8
1,271
3.046875
3
[ "MIT" ]
permissive
use std::ffi::CStr; use crate::ffi::*; use crate::types::TaResult; pub struct GroupTable(*mut TA_StringTable); impl GroupTable { pub fn new() -> TaResult<Self> { let mut table = std::ptr::null_mut(); let ret_code = unsafe { TA_GroupTableAlloc(&mut table) }; if ret_code != TA_RetCode::TA_SUCCESS { return Err(ret_code.into()); } Ok(Self(table)) } pub fn iter(&self) -> impl Iterator<Item = &CStr> { unsafe { std::slice::from_raw_parts((*self.0).string, (*self.0).size as usize) .iter() .map(|ptr| CStr::from_ptr(*ptr)) } } } impl Drop for GroupTable { fn drop(&mut self) { unsafe { TA_GroupTableFree(self.0) }; } } #[cfg(test)] mod tests { use std::{error::Error, ffi::CString}; use super::*; #[test] fn test_group_iter() -> Result<(), Box<dyn Error>> { let group_table = GroupTable::new()?; let mut iter = group_table.iter(); let expected: &CStr = &CString::new("Math Operators")?; assert_eq!(expected, iter.next().unwrap()); let expected: &CStr = &CString::new("Math Transform")?; assert_eq!(expected, iter.next().unwrap()); Ok(()) } }
true
55b20d16931c843fa61a3f9b868085ace4ea4790
Rust
youngbloood/actix3
/common/src/msg.rs
UTF-8
1,543
3.140625
3
[ "MIT" ]
permissive
// 请求msg和响应msg use serde::{Deserialize,Serialize}; use actix_web::HttpResponse; use actix_web::error; use failure::Fail; #[derive(Fail, Debug)] pub enum BusinessError { #[fail(display = "Validation error on field: {}", field)] ValidationError { field: String }, #[fail(display = "An internal error occurred. Please try again later.")] InternalError, } impl error::ResponseError for BusinessError { fn error_response(&self) -> HttpResponse { match *self { BusinessError::ValidationError { .. } => { let resp = Resp::err(10001, &self.to_string()); HttpResponse::BadRequest().json(resp) } _ => { let resp = Resp::err(10000, &self.to_string()); HttpResponse::InternalServerError().json(resp) } } } // 重写response的序列化结果 // fn render_response(&self) -> HttpResponse { // self.error_response() // } } #[derive(Deserialize, Serialize)] pub struct Resp<T> where T: Serialize { code: i32, message: String, data: Option<T>, } impl<T: Serialize> Resp<T> { pub fn ok(data: T) -> Self { Resp { code: 0, message: "ok".to_owned(), data: Some(data) } } pub fn to_json_result(&self) -> Result<HttpResponse, BusinessError> { Ok(HttpResponse::Ok().json(self)) } } impl Resp<()> { pub fn err(error: i32, message: &str) -> Self { Resp { code: error, message: message.to_owned(), data: None } } }
true
ef20c5159ed95d2e091c1e003b3ccb6c9721305f
Rust
Weasy666/egui
/crates/ecolor/src/hsva_gamma.rs
UTF-8
1,447
3.15625
3
[ "Apache-2.0", "MIT" ]
permissive
use crate::{gamma_from_linear, linear_from_gamma, Color32, Hsva, Rgba}; /// Like Hsva but with the `v` value (brightness) being gamma corrected /// so that it is somewhat perceptually even. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct HsvaGamma { /// hue 0-1 pub h: f32, /// saturation 0-1 pub s: f32, /// value 0-1, in gamma-space (~perceptually even) pub v: f32, /// alpha 0-1. A negative value signifies an additive color (and alpha is ignored). pub a: f32, } impl From<HsvaGamma> for Rgba { fn from(hsvag: HsvaGamma) -> Rgba { Hsva::from(hsvag).into() } } impl From<HsvaGamma> for Color32 { fn from(hsvag: HsvaGamma) -> Color32 { Rgba::from(hsvag).into() } } impl From<HsvaGamma> for Hsva { fn from(hsvag: HsvaGamma) -> Hsva { let HsvaGamma { h, s, v, a } = hsvag; Hsva { h, s, v: linear_from_gamma(v), a, } } } impl From<Rgba> for HsvaGamma { fn from(rgba: Rgba) -> HsvaGamma { Hsva::from(rgba).into() } } impl From<Color32> for HsvaGamma { fn from(srgba: Color32) -> HsvaGamma { Hsva::from(srgba).into() } } impl From<Hsva> for HsvaGamma { fn from(hsva: Hsva) -> HsvaGamma { let Hsva { h, s, v, a } = hsva; HsvaGamma { h, s, v: gamma_from_linear(v), a, } } }
true
85103cdde29bf769a6110c41870de48cf72ad4b9
Rust
wannabit-jayb/kms
/src/types/vote.rs
UTF-8
8,581
2.78125
3
[ "Apache-2.0" ]
permissive
use super::{BlockID, TendermintSign, Time}; use chrono::{DateTime, Utc}; use std::time::{SystemTime, UNIX_EPOCH}; use subtle_encoding::hex::encode_upper; // TODO(ismail): we might not want to use this error type here // see below: those aren't prost errors use prost::error::DecodeError; enum VoteType { PreVote, PreCommit, } fn vote_type_to_char(vt: &VoteType) -> char { match *vt { VoteType::PreVote => 0x01 as char, VoteType::PreCommit => 0x02 as char, } } fn u32_to_vote_type(data: u32) -> Result<VoteType, DecodeError> { match data { 1 => Ok(VoteType::PreVote), 2 => Ok(VoteType::PreCommit), _ => Err(DecodeError::new("Invalid vote type")), } } #[derive(Clone, PartialEq, Message)] pub struct Vote { #[prost(bytes, tag = "1")] validator_address: Vec<u8>, #[prost(sint64)] validator_index: i64, #[prost(sint64)] height: i64, #[prost(sint64)] round: i64, #[prost(message)] timestamp: Option<Time>, #[prost(uint32)] vote_type: u32, #[prost(message)] block_id: Option<BlockID>, #[prost(message)] signature: Option<Vec<u8>>, } pub const AMINO_NAME: &str = "tendermint/socketpv/SignVoteMsg"; #[derive(Clone, PartialEq, Message)] #[amino_name = "tendermint/socketpv/SignVoteMsg"] pub struct SignVoteMsg { #[prost(message, tag = "1")] vote: Option<Vote>, } impl TendermintSign for SignVoteMsg { fn cannonicalize(self, chain_id: &str) -> String { match self.vote { Some(vote) => { let empty: Vec<u8> = b"".to_vec(); let value = json!({ "@chain_id":chain_id, "@type":"vote", "block_id":{ "hash":encode_upper(match &vote.block_id { Some(ref block_id) => &block_id.hash, None => &empty, }), "parts":{ "hash":encode_upper(match &vote.block_id { Some(block_id) => match &block_id.parts_header { Some(ref parts_header) => &parts_header.hash, None => &empty, }, None => &empty, }), "total":match vote.block_id { Some(block_id) => match block_id.parts_header { Some(parts_header) => parts_header.total, None => 0, }, None => 0, } } }, "height":vote.height, "round":vote.round, "timestamp": match vote.timestamp { Some(timestamp) => { let ts: DateTime<Utc> = DateTime::from(SystemTime::from(timestamp)); ts.to_rfc3339() }, None => { let ts: DateTime<Utc> = DateTime::from(UNIX_EPOCH); ts.to_rfc3339() } }, "type": match u32_to_vote_type(vote.vote_type) { Ok(ref vt) => vote_type_to_char(vt), Err(_e) => 0 as char, } }); value.to_string() } None => "".to_owned(), } } fn sign(&mut self) { unimplemented!() } } #[cfg(test)] mod tests { use super::super::PartsSetHeader; use super::*; use prost::Message; #[test] fn test_vote_serialization() { let dt = "2017-12-25T03:00:01.234Z".parse::<DateTime<Utc>>().unwrap(); let t = Time { seconds: dt.timestamp(), nanos: dt.timestamp_subsec_nanos() as i32, }; let vote = Vote { validator_address: vec![ 0xa3, 0xb2, 0xcc, 0xdd, 0x71, 0x86, 0xf1, 0x68, 0x5f, 0x21, 0xf2, 0x48, 0x2a, 0xf4, 0xfb, 0x34, 0x46, 0xa8, 0x4b, 0x35, ], validator_index: 56789, height: 12345, round: 2, timestamp: Some(t), vote_type: 0x01, block_id: Some(BlockID { hash: "hash".as_bytes().to_vec(), parts_header: Some(PartsSetHeader { total: 1000000, hash: "parts_hash".as_bytes().to_vec(), }), }), signature: None, }; let sign_vote_msg = SignVoteMsg { vote: Some(vote) }; let mut got = vec![]; let _have = sign_vote_msg.encode(&mut got); // the following vector is generated via: // cdc := amino.NewCodec() // cdc.RegisterInterface((*privval.SocketPVMsg)(nil), nil) // cdc.RegisterInterface((*crypto.Signature)(nil), nil) // cdc.RegisterConcrete(crypto.SignatureEd25519{}, // "tendermint/SignatureEd25519", nil) // // cdc.RegisterConcrete(&privval.PubKeyMsg{}, "tendermint/socketpv/PubKeyMsg", nil) // cdc.RegisterConcrete(&privval.SignVoteMsg{}, "tendermint/socketpv/SignVoteMsg", nil) // cdc.RegisterConcrete(&privval.SignProposalMsg{}, "tendermint/socketpv/SignProposalMsg", nil) // cdc.RegisterConcrete(&privval.SignHeartbeatMsg{}, "tendermint/socketpv/SignHeartbeatMsg", nil) // data, _ := cdc.MarshalBinary(privval.SignVoteMsg{Vote: vote}) // // where vote is equal to // // types.Vote{ // ValidatorAddress: []byte{0xa3, 0xb2, 0xcc, 0xdd, 0x71, 0x86, 0xf1, 0x68, 0x5f, 0x21, 0xf2, 0x48, 0x2a, 0xf4, 0xfb, 0x34, 0x46, 0xa8, 0x4b, 0x35}, // ValidatorIndex: 56789, // Height: 12345, // Round: 2, // Timestamp: stamp, // Type: byte(0x01), // pre-vote // BlockID: types.BlockID{ // Hash: []byte("hash"), // PartsHeader: types.PartSetHeader{ // Total: 1000000, // Hash: []byte("parts_hash"), // }, // }, // } let want = vec![ 0x52, 0x6c, 0x1d, 0x3a, 0x35, 0xa, 0x4c, 0xa, 0x14, 0xa3, 0xb2, 0xcc, 0xdd, 0x71, 0x86, 0xf1, 0x68, 0x5f, 0x21, 0xf2, 0x48, 0x2a, 0xf4, 0xfb, 0x34, 0x46, 0xa8, 0x4b, 0x35, 0x10, 0xaa, 0xf7, 0x6, 0x18, 0xf2, 0xc0, 0x1, 0x20, 0x4, 0x2a, 0xe, 0x9, 0xb1, 0x69, 0x40, 0x5a, 0x0, 0x0, 0x0, 0x0, 0x15, 0x80, 0x8e, 0xf2, 0xd, 0x30, 0x1, 0x3a, 0x18, 0xa, 0x4, 0x68, 0x61, 0x73, 0x68, 0x12, 0x10, 0x8, 0x80, 0x89, 0x7a, 0x12, 0xa, 0x70, 0x61, 0x72, 0x74, 0x73, 0x5f, 0x68, 0x61, 0x73, 0x68, ]; assert_eq!(got, want); } #[test] fn test_deserialization() { let encoded = vec![ 0x52, 0x6c, 0x1d, 0x3a, 0x35, 0xa, 0x4c, 0xa, 0x14, 0xa3, 0xb2, 0xcc, 0xdd, 0x71, 0x86, 0xf1, 0x68, 0x5f, 0x21, 0xf2, 0x48, 0x2a, 0xf4, 0xfb, 0x34, 0x46, 0xa8, 0x4b, 0x35, 0x10, 0xaa, 0xf7, 0x6, 0x18, 0xf2, 0xc0, 0x1, 0x20, 0x4, 0x2a, 0xe, 0x9, 0xb1, 0x69, 0x40, 0x5a, 0x0, 0x0, 0x0, 0x0, 0x15, 0x80, 0x8e, 0xf2, 0xd, 0x30, 0x1, 0x3a, 0x18, 0xa, 0x4, 0x68, 0x61, 0x73, 0x68, 0x12, 0x10, 0x8, 0x80, 0x89, 0x7a, 0x12, 0xa, 0x70, 0x61, 0x72, 0x74, 0x73, 0x5f, 0x68, 0x61, 0x73, 0x68, ]; let dt = "2017-12-25T03:00:01.234Z".parse::<DateTime<Utc>>().unwrap(); let t = Time { seconds: dt.timestamp(), nanos: dt.timestamp_subsec_nanos() as i32, }; let vote = Vote { validator_address: vec![ 0xa3, 0xb2, 0xcc, 0xdd, 0x71, 0x86, 0xf1, 0x68, 0x5f, 0x21, 0xf2, 0x48, 0x2a, 0xf4, 0xfb, 0x34, 0x46, 0xa8, 0x4b, 0x35, ], validator_index: 56789, height: 12345, round: 2, timestamp: Some(t), vote_type: 0x01, block_id: Some(BlockID { hash: "hash".as_bytes().to_vec(), parts_header: Some(PartsSetHeader { total: 1000000, hash: "parts_hash".as_bytes().to_vec(), }), }), signature: None, }; let want = SignVoteMsg { vote: Some(vote) }; match SignVoteMsg::decode(&encoded) { Ok(have) => { assert_eq!(have, want); println!("{}", have.cannonicalize("chain_iddddd")); } Err(err) => assert!(false, err.to_string()), } } }
true
139d6ce2d0f01621ff69bacff1754ce1170a9b60
Rust
fotcorn/x86emu
/src/instruction_set.rs
UTF-8
13,009
3.390625
3
[ "MIT" ]
permissive
use std::fmt; #[derive(Clone, Copy, Debug)] pub enum RegisterSize { Bit8, Bit16, Bit32, Bit64, Segment, } #[derive(Debug, Copy, Clone)] pub enum Register { // 64 Bit RAX, RBX, RCX, RDX, RSP, RBP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15, RIP, CR0, CR2, CR3, CR4, CR8, // 32 Bit EAX, EBX, ECX, EDX, ESP, EBP, ESI, EDI, R8D, R9D, R10D, R11D, R12D, R13D, R14D, R15D, // 32 Bit AX, CX, DX, BX, SP, BP, SI, DI, R8W, R9W, R10W, R11W, R12W, R13W, R14W, R15W, // 16 Bit AL, CL, DL, BL, AH, CH, DH, BH, SPL, BPL, SIL, DIL, R8B, R9B, R10B, R11B, R12B, R13B, R14B, R15B, ES, CS, SS, DS, FS, GS, } pub enum Flags { Carry = 1 << 0, Parity = 1 << 2, Zero = 1 << 6, Sign = 1 << 7, Direction = 1 << 10, Overflow = 1 << 11, } #[derive(Debug, Copy, Clone)] pub enum ArgumentSize { Bit64, Bit32, Bit16, Bit8, } pub fn get_register_size(reg: &Register) -> ArgumentSize { match *reg { Register::RAX | Register::RBX | Register::RCX | Register::RDX | Register::RSP | Register::RBP | Register::RSI | Register::RDI | Register::RIP | Register::R8 | Register::R9 | Register::R10 | Register::R11 | Register::R12 | Register::R13 | Register::R14 | Register::R15 | Register::CR0 | Register::CR2 | Register::CR3 | Register::CR4 | Register::CR8 => ArgumentSize::Bit64, Register::EAX | Register::EBX | Register::ECX | Register::EDX | Register::ESP | Register::EBP | Register::ESI | Register::EDI | Register::R8D | Register::R9D | Register::R10D | Register::R11D | Register::R12D | Register::R13D | Register::R14D | Register::R15D => ArgumentSize::Bit32, Register::AX | Register::CX | Register::DX | Register::BX | Register::SP | Register::BP | Register::SI | Register::DI | Register::R8W | Register::R9W | Register::R10W | Register::R11W | Register::R12W | Register::R13W | Register::R14W | Register::R15W | Register::ES | Register::CS | Register::SS | Register::DS | Register::FS | Register::GS => ArgumentSize::Bit16, Register::AL | Register::CL | Register::DL | Register::BL | Register::AH | Register::CH | Register::DH | Register::BH | Register::SPL | Register::BPL | Register::SIL | Register::DIL | Register::R8B | Register::R9B | Register::R10B | Register::R11B | Register::R12B | Register::R13B | Register::R14B | Register::R15B => ArgumentSize::Bit8, } } impl fmt::Display for Register { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let rep = format!("{:?}", self).to_lowercase(); write!(f, "%{}", rep) } } #[derive(Debug)] pub enum InstructionArgument { Immediate { immediate: i64 }, Register { register: Register }, EffectiveAddress { base: Option<Register>, index: Option<Register>, scale: Option<u8>, displacement: i32, }, } impl InstructionArgument { pub fn format(&self, size: ArgumentSize) -> String { match *self { InstructionArgument::Register {..} | InstructionArgument::EffectiveAddress {..} => format!("{}", self), InstructionArgument::Immediate { immediate } => { format!("$0x{:x}", match size { ArgumentSize::Bit8 => immediate as u8 as u64, ArgumentSize::Bit16 => immediate as u16 as u64, ArgumentSize::Bit32 => immediate as u32 as u64, ArgumentSize::Bit64 => immediate as u64, }) } } } } #[derive(Debug)] pub struct InstructionArguments { pub first_argument: Option<InstructionArgument>, pub second_argument: Option<InstructionArgument>, pub third_argument: Option<InstructionArgument>, pub opcode: Option<u8>, pub explicit_size: Option<ArgumentSize>, pub repeat_equal: bool, pub repeat_not_equal: bool, } impl InstructionArguments { pub fn get_one_argument(&self) -> &InstructionArgument { let first_argument = match self.first_argument { Some(ref first_argument) => first_argument, None => panic!("Instructions needs one argument"), }; match self.second_argument { Some(_) => panic!("Instruction accepts only one argument"), None => (), }; first_argument } pub fn get_two_arguments(&self) -> (&InstructionArgument, &InstructionArgument) { let first_argument = match self.first_argument { Some(ref first_argument) => first_argument, None => panic!("Instruction needs first_argument"), }; let second_argument = match self.second_argument { Some(ref first_argument) => first_argument, None => panic!("Instruction needs second_argument"), }; (first_argument, second_argument) } pub fn size(&self) -> ArgumentSize { match self.explicit_size { Some(explicit_size) => explicit_size, None => { match self.second_argument { Some(ref second_argument) => { match self.first_argument { Some(ref first_argument) => { match *first_argument { InstructionArgument::Register { ref register } => { get_register_size(register) } InstructionArgument::Immediate { .. } | InstructionArgument::EffectiveAddress { .. } => { match *second_argument { InstructionArgument::Register { ref register } => { get_register_size(register) } _ => panic!("Cannot determine instruction argument size"), } } } }, None => panic!("Instructions with second_argument also need a first_argument"), } }, None => { match self.first_argument { Some(ref first_argument) => { match *first_argument { InstructionArgument::Register { ref register } => { get_register_size(register) } InstructionArgument::Immediate { .. } => ArgumentSize::Bit64, InstructionArgument::EffectiveAddress { .. } => ArgumentSize::Bit64, } }, None => panic!("Instructions without arguments needs explicit_size set"), } } } } } } } pub struct InstructionArgumentsBuilder { first_argument: Option<InstructionArgument>, second_argument: Option<InstructionArgument>, opcode: Option<u8>, explicit_size: Option<ArgumentSize>, repeat_equal: bool, repeat_not_equal: bool, } impl InstructionArgumentsBuilder { pub fn new() -> InstructionArgumentsBuilder { InstructionArgumentsBuilder { first_argument: None, second_argument: None, opcode: None, explicit_size: None, repeat_equal: false, repeat_not_equal: false, } } pub fn first_argument(mut self, first_argument: InstructionArgument) -> InstructionArgumentsBuilder { self.first_argument = Some(first_argument); self } pub fn second_argument(mut self, second_argument: InstructionArgument) -> InstructionArgumentsBuilder { self.second_argument = Some(second_argument); self } pub fn opcode(mut self, opcode: u8) -> InstructionArgumentsBuilder { self.opcode = Some(opcode); self } pub fn explicit_size(mut self, explicit_size: ArgumentSize) -> InstructionArgumentsBuilder { self.explicit_size = Some(explicit_size); self } pub fn finalize(self) -> InstructionArguments { InstructionArguments { first_argument: self.first_argument, second_argument: self.second_argument, third_argument: None, opcode: self.opcode, explicit_size: self.explicit_size, repeat_equal: self.repeat_equal, repeat_not_equal: self.repeat_not_equal, } } pub fn repeat(mut self, repeat_equal: bool, repeat_not_equal: bool) -> InstructionArgumentsBuilder { self.repeat_equal = repeat_equal; self.repeat_not_equal = repeat_not_equal; self } } impl fmt::Display for InstructionArguments { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.second_argument { Some(ref second_argument) => { match self.first_argument { Some(ref first_argument) => write!(f, "{},{}", first_argument.format(self.size()), second_argument.format(self.size())), None => panic!("Instructions with second_argument also need a first_argument"), } }, None => { match self.first_argument { Some(ref first_argument) => write!(f, "{}", first_argument.format(self.size())), None => write!(f, ""), } }, } } } impl fmt::Display for InstructionArgument { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InstructionArgument::Register { ref register } => write!(f, "{}", register), InstructionArgument::Immediate { immediate } => write!(f, "$0x{:x}", immediate), InstructionArgument::EffectiveAddress { displacement, .. } => { if displacement < 0 { write!(f, "-{:#x}{}", displacement.abs(), format_effective_address(self)) } else if displacement > 0 { write!(f, "{:#x}{}", displacement, format_effective_address(self)) } else { write!(f, "0x0{}", format_effective_address(self)) } } } } } fn format_effective_address(arg: &InstructionArgument) -> String { match *arg { InstructionArgument::EffectiveAddress { ref base, ref index, scale, .. } => { match *index { None => { match *base { Some(ref base) => format!("({})", base), None => format!(""), } } Some(ref index) => { match *base { Some(ref base) => format!("({},{},{})", base, index, scale.unwrap()), None => format!("(,{},{})", index, scale.unwrap()), } } } }, _ => unreachable!() } } pub struct InstructionCache { pub instruction: Instruction, pub arguments: Option<InstructionArguments>, pub size: u64 } pub enum Instruction { Adc, Add, And, Arithmetic, BitManipulation, Bt, Bts, Btr, Btc, Call, Cld, Cmova, Cmovae, Cmovb, Cmovbe, Cmove, Cmovg, Cmovge, Cmovl, Cmovle, Cmovne, Cmovno, Cmovnp, Cmovns, Cmovo, Cmovp, Cmovs, Cmp, CompareMulOperation, Cpuid, Imul, Int, Ja, Jae, Jb, Jbe, Je, Jg, Jge, Jl, Jle, Jmp, Jne, Jno, Jnp, Jns, Jo, Jp, Js, Lea, Leave, Lidt, Lgdt, Mov, Movs, Movsx, Movzx, Nop, Or, Out, Pop, Popf, Push, Pushf, Rdmsr, RegisterOperation, Ret, Lret, Sbb, ShiftRotate, Std, Stos, Sub, Test, Wrmsr, Xor, Scas, Cmpxchg, Xchg, Syscall, Seto, Setno, Setb, Setae, Sete, Setne, Setbe, Seta, Sets, Setns, Setp, Setnp, Setl, Setge, Setle, Setg, }
true
b51a2a6c640682ca752dcbbfb527879e97672746
Rust
kpozin/icu4x
/components/pluralrules/tests/rules.rs
UTF-8
2,690
2.8125
3
[ "MIT", "LicenseRef-scancode-unicode", "ICU", "Apache-2.0" ]
permissive
mod fixtures; mod helpers; use icu_pluralrules::rules::{parse, parse_condition, test_condition, Lexer}; use icu_pluralrules::PluralOperands; #[test] fn test_parsing_operands() { let path = "./tests/fixtures/rules.json"; let test_set: fixtures::RuleTestSet = helpers::read_fixture(path).expect("Failed to read a fixture"); for test in test_set.0 { match test.output { fixtures::RuleTestOutput::Value(val) => { let lex = Lexer::new(test.rule.as_bytes()); lex.count(); let ast = parse_condition(test.rule.as_bytes()).expect("Failed to parse."); let operands: PluralOperands = test.input.into(); if val { assert!(test_condition(&ast, &operands)); } else { assert!(!test_condition(&ast, &operands)); } } fixtures::RuleTestOutput::Error(val) => { let err = parse(test.rule.as_bytes()).unwrap_err(); assert_eq!(format!("{:?}", err), val); } } } } #[cfg(feature = "io-json")] #[test] fn test_round_trip() { use icu_pluralrules::data::cldr_resource::Resource; use icu_pluralrules::rules::serialize; use icu_pluralrules::PluralCategory; let path = "./data/plurals.json"; let s = std::fs::read_to_string(path).unwrap(); let res: Resource = serde_json::from_str(&s).unwrap(); for (_, rules) in res.supplemental.plurals_type_cardinal.unwrap().0 { for category in PluralCategory::all() { if let Some(rule) = rules.get(category) { let lexer = Lexer::new(rule.as_bytes()); let _ = lexer.collect::<Vec<_>>(); let ast = parse(rule.as_bytes()).expect("Parsing failed."); let mut output = String::new(); serialize(&ast, &mut output).unwrap(); assert_eq!(rule, output); } } } let path = "./data/ordinals.json"; let s = std::fs::read_to_string(path).unwrap(); let res: Resource = serde_json::from_str(&s).unwrap(); for (_, rules) in res.supplemental.plurals_type_ordinal.unwrap().0 { for category in PluralCategory::all() { if let Some(rule) = rules.get(category) { let lexer = Lexer::new(rule.as_bytes()); let _ = lexer.collect::<Vec<_>>(); let ast = parse(rule.as_bytes()).expect("Parsing failed."); let mut output = String::new(); serialize(&ast, &mut output).unwrap(); assert_eq!(rule, output); } } } }
true
bcb986143363fccb9e43c50f715c586c25256ccb
Rust
mhetrerajat/ds-challenge
/exercism/rust/proverb/src/lib.rs
UTF-8
522
2.75
3
[ "MIT" ]
permissive
pub fn build_proverb(list: &[&str]) -> String { let mut result = String::new(); let length = if list.len() != 0 { list.len() - 1 } else { 0 }; for idx in 0..length { result.push_str( format!( "For want of a {} the {} was lost.\n", list[idx], list[idx + 1] ) .as_str(), ); } if list.len() >= 1 { result.push_str(format!("And all for the want of a {}.", list[0]).as_str()); } result }
true
a08cdafd012cc0d0158bc528463d6e61030aea8b
Rust
jafow/pals
/src/xor.rs
UTF-8
4,768
3.296875
3
[]
no_license
extern crate hex; use table; use std::collections::HashMap; use FreqScore; struct Freq { raw: u8, pct: f32 } /// xor_fixed /// take 2 equal length buffers and return the fixed /// xor of them pub fn xor_fixed(buf1: &[u8], buf2: &[u8]) -> Result<Vec<u8>, hex::FromHexError> { // assert_eq!(buf1.len(), buf2.len()); let b1_decoded = hex::decode(buf1)?; let b2_decoded = hex::decode(buf2)?; let mut res: Vec<u8> = Vec::new(); for (b1, b2) in b1_decoded.iter().zip(b2_decoded.iter()) { res.push(b1 ^ b2); } Ok(res) } #[test] fn test_xor_fixed() { let expected = String::from("746865206b696420646f6e277420706c6179"); let a1: &[u8; 36] = b"1c0111001f010100061a024b53535009181c"; let a2: &[u8; 36] = b"686974207468652062756c6c277320657965"; let actual = xor_fixed(a1, a2); assert_eq!(hex::encode(actual.unwrap()), expected); } #[test] fn test_xor_err() { let s1 = b"123"; let s2 = b"foo"; let actual = xor_fixed(s1, s2); assert_eq!(actual, Err(hex::FromHexError::OddLength)); } /// create a slice of length slice_len of bytes fn cycle_bytes(slice_len: u8, bytes: &[u8]) -> Vec<&u8> { (0..slice_len).zip(bytes.iter().cycle()).map(|b| b.1).collect() } #[test] fn test_cycle_bytes() { let expected: [&u8; 5] = [&97, &98, &99, &97, &98]; let actual = cycle_bytes(5, b"abc"); assert_eq!(actual, expected); } fn fill_bytes(slice_len: usize, _char: &u8) -> Vec<u8> { let mut filled: Vec<u8> = Vec::new(); for _i in 0..slice_len { filled.push(*_char); } filled } #[test] fn test_fill_bytes() { let bytes_input = "hello"; let expect0 = vec![b'f', b'f', b'f', b'f', b'f']; let actual0 = fill_bytes(bytes_input.len(), &b'f'); let expect1 = vec![b'a', b'a', b'a', b'a', b'a']; let actual1 = fill_bytes(5, &b'a'); let expect2 = vec![b'z']; let actual2 = fill_bytes(1, &b'z'); assert_eq!(expect0, actual0); assert_eq!(expect1, actual1); assert_eq!(expect2, actual2); } /// takes a hex string and xors against each char A-Za-z /// returning the most likely to be valid English /// /// scoring: /// - create a table T of chars to frequency in English language /// like this: /// https://en.wikipedia.org/wiki/Letter_frequency#Relative_frequencies_of_letters_in_the_English_language /// - reduce the decoded/xor'd bytes B into their own freq table t /// - for idx, b in B: /// sum the difference of each key in t to corresponding key in T /// return the key with the lowest sum (where lowest is the smaller deviation from the ideal) pub fn single_byte(bytes: &str) -> FreqScore { debug_assert_ne!(bytes.is_empty(), true); let _len: usize = bytes.len(); let mut min_score: FreqScore = FreqScore {id: 0, score: 100.0}; for ch in table::LETTERS.iter() { // fill up a buffer with a byte let _key = hex::encode(fill_bytes(_len, ch)); // xor ciphertext against `_key` let cipher = xor_fixed(&_key.into_bytes(), &bytes.as_bytes()).expect("xor fixed"); let cipher_table: HashMap<u8, Freq> = freq_table(&cipher); let score: FreqScore = score_cipher(cipher_table, *ch); if score.score <= min_score.score { min_score = score; } } min_score } #[test] fn test_single_byte() { let actual = single_byte("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"); let expected = 88; assert_eq!(actual.id, expected); } /// creates a frequency table of chars in a bytearray fn freq_table(bytes: &[u8]) -> HashMap<u8, Freq> { let mut table: HashMap<u8, Freq> = HashMap::new(); for &c in bytes.iter() { let mut fq = Freq { raw: 1, pct: 0.0 }; match table.get(&c) { Some(v) => fq.raw += v.raw, None => fq.raw += 0 }; fq.pct = (fq.raw / bytes.len() as u8).into(); table.insert(c, fq); } table } /// score a ciphertext's freq table against the ETAOINSHRDLU freq table fn score_cipher(cipher_table: HashMap<u8, Freq>, key_char: u8) -> FreqScore { let mut freq_score = FreqScore { score: 0.0, id: key_char }; let english_letters = table::char_freq(); for (c, val) in cipher_table.iter() { let mut r = 0.0; match english_letters.get(c) { // Take the difference of the letter's freq/length of word to the // "ideal" frequency in table::freq_table() Some(dist) => r += (dist - val.pct).abs(), // or add 1 for any keys that aren't in the alphabet; // Higher scores indicate lower liklihood of english plaintext. None => r += 1.0 }; freq_score.score += r; } freq_score }
true
927f51de741103d2ab6c5c893263321dbe70d5d3
Rust
nikomatsakis/rust
/src/libstd/smallintmap.rs
UTF-8
3,288
3.078125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "bzip2-1.0.6", "BSD-1-Clause" ]
permissive
/* Module: smallintmap A simple map based on a vector for small integer keys. Space requirements are O(highest integer key). */ import core::option; import core::option::{some, none}; // FIXME: Should not be @; there's a bug somewhere in rustc that requires this // to be. /* Type: smallintmap */ type smallintmap<T> = @{mutable v: [mutable option::t<T>]}; /* Function: mk Create a smallintmap */ fn mk<T>() -> smallintmap<T> { let v: [mutable option::t<T>] = [mutable]; ret @{mutable v: v}; } /* Function: insert Add a value to the map. If the map already contains a value for the specified key then the original value is replaced. */ fn insert<T: copy>(m: smallintmap<T>, key: uint, val: T) { vec::grow_set::<option::t<T>>(m.v, key, none::<T>, some::<T>(val)); } /* Function: find Get the value for the specified key. If the key does not exist in the map then returns none. */ fn find<T: copy>(m: smallintmap<T>, key: uint) -> option::t<T> { if key < vec::len::<option::t<T>>(m.v) { ret m.v[key]; } ret none::<T>; } /* Method: get Get the value for the specified key Failure: If the key does not exist in the map */ fn get<T: copy>(m: smallintmap<T>, key: uint) -> T { alt find(m, key) { none. { #error("smallintmap::get(): key not present"); fail; } some(v) { ret v; } } } /* Method: contains_key Returns true if the map contains a value for the specified key */ fn contains_key<T: copy>(m: smallintmap<T>, key: uint) -> bool { ret !option::is_none(find::<T>(m, key)); } // FIXME: Are these really useful? fn truncate<T: copy>(m: smallintmap<T>, len: uint) { m.v = vec::slice_mut::<option::t<T>>(m.v, 0u, len); } fn max_key<T>(m: smallintmap<T>) -> uint { ret vec::len::<option::t<T>>(m.v); } /* Impl: map Implements the map::map interface for smallintmap */ impl <V: copy> of map::map<uint, V> for smallintmap<V> { fn size() -> uint { let sz = 0u; for item in self.v { alt item { some(_) { sz += 1u; } _ {} } } sz } fn insert(&&key: uint, value: V) -> bool { let exists = contains_key(self, key); insert(self, key, value); ret !exists; } fn remove(&&key: uint) -> option::t<V> { if key >= vec::len(self.v) { ret none; } let old = self.v[key]; self.v[key] = none; old } fn contains_key(&&key: uint) -> bool { contains_key(self, key) } fn get(&&key: uint) -> V { get(self, key) } fn find(&&key: uint) -> option::t<V> { find(self, key) } fn rehash() { fail } fn items(it: block(&&uint, V)) { let idx = 0u; for item in self.v { alt item { some(elt) { it(idx, elt); } none. { } } idx += 1u; } } fn keys(it: block(&&uint)) { let idx = 0u; for item in self.v { if item != none { it(idx); } idx += 1u; } } fn values(it: block(V)) { for item in self.v { alt item { some(elt) { it(elt); } _ {} } } } } /* Funtion: as_map Cast the given smallintmap to a map::map */ fn as_map<V>(s: smallintmap<V>) -> map::map<uint, V> { s as map::map::<uint, V> }
true
07658967a551590c5fe42efaff36344f1762e8ce
Rust
jatinchowdhury18/distortion-rs
/distortionlib/src/waveshape.rs
UTF-8
1,398
3.078125
3
[]
no_license
use super::utils; pub struct WaveShape { amount: f32, skew: f32, } impl WaveShape { const MIN_EXP: f32 = 0.4; const MAX_EXP: f32 = 5.0; pub fn new() -> Self { WaveShape { amount: 2.5, skew: utils::get_skew_for_centre(WaveShape::MIN_EXP, WaveShape::MAX_EXP, 2.5), } } pub fn set_drive(&mut self, drive: f32) { self.amount = utils::jmap01((1.0 - drive).powf(self.skew), WaveShape::MIN_EXP, WaveShape::MAX_EXP); } // saturating waveshaper, adapted from D. Yeh thesis // (https://ccrma.stanford.edu/~dtyeh/papers/DavidYehThesissinglesided.pdf), // see "tanh approx" on page 11 #[inline(always)] fn process_sample(x: f32, p: f32) -> f32 { x / (1.0 + x.abs().powf(p)).powf(1.0 / p) } pub fn process_block(&self, block: &mut [f32]) { // @TODO: SIMD accelerate?? for x in block { *x = WaveShape::process_sample(*x, self.amount); } } } #[cfg(test)] mod tests { use super::*; use assert_approx_eq::assert_approx_eq; #[test] fn test_gain_apply() { let mut ws = WaveShape::new(); ws.set_drive(0.5); let mut vec = vec![-500.0, 0.0, 500.0]; ws.process_block(&mut vec); assert_approx_eq!(vec[0], -1.0); assert_approx_eq!(vec[1], 0.0); assert_approx_eq!(vec[2], 1.0); } }
true
c27fc4c8e7ca8746a16fe6e2948e8fc07bc3f93c
Rust
DoYouEvenCpp/aoc2015
/day15/src/main.rs
UTF-8
3,530
3.421875
3
[]
no_license
use std::cmp; #[derive(PartialEq, Eq, Hash, Clone, Debug)] struct Ingredient { capacity: i32, durability: i32, flavor: i32, texture: i32, calories: i32, } type DataType = Vec<Ingredient>; fn get_input() -> DataType { let mut m = DataType::new(); m.push(Ingredient { capacity: 2, durability: 0, flavor: -2, texture: 0, calories: 3, }); m.push(Ingredient { capacity: 0, durability: 5, flavor: -3, texture: 0, calories: 3, }); m.push(Ingredient { capacity: 0, durability: 0, flavor: 5, texture: -1, calories: 8, }); m.push(Ingredient { capacity: 0, durability: -1, flavor: 0, texture: 5, calories: 8, }); m } fn calculate( input: &[Ingredient], first: u32, second: u32, third: u32, fourth: u32, ) -> (i32, i32, i32, i32) { let capacity = cmp::max( 0, first as i32 * input[0].capacity + second as i32 * input[1].capacity + third as i32 * input[2].capacity + fourth as i32 * input[3].capacity, ); let durability = cmp::max( 0, first as i32 * input[0].durability + second as i32 * input[1].durability + third as i32 * input[2].durability + fourth as i32 * input[3].durability, ); let flavor = cmp::max( 0, first as i32 * input[0].flavor + second as i32 * input[1].flavor + third as i32 * input[2].flavor + fourth as i32 * input[3].flavor, ); let texture = cmp::max( 0, first as i32 * input[0].texture + second as i32 * input[1].texture + third as i32 * input[2].texture + fourth as i32 * input[3].texture, ); (capacity, durability, flavor, texture) } fn part_1(input: &[Ingredient], spoons: u32) -> u32 { let mut vals = std::collections::HashSet::<u32>::new(); for first in 0..spoons { for second in 0..spoons - first { for third in 0..spoons - first - second { let fourth = spoons - first - second - third; let v = calculate(input, first, second, third, fourth); let sum = v.0 * v.1 * v.2 * v.3; vals.insert(sum as u32); } } } *vals.iter().max().unwrap() } fn part_2(input: &[Ingredient], spoons: u32) -> u32 { let mut vals = std::collections::HashSet::<u32>::new(); for first in 0..spoons { for second in 0..spoons - first { for third in 0..spoons - first - second { let fourth = spoons - first - second - third; let calories = cmp::max( 0, first as i32 * input[0].calories + second as i32 * input[1].calories + third as i32 * input[2].calories + fourth as i32 * input[3].calories, ); if calories == 500 { let v = calculate(input, first, second, third, fourth); let sum = v.0 * v.1 * v.2 * v.3; vals.insert(sum as u32); } } } } *vals.iter().max().unwrap() } fn main() { let data = get_input(); println!("First puzzle: {}", part_1(&data, 100)); println!("Second puzzle: {}", part_2(&data, 100)); }
true
004768ec9d4670945a03b9ce56d775b608cef19b
Rust
ryanpbrewster/wasm-fzf
/src/main.rs
UTF-8
1,723
2.703125
3
[]
no_license
use fst::IntoStreamer; use fst::{automaton::Subsequence, Streamer}; use std::{ io::{stdin, stdout, Write}, time::Instant, }; use termion::event::{Event, Key}; use termion::input::{MouseTerminal, TermRead}; use termion::{cursor::Goto, raw::IntoRawMode}; const WORDS: &str = include_str!("../data/words_alpha.txt"); const MAX_MATCHES: u16 = 8; fn main() -> Result<(), Box<dyn std::error::Error>> { let set = fst::Set::from_iter(WORDS.lines())?; let stdin = stdin(); let mut stdout = MouseTerminal::from(stdout().into_raw_mode()?); let mut query = String::new(); write!(stdout, "{}", termion::clear::All)?; stdout.flush()?; for evt in stdin.events() { match evt? { Event::Key(key) => { match key { Key::Esc => break, Key::Char(ch) => { query.push(ch); } Key::Backspace => { query.pop(); } _ => {} }; } _ => {} } write!(stdout, "{}", termion::clear::All)?; let start = Instant::now(); let mut stream = set.search(Subsequence::new(&query)).into_stream(); let mut i = 0; while let Some(key) = stream.next() { write!(stdout, "{}{}", Goto(1, 2 + i), std::str::from_utf8(key)?)?; i += 1; if i > MAX_MATCHES { break; } } let elapsed = start.elapsed(); write!(stdout, "{}{}us", Goto(1, 3 + i), elapsed.as_micros())?; write!(stdout, "{}{}", Goto(1, 1), query)?; stdout.flush()?; } Ok(()) }
true
ba473d4915b52e0b1e851c7d1e8aaae17aceeb6e
Rust
INDAPlus21/murnion-task-2
/avstand_till_kanten/src/main.rs
UTF-8
1,318
4
4
[]
no_license
use std::io; use std::io::prelude::*; use std::cmp; /// Takes an input file with two numbers R and C, in a format of a single line "r c" /// Then converts it into an output string displaying a rectangle R wide and C long fn main() { // Get the input let input = io::stdin(); let mut s = &input.lock().lines().map(|_line| _line.ok().unwrap()).collect::<Vec<String>>()[0]; let mut values = s.split(" "); // Break down the input into the actual values we want let rows: usize = values.next().unwrap().parse().unwrap(); let columns: usize = values.next().unwrap().parse().unwrap(); // The rows part just prints it and initializes the string. for x in 1..=rows { let mut name: String = String::with_capacity(columns); // The columns part constructs the string using the dist_map function. for y in 1..=columns { name.push(dist_map(cmp::min(cmp::min(x, rows - x + 1), cmp::min(y, columns - y + 1)))); } println!("{}", name); } } /// Map numbers to chars, where any number above 9 is a dot. fn dist_map(x: usize) -> char { match x { 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9', _ => '.', } }
true
fc76a97e2957b54b4f0c4caaab70437ae225f104
Rust
mfred488/ferris-is-you
/ferris-base/tests/hot_melt.rs
UTF-8
1,418
2.90625
3
[ "MIT" ]
permissive
use ferris_base; mod utils; #[test] fn hot_destroys_melt() { let start = vec![ "............", "..🦀🔥......", "Fe==Me......", "Fe==U La==Ho", ]; let inputs = vec![ ferris_base::core::direction::Direction::RIGHT, ferris_base::core::direction::Direction::RIGHT, ]; let end = vec![ "............", "....🔥......", "Fe==Me......", "Fe==U La==Ho", ]; utils::assert_evolution(start, inputs, end); } #[test] fn hot_does_not_destroy_not_melt() { let start = vec![ "............", "..🦀🔥......", "............", "Fe==U La==Ho", ]; let inputs = vec![ ferris_base::core::direction::Direction::RIGHT, ferris_base::core::direction::Direction::RIGHT, ]; let end = vec![ "............", "....🔥🦀....", "............", "Fe==U La==Ho", ]; utils::assert_evolution(start, inputs, end); } #[test] fn both_hot_and_melt() { let start = vec![ "....La....🔥", "....==......", "🦀Me........", "Fe==U La==Ho", ]; let inputs = vec![ferris_base::core::direction::Direction::RIGHT]; let end = vec![ "....La......", "....==......", "..🦀Me......", "Fe==U La==Ho", ]; utils::assert_evolution(start, inputs, end); }
true
cd7efc14caa523ac72047a9382dbd3e9c52e550a
Rust
rust-lang/rust
/tests/ui/traits/new-solver/cycles/coinduction/incompleteness-unstable-result.rs
UTF-8
2,324
2.90625
3
[ "Apache-2.0", "LLVM-exception", "NCSA", "BSD-2-Clause", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
// compile-flags: -Ztrait-solver=next #![feature(rustc_attrs)] // This test is incredibly subtle. At its core the goal is to get a coinductive cycle, // which, depending on its root goal, either holds or errors. We achieve this by getting // incomplete inference via a `ParamEnv` candidate in the `A<T>` impl and required // inference from an `Impl` candidate in the `B<T>` impl. // // To make global cache accesses stronger than the guidance from the where-bounds, we add // another coinductive cycle from `A<T>: Trait<U, V, D>` to `A<T>: Trait<U, D, V>` and only // constrain `D` directly. This means that any candidates which rely on `V` only make // progress in the second iteration, allowing a cache access in the first iteration to take // precedence. // // tl;dr: our caching of coinductive cycles was broken and this is a regression // test for that. #[rustc_coinductive] trait Trait<T: ?Sized, V: ?Sized, D: ?Sized> {} struct A<T: ?Sized>(*const T); struct B<T: ?Sized>(*const T); trait IncompleteGuidance<T: ?Sized, V: ?Sized> {} impl<T: ?Sized, U: ?Sized + 'static> IncompleteGuidance<U, u8> for T {} impl<T: ?Sized, U: ?Sized + 'static> IncompleteGuidance<U, i8> for T {} impl<T: ?Sized, U: ?Sized + 'static> IncompleteGuidance<U, i16> for T {} trait ImplGuidance<T: ?Sized, V: ?Sized> {} impl<T: ?Sized> ImplGuidance<u32, u8> for T {} impl<T: ?Sized> ImplGuidance<i32, i8> for T {} impl<T: ?Sized, U: ?Sized, V: ?Sized, D: ?Sized> Trait<U, V, D> for A<T> where T: IncompleteGuidance<U, V>, A<T>: Trait<U, D, V>, B<T>: Trait<U, V, D>, (): ToU8<D>, { } trait ToU8<T: ?Sized> {} impl ToU8<u8> for () {} impl<T: ?Sized, U: ?Sized, V: ?Sized, D: ?Sized> Trait<U, V, D> for B<T> where T: ImplGuidance<U, V>, A<T>: Trait<U, V, D>, { } fn impls_trait<T: ?Sized + Trait<U, V, D>, U: ?Sized, V: ?Sized, D: ?Sized>() {} fn with_bound<X>() where X: IncompleteGuidance<i32, u8>, X: IncompleteGuidance<u32, i8>, X: IncompleteGuidance<u32, i16>, { impls_trait::<B<X>, _, _, _>(); // entering the cycle from `B` works // entering the cycle from `A` fails, but would work if we were to use the cache // result of `B<X>`. impls_trait::<A<X>, _, _, _>(); //~^ ERROR the trait bound `A<X>: Trait<_, _, _>` is not satisfied } fn main() { with_bound::<u32>(); }
true
6db6f91fe96edc9ff65b5c0de06d5076b5eacf4f
Rust
siddharthparmarr/rustcode
/rustcode/easyrust/othercollections/hashmap2.rs
UTF-8
554
3.296875
3
[]
no_license
use std::collections::HashMap; fn main() { let canadian_cities = vec!["calgary", "vancouver", "gimli"]; let german_cities = vec!["karlsruhe", "bad doberan", "bielefeld"]; let mut city_hashmap = HashMap::new(); for city in canadian_cities { city_hashmap.insert(city, "canada"); } for city in german_cities { city_hashmap.insert(city, "Germany"); } println!("{:?}", city_hashmap["bielefeld"]); println!("{:?}", city_hashmap.get("bielefeld")); println!("{:?}", city_hashmap.get("bielefelddd")); }
true
f79833ec4b633a3dbf4ee98b9015b908c094e58b
Rust
rthinman/sts3x
/src/lib.rs
UTF-8
13,943
2.859375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
//! This is a platform-agnostic Rust driver for the Sensirion STS30, STS31, and STS35 //! high-accuracy, low-power, I2C digital temperature sensors, based on the //! [`embedded-hal`] traits. //! //! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal //! //! TODO: More information here. //! //! The driver borrows liberally from: //! - eldruin's tmp1x2-rs driver for Texas Instruments TMP102 and TMP112, https://github.com/eldruin/tmp1x2-rs, and //! - dbrgn's shtcx-rs driver for Sensirion SHTCx temperature/humidity sensors, https://github.com/dbrgn/shtcx-rs. #![deny(unsafe_code)] #![no_std] // TODO: add deny missing docs, and doc root url mod crc; use core::marker::PhantomData; use embedded_hal::blocking::i2c; // TODO: move to using nb if the crate adds a nonblocking I2C. pub use nb; /// Possible errors in this crate #[derive(Debug)] pub enum Error<E> { /// I²C bus error I2C(E), /// CRC checksum validation failed Crc, } /// Error type for mode changes. /// This allows us to retrieve the unchanged device in case of an error. #[derive(Debug)] pub enum ModeChangeError<E, DEV> { /// I²C bus error while changing modes /// /// `E` is the error that happened. /// `DEV` is the device with the mode unchanged. I2C(E, DEV), } /// Conversion rate for continuous conversion mode. #[derive(Debug, Clone, Copy, PartialEq)] pub enum ConversionRate { /// 0.5 Hz _0_5Hz, /// 1 Hz _1Hz, /// 2 Hz _2Hz, /// 4 Hz _4Hz, /// 10 Hz _10Hz, } /// Repeatability condition for both one-shot and continuous modes. /// From the datasheet: the value is 3 * standard deviation of measurements at constant ambient. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Repeatability { /// High repeatability 0.04°C High, /// Medium repeatability 0.08°C Medium, /// Low repeatability 0.15°C Low, } impl Default for Repeatability { fn default() -> Self { Repeatability::Low } } /// Possible peripheral addresses #[derive(Debug, Clone, Copy, PartialEq)] pub enum PeripheralAddr { /// Default address, with address pin held low PinLow, /// Address with the pin held high PinHigh, } impl Default for PeripheralAddr { fn default() -> Self { PeripheralAddr::PinLow } } impl PeripheralAddr { /// Return the 7-bit I2C address corresponding to the enum. fn as_byte(self) -> u8 { match self { PeripheralAddr::PinLow => 0x4A, PeripheralAddr::PinHigh => 0x4B, } } } /// I²C commands sent to the sensor #[derive(Debug)] enum Command { /// Initiate a single-shot conversion. StartSingleShot {repeatability: Repeatability}, /// Change to periodic mode with the given repeatability and conversion rates. StartPeriodic { repeatability: Repeatability, conversion_rate: ConversionRate, }, /// Fetch data from the sensor when it is in continuous mode. FetchData, /// Break out of continuous mode and return to one-shot mdoe. Break, /// Issue a software reset. SoftReset, /// Turn the heater on for plausibility checking. HeaterOn, /// Turn the heater off. HeaterOff, /// Read the status register. ReadStatus, /// Clear the status register. ClearStatus, } impl Command { /// Return a slice of two bytes corresponding to the command. /// These are the bytes the sensor expects. fn as_bytes(self) -> [u8; 2] { match self { // For single shot, listing each variant directly. Command::StartSingleShot{repeatability: Repeatability::High} => [0x24, 0x00], Command::StartSingleShot{repeatability: Repeatability::Medium} => [0x24, 0x0B], Command::StartSingleShot{repeatability: Repeatability::Low} => [0x24, 0x16], // For periodic, using nested matches, more lines of code, but hopefully more readable. Command::StartPeriodic{repeatability: r, conversion_rate: c} => { match c { ConversionRate::_0_5Hz => { match r { Repeatability::High => [0x20, 0x32], Repeatability::Medium => [0x20, 0x24], Repeatability::Low => [0x20, 0x2F], } }, ConversionRate::_1Hz => { match r { Repeatability::High => [0x21, 0x30], Repeatability::Medium => [0x21, 0x26], Repeatability::Low => [0x21, 0x2D], } }, ConversionRate::_2Hz => { match r { Repeatability::High => [0x22, 0x36], Repeatability::Medium => [0x22, 0x20], Repeatability::Low => [0x22, 0x2B], } }, ConversionRate::_4Hz => { match r { Repeatability::High => [0x23, 0x34], Repeatability::Medium => [0x23, 0x22], Repeatability::Low => [0x23, 0x29], } }, ConversionRate::_10Hz => { match r { Repeatability::High => [0x27, 0x37], Repeatability::Medium => [0x27, 0x21], Repeatability::Low => [0x27, 0x2A], } }, } }, Command::FetchData => [0xE0, 0x00], Command::Break => [0x30, 0x93], Command::SoftReset => [0x30, 0xA2], Command::HeaterOn => [0x30, 0x6D], Command::HeaterOff => [0x30, 0x66], Command::ReadStatus => [0xF3, 0x2D], Command::ClearStatus => [0x30, 0x41], } } } // TODO: this is from shtcx, and I need to figure out how/whether to implement pub trait MeasurementDuration { /// Return the maximum measurement duration according to repeatability /// in microseconds fn measurement_duration_us(repeat: Repeatability) -> u16; } #[doc(hidden)] // Type states for one-shot and continuous modes. pub mod marker { pub mod mode { #[derive(Debug)] pub struct OneShot(()); #[derive(Debug)] pub struct Continuous(()); } } /// Device Driver #[derive(Debug, Default)] pub struct Sts3x<I2C, MODE> { /// The I2C device implementation i2c: I2C, /// The 7-bit I2C device address address: u8, /// The present repeatabiliy setting repeatability: Repeatability, /// A temperature measurement was started. temp_measurement_started: bool, _mode: PhantomData<MODE>, } // Implement struct creation for OneShot only so that it is only possible to create a one-shot version. impl<I2C, E> Sts3x<I2C, marker::mode::OneShot> where I2C: i2c::Write<Error = E>, { /// Create new instance of the Sts3x device. /// Defaults to Low repeatability for power savings. /// Change repeatability with set_repeatability(). /// /// By default, the device starts in one-shot mode. pub fn new(i2c: I2C, address: PeripheralAddr) -> Self { Sts3x { i2c, address: address.as_byte(), repeatability: Repeatability::default(), temp_measurement_started: false, _mode: PhantomData, } } /// Create new instance of the Sts3x device, choosing a Repeatability. /// /// By default, the device starts in one-shot mode. pub fn new_with_repeatability(i2c: I2C, address: PeripheralAddr, repeatability: Repeatability) -> Self { Sts3x { i2c, address: address.as_byte(), repeatability, temp_measurement_started: false, _mode: PhantomData, } } } // Methods shared by both single-shot and continuous modes impl<I2C, MODE, E> Sts3x<I2C, MODE> where I2C: i2c::Read<Error = E> + i2c::Write<Error = E>, { /// Destroy driver instance and return the I2C bus instance. pub fn destroy(self) -> I2C { self.i2c } // write and read private methods /// Write an I2C command to the sensor fn send_command(&mut self, command: Command) -> Result<(), Error<E>> { self.i2c .write(self.address, &command.as_bytes()) .map_err(Error::I2C) } /// Read and check the CRC. /// Returns a Result with u16 corresponding to the MSB,LSB of the first /// two bytes of the buffer. fn read_with_crc(&mut self) -> Result<u16, Error<E>> { let mut buf = [0u8; 3]; self.i2c.read(self.address, &mut buf).map_err(Error::I2C)?; if crc::is_crc8_valid(&buf) { let x: u16 = (buf[0] as u16) << 8 | (buf[1] as u16); Ok(x) } else { Err(Error::Crc) } } fn convert_temp_to_float(temp: u16) -> f32 { -45.0 + 175.0 * (temp as f32) / 65535.0 } // method about measurement duration? } // Methods for one-shot mode only // TODO: these are nonblocking, but don't utilize the nb concepts. Also make blocking types. impl<I2C, E> Sts3x<I2C, marker::mode::OneShot> where I2C: i2c::Read<Error = E> + i2c::Write<Error = E>, { /// Start a one-shot temperature measurement using the repeatability /// that has already been set. pub fn trigger_temp_meas(&mut self) -> Result<(), Error<E>> { self.send_command(Command::StartSingleShot{repeatability: self.repeatability}) } /// Perform a one-shot temperature measurement. /// /// This allows triggering a single temperature measurement when in /// one-shot mode. The device returns to the low-power state at the /// completion of the temperature conversion, reducing power /// consumption when continuous temperature monitoring is not required. /// /// If no temperature conversion was started yet, calling this method /// will start one and return `nb::Error::WouldBlock`. Subsequent calls /// will continue to return `nb::Error::WouldBlock` until the /// temperature measurement is finished. Then it will return the /// measured temperature in °C. pub fn read_temperature(&mut self) -> nb::Result<f32, Error<E>> { if !self.temp_measurement_started { self.trigger_temp_meas() .map_err(nb::Error::Other)?; self.temp_measurement_started = true; return Err(nb::Error::WouldBlock); } let mut buf = [0u8; 3]; let completion = self.i2c.read(self.address, &mut buf); // What I want to do: // match completion { // Ok(val) => { // // Conversion complete. // let x: u16 = (buf[0] as u16) << 8 | (buf[1] as u16); // self.temp_measurement_started = false; // Ok(Self::convert_temp_to_float(x)) // }, // Err(stm32f3xx_hal::i2c::Error::Nack) => { // I want to replace with a generic path in embedded_hal // // namespace because we shouldn't depend on a specific device HAL. // Err(nb::Error::WouldBlock) // }, // Err(e) => { // Err(nb::Error::Other(Error::I2C(e))) // Not sure this is correct, but compiler doesn't complain. // } // } // What I have to do with embedded_hal 0.2.4/0.2.5: match completion { Ok(_) => { // Conversion complete. self.temp_measurement_started = false; if crc::is_crc8_valid(&buf) { let x: u16 = (buf[0] as u16) << 8 | (buf[1] as u16); Ok(Self::convert_temp_to_float(x)) } else { Err(nb::Error::Other(Error::Crc)) } }, _ => { Err(nb::Error::WouldBlock) } } } pub fn set_repeatability(&mut self, r: Repeatability) -> Repeatability{ self.repeatability = r; r } // pub fn into_continuous(self, rate: ConversionRate) -> Result<Sts3x<I2C, marker::mode::Continuous>, ModeChangeError<E, Self>> // /// Reset the state of the driver, to be used if there was a "general call" on the I2C bus. // pub fn reset_state(&mut self) // pub fn soft_reset(&mut self) // pub fn get_status(&self) // pub fn clear_status(&mut self) // pub fn heater_on(&mut self) // pub fn heater_off(&mut self) } // Methods for continuous mode only impl<I2C, E> Sts3x<I2C, marker::mode::Continuous> where I2C: i2c::Write<Error = E>, { /// Get latest temperature reading. /// TODO: fill out pub fn read_temperature(&self) -> u16 { 25 } // /// Convert to one-shot mode. // /// TODO: add the command to change and a failure error. // pub fn into_one_shot(self) -> Result<Sts3x<I2C, marker::mode::OneShot>, ModeChangeError<E, Self>> { // Result(Sts3x { // i2c: self.i2c, // address: self.address, // repeatability: self.repeatability, // temp_measurement_started: false, // _mode: PhantomData, // }) // } // /// Reset the state of the driver, to be used if there was a "general call" on the I2C bus. // /// This will convert into a one-shot mode device. // pub fn reset_state(mut self) } // impl MeasurementDuration for Sts3x<I2C, MODE> { // // TODO: fill out fn measurement_duration // fn measurement_duration_us(repeat: Repeatability) -> u16 { // 20 // } // }
true
c2cdc62cec14af76951b975bcf6a03f34a1687ff
Rust
3akur6/checksec
/src/main.rs
UTF-8
1,259
2.6875
3
[]
no_license
mod checksec; mod elf; use crate::checksec::checksec; use clap::{App, Arg}; use std::path::Path; use std::process::exit; fn main() { let matches = App::new("CheckSec") .author("3akur6 <github.com/3akur6>") .arg( Arg::with_name("files") .help("Files to check") .multiple(true) .value_name("elf"), ) .arg( Arg::with_name("ex_files") .long("file") .value_name("elf") .multiple(true) .help("File to check (for compatibility with checksec.sh)") .takes_value(true), ) .get_matches(); let files = if matches.is_present("ex_files") { matches.values_of("ex_files") } else { matches.values_of("files") }; let file_names = files.unwrap_or_else(|| { println!("{}", matches.usage()); exit(1); }); for name in file_names { match Path::new(name).canonicalize() { Ok(path) => { if let Err(err) = checksec(path.as_path()) { eprintln!("{}", err); } } Err(err) => eprintln!("'{}': {}", name, err), }; } }
true
bea1fb04fea63b6f251e4aa1a2d2e4a663b0be4d
Rust
oxidecomputer/cli
/src/config_from_env.rs
UTF-8
3,281
2.765625
3
[ "MIT" ]
permissive
use std::env; use anyhow::Result; use thiserror::Error; use crate::cmd_auth::parse_host; use crate::config_file::get_env_var; const OXIDE_HOST: &str = "OXIDE_HOST"; const OXIDE_TOKEN: &str = "OXIDE_TOKEN"; pub struct EnvConfig<'a> { pub config: &'a mut (dyn crate::config::Config + 'a), } impl EnvConfig<'_> { pub fn inherit_env(config: &mut dyn crate::config::Config) -> EnvConfig { EnvConfig { config } } } #[derive(Error, Debug)] pub enum ReadOnlyEnvVarError { #[error("read-only value in: {0}")] Variable(String), } unsafe impl Send for EnvConfig<'_> {} unsafe impl Sync for EnvConfig<'_> {} impl crate::config::Config for EnvConfig<'_> { fn get(&self, hostname: &str, key: &str) -> Result<String> { let (val, _) = self.get_with_source(hostname, key)?; Ok(val) } fn get_with_source(&self, hostname: &str, key: &str) -> Result<(String, String)> { // If they are asking specifically for the token, return the value. if key == "token" { let token = get_env_var(OXIDE_TOKEN); if !token.is_empty() { return Ok((token, OXIDE_TOKEN.to_string())); } } else { let var = format!("OXIDE_{}", heck::AsShoutySnakeCase(key)); let val = get_env_var(&var); if !val.is_empty() { return Ok((val, var)); } } self.config.get_with_source(hostname, key) } fn set(&mut self, hostname: &str, key: &str, value: &str) -> Result<()> { self.config.set(hostname, key, value) } fn unset_host(&mut self, key: &str) -> Result<()> { self.config.unset_host(key) } fn hosts(&self) -> Result<Vec<String>> { self.config.hosts() } fn default_host(&self) -> Result<String> { let (host, _) = self.default_host_with_source()?; Ok(host) } fn default_host_with_source(&self) -> Result<(String, String)> { if let Ok(host) = env::var(OXIDE_HOST) { let host = parse_host(&host)?; Ok((host.to_string(), OXIDE_HOST.to_string())) } else { self.config.default_host_with_source() } } fn aliases(&mut self) -> Result<crate::config_alias::AliasConfig> { self.config.aliases() } fn save_aliases(&mut self, aliases: &crate::config_map::ConfigMap) -> Result<()> { self.config.save_aliases(aliases) } fn expand_alias(&mut self, args: Vec<String>) -> Result<(Vec<String>, bool)> { self.config.expand_alias(args) } fn check_writable(&self, hostname: &str, key: &str) -> Result<()> { // If they are asking specifically for the token, return the value. if key == "token" { let token = get_env_var(OXIDE_TOKEN); if !token.is_empty() { return Err(ReadOnlyEnvVarError::Variable(OXIDE_TOKEN.to_string()).into()); } } self.config.check_writable(hostname, key) } fn write(&self) -> Result<()> { self.config.write() } fn config_to_string(&self) -> Result<String> { self.config.config_to_string() } fn hosts_to_string(&self) -> Result<String> { self.config.hosts_to_string() } }
true
86a27c7e5c9a95a94e2f8fc83f3f7a11da6ab2b7
Rust
jsperafico/learn-rust
/11.3_unit-integration-test/tests/integration_test.rs
UTF-8
263
2.953125
3
[ "MIT" ]
permissive
use unit_integration_test::Point; mod common; #[test] fn must_create_new_point() { common::setup(); Point::new(1,1,1); } #[test] fn must_draw_a_point() { common::setup(); let p = Point::new(1,1,1); assert_eq!(p.draw(), "(1, 1, 1)"); }
true
45602ed700a2ff136cf2fe9719f075e9290af097
Rust
swilcox3/flexi-cad
/operations/src/entity_ops/tests.rs
UTF-8
15,781
2.578125
3
[]
no_license
use super::*; use crate::prelude::*; use crate::tests::*; use crossbeam_channel::Receiver; fn test_setup(desc: &str, callback: impl Fn(PathBuf, UserID, Receiver<UpdateMsg>)) { let file = PathBuf::from(desc); let (s, r) = crossbeam_channel::unbounded(); let user = UserID::new_v4(); app_state::init_file(file.clone(), user, s); callback(file, user, r); } //This makes sure that all the background updates have completed fn empty_receiver(rcv: &Receiver<UpdateMsg>) { while let Ok(_) = rcv.recv_timeout(std::time::Duration::from_millis(1000)) { //Do nothing } } #[test] fn test_copy_objs() { test_setup("copy_objs", |file, user, rcv| { let mut first = Box::new(TestObj::new("first")); let id_1 = first.get_id().clone(); first.move_obj(&Vector3f::new(1.0, 2.0, 3.0)); let mut second = Box::new(TestObj::new("second")); let id_2 = second.get_id().clone(); second.set_ref( 0, &RefGeometry::Point { pt: Point3f::new(1.0, 2.0, 3.0), }, GeometryId { id: id_1.clone(), index: 0 }, &None, ); let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("add objs")).unwrap(); app_state::add_obj(&file, &event, first).unwrap(); app_state::add_obj(&file, &event, second).unwrap(); app_state::end_undo_event(&file, event).unwrap(); let mut copy_set = HashSet::new(); copy_set.insert(id_1); copy_set.insert(id_2); let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("copy objs")).unwrap(); let (_, orig_to_dups) = copy_objs(&file, &event, copy_set).unwrap(); assert_eq!(orig_to_dups.len(), 2); let copy_id_1 = orig_to_dups.get(&id_1).unwrap(); let copy_id_2 = orig_to_dups.get(&id_2).unwrap(); crate::move_obj(file.clone(), &event, copy_id_1.clone(), &Vector3f::new(0.0, 0.0, 1.0)).unwrap(); empty_receiver(&rcv); app_state::get_obj(&file, &copy_id_1, |obj| { let point_ref = obj.query_ref::<dyn ReferTo>().unwrap(); assert_eq!( point_ref.get_result(0), Some(RefGeometry::Point { pt: Point3f::new(1.0, 2.0, 4.0) }) ); Ok(()) }) .unwrap(); app_state::get_obj(&file, &copy_id_2, |obj| { let point_ref = obj.query_ref::<dyn ReferTo>().unwrap(); assert_eq!( point_ref.get_result(0), Some(RefGeometry::Point { pt: Point3f::new(1.0, 2.0, 4.0) }) ); Ok(()) }) .unwrap(); }); } #[test] fn test_join_walls() { test_setup("join walls", |file, user, rcv| { let first = Box::new(Wall::new(Point3f::new(1.0, 2.0, 3.0), Point3f::new(2.0, 2.0, 3.0), 1.0, 1.0)); let id_1 = first.get_id().clone(); let second = Box::new(Wall::new(Point3f::new(2.0, 3.0, 4.0), Point3f::new(4.0, 5.0, 6.0), 1.0, 1.0)); let id_2 = second.get_id().clone(); let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("add objs")).unwrap(); app_state::add_obj(&file, &event, first).unwrap(); app_state::add_obj(&file, &event, second).unwrap(); app_state::end_undo_event(&file, event).unwrap(); let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("snap objs")).unwrap(); crate::join_objs( file.clone(), &event, id_1.clone(), id_2.clone(), &RefType::Point, &RefType::Point, &Point3f::new(2.0, 4.0, 3.0), ) .unwrap(); empty_receiver(&rcv); crate::move_obj(file.clone(), &event, id_1.clone(), &Vector3f::new(0.0, 1.0, 0.0)).unwrap(); app_state::end_undo_event(&file, event).unwrap(); empty_receiver(&rcv); app_state::get_obj(&file, &id_1, |first| { let read = first.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(1.0, 3.0, 3.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(2.0, 3.0, 3.0) } ); Ok(()) }) .unwrap(); app_state::get_obj(&file, &id_2, |second| { let read = second.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(2.0, 3.0, 3.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(4.0, 5.0, 6.0) } ); Ok(()) }) .unwrap(); }); } #[test] fn test_join_door_and_wall() { test_setup("snap door to wall", |file, user, rcv| { let first = Box::new(Wall::new(Point3f::new(0.0, 0.0, 0.0), Point3f::new(1.0, 0.0, 0.0), 1.0, 1.0)); let id_1 = first.get_id().clone(); let second = Box::new(Door::new(Point3f::new(1.0, 2.0, 3.0), Point3f::new(1.0, 2.5, 3.0), 1.0, 1.0)); let id_2 = second.get_id().clone(); let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("add objs")).unwrap(); app_state::add_obj(&file, &event, first).unwrap(); app_state::add_obj(&file, &event, second).unwrap(); app_state::end_undo_event(&file, event).unwrap(); let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("snap objs")).unwrap(); crate::join_objs( file.clone(), &event, id_1.clone(), id_2.clone(), &RefType::Rect, &RefType::Line, &Point3f::new(0.25, 1.0, 0.0), ) .unwrap(); app_state::end_undo_event(&file, event).unwrap(); empty_receiver(&rcv); app_state::get_obj(&file, &id_2, |second| { let read = second.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(0.25, 0.0, 0.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(0.75, 0.0, 0.0) } ); Ok(()) }) .unwrap(); let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("move obj")).unwrap(); crate::move_obj(file.clone(), &event, id_1.clone(), &Vector3f::new(0.0, 1.0, 0.0)).unwrap(); app_state::end_undo_event(&file, event).unwrap(); empty_receiver(&rcv); app_state::get_obj(&file, &id_2, |second| { let read = second.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(0.25, 1.0, 0.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(0.75, 1.0, 0.0) } ); Ok(()) }) .unwrap(); }); } #[test] fn test_walls_and_doors() { test_setup("walls and doors", |file, user, rcv| { let first = Box::new(Wall::new(Point3f::new(0.0, 0.0, 0.0), Point3f::new(1.0, 0.0, 0.0), 0.5, 1.0)); let wall_1_id = first.get_id().clone(); let second = Box::new(Wall::new(Point3f::new(1.0, 0.0, 0.0), Point3f::new(1.0, 1.0, 0.0), 0.5, 1.0)); let wall_2_id = second.get_id().clone(); let third = Box::new(Wall::new(Point3f::new(1.0, 1.0, 0.0), Point3f::new(0.0, 1.0, 0.0), 0.5, 1.0)); let wall_3_id = third.get_id().clone(); let door_1 = Box::new(Door::new(Point3f::new(0.25, 0.0, 0.0), Point3f::new(0.75, 0.0, 0.0), 0.25, 0.75)); let door_1_id = door_1.get_id().clone(); let door_2 = Box::new(Door::new(Point3f::new(1.0, 0.25, 0.0), Point3f::new(1.0, 0.75, 0.0), 0.25, 0.75)); let door_2_id = door_2.get_id().clone(); let door_3 = Box::new(Door::new(Point3f::new(0.75, 1.0, 0.0), Point3f::new(0.25, 1.0, 0.0), 0.25, 0.75)); let door_3_id = door_3.get_id().clone(); /*println!("wall 1: {:?}", wall_1_id); println!("wall 2: {:?}", wall_2_id); println!("wall 3: {:?}", wall_3_id); println!("door 1: {:?}", door_1_id); println!("door 2: {:?}", door_2_id); println!("door 3: {:?}", door_3_id);*/ let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("add objs")).unwrap(); app_state::add_obj(&file, &event, first).unwrap(); app_state::add_obj(&file, &event, second).unwrap(); app_state::add_obj(&file, &event, third).unwrap(); app_state::add_obj(&file, &event, door_1).unwrap(); app_state::add_obj(&file, &event, door_2).unwrap(); app_state::add_obj(&file, &event, door_3).unwrap(); app_state::end_undo_event(&file, event).unwrap(); let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("snap objs")).unwrap(); join_refs( &file, &event, &wall_1_id, &wall_2_id, &RefType::Point, &RefType::Point, &Point3f::new(1.0, 0.0, 0.0), ) .unwrap(); join_refs( &file, &event, &wall_2_id, &wall_3_id, &RefType::Point, &RefType::Point, &Point3f::new(1.0, 1.0, 0.0), ) .unwrap(); join_refs( &file, &event, &door_1_id, &wall_1_id, &RefType::Line, &RefType::Rect, &Point3f::new(0.25, 0.0, 0.0), ) .unwrap(); join_refs( &file, &event, &door_2_id, &wall_2_id, &RefType::Line, &RefType::Rect, &Point3f::new(1.0, 0.25, 0.0), ) .unwrap(); join_refs( &file, &event, &door_3_id, &wall_3_id, &RefType::Line, &RefType::Rect, &Point3f::new(0.75, 1.0, 0.0), ) .unwrap(); app_state::end_undo_event(&file, event).unwrap(); empty_receiver(&rcv); let event = UndoEventID::new_v4(); app_state::begin_undo_event(&file, &user, event.clone(), String::from("move obj")).unwrap(); crate::move_obj(file.clone(), &event, wall_2_id.clone(), &Vector3f::new(1.0, 0.0, 0.0)).unwrap(); app_state::end_undo_event(&file, event).unwrap(); empty_receiver(&rcv); app_state::get_obj(&file, &wall_2_id, |second| { let read = second.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(2.0, 0.0, 0.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(2.0, 1.0, 0.0) } ); assert_eq!( pts[3], RefGeometry::Rect { pt_1: Point3f::new(2.0, 0.25, 0.0), pt_2: Point3f::new(2.0, 0.75, 0.0), pt_3: Point3f::new(2.0, 0.75, 0.75) } ); Ok(()) }) .unwrap(); app_state::get_obj(&file, &door_2_id, |second| { let read = second.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(2.0, 0.25, 0.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(2.0, 0.75, 0.0) } ); Ok(()) }) .unwrap(); app_state::get_obj(&file, &door_1_id, |wall| { let read = wall.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(0.5, 0.0, 0.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(1.0, 0.0, 0.0) } ); Ok(()) }) .unwrap(); app_state::get_obj(&file, &door_3_id, |wall| { let read = wall.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(1.5, 1.0, 0.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(1.0, 1.0, 0.0) } ); Ok(()) }) .unwrap(); app_state::get_obj(&file, &wall_1_id, |wall| { let read = wall.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(0.0, 0.0, 0.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(2.0, 0.0, 0.0) } ); assert_eq!( pts[3], RefGeometry::Rect { pt_1: Point3f::new(0.5, 0.0, 0.0), pt_2: Point3f::new(1.0, 0.0, 0.0), pt_3: Point3f::new(1.0, 0.0, 0.75) } ); Ok(()) }) .unwrap(); app_state::get_obj(&file, &wall_3_id, |wall| { let read = wall.query_ref::<dyn ReferTo>().unwrap(); let pts = read.get_all_results(); assert_eq!( pts[0], RefGeometry::Point { pt: Point3f::new(2.0, 1.0, 0.0) } ); assert_eq!( pts[1], RefGeometry::Point { pt: Point3f::new(0.0, 1.0, 0.0) } ); assert_eq!( pts[3], RefGeometry::Rect { pt_1: Point3f::new(1.5, 1.0, 0.0), pt_2: Point3f::new(1.0, 1.0, 0.0), pt_3: Point3f::new(1.0, 1.0, 0.75) } ); Ok(()) }) .unwrap(); }); }
true
4ff2ea6485dd295a2d8a861f64ac143c7bb2b40d
Rust
KotoDevelopers/koto
/src/rust/src/metrics_ffi.rs
UTF-8
7,523
2.53125
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT", "AGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
use libc::{c_char, c_double}; use metrics::{try_recorder, GaugeValue, Key, Label}; use metrics_exporter_prometheus::PrometheusBuilder; use std::ffi::CStr; use std::net::{IpAddr, SocketAddr}; use std::ptr; use std::slice; use tracing::error; #[no_mangle] pub extern "C" fn metrics_run( bind_address: *const c_char, allow_ips: *const *const c_char, allow_ips_len: usize, prometheus_port: u16, ) -> bool { // Parse any allowed IPs. let allow_ips = unsafe { slice::from_raw_parts(allow_ips, allow_ips_len) }; let mut allow_ips: Vec<ipnet::IpNet> = match allow_ips .iter() .map(|&p| unsafe { CStr::from_ptr(p) }) .map(|s| { s.to_str().ok().and_then(|s| { s.parse() .map_err(|e| { error!("Invalid -metricsallowip argument '{}': {}", s, e); }) .ok() }) }) .collect() { Some(ips) => ips, None => { return false; } }; // We always allow localhost. allow_ips.extend(&["127.0.0.0/8".parse().unwrap(), "::1/128".parse().unwrap()]); // Parse the address to bind to. let bind_address = SocketAddr::new( if allow_ips.is_empty() { // Default to loopback if not allowing external IPs. "127.0.0.1".parse::<IpAddr>().unwrap() } else if bind_address.is_null() { // No specific bind address specified, bind to any. "0.0.0.0".parse::<IpAddr>().unwrap() } else { match unsafe { CStr::from_ptr(bind_address) } .to_str() .ok() .and_then(|s| s.parse::<IpAddr>().ok()) { Some(addr) => addr, None => { error!("Invalid -metricsbind argument"); return false; } } }, prometheus_port, ); allow_ips .into_iter() .fold( PrometheusBuilder::new().listen_address(bind_address), |builder, subnet| builder.add_allowed(subnet), ) .install() .is_ok() } pub struct FfiCallsite { key: Key, } #[no_mangle] pub extern "C" fn metrics_callsite( name: *const c_char, label_names: *const *const c_char, label_values: *const *const c_char, labels_len: usize, ) -> *mut FfiCallsite { let name = unsafe { CStr::from_ptr(name) }.to_str().unwrap(); let labels = unsafe { slice::from_raw_parts(label_names, labels_len) }; let values = unsafe { slice::from_raw_parts(label_values, labels_len) }; let stringify = |s: &[_]| { s.iter() .map(|&p| unsafe { CStr::from_ptr(p) }) .map(|cs| cs.to_string_lossy().into_owned()) .collect::<Vec<_>>() }; let labels = stringify(labels); let values = stringify(values); let labels: Vec<_> = labels .into_iter() .zip(values.into_iter()) .map(|(name, value)| Label::new(name, value)) .collect(); Box::into_raw(Box::new(FfiCallsite { key: Key::from_parts(name, labels), })) } pub struct FfiKey { inner: Key, } #[no_mangle] pub extern "C" fn metrics_key( name: *const c_char, label_names: *const *const c_char, label_values: *const *const c_char, labels_len: usize, ) -> *mut FfiKey { if try_recorder().is_none() { // No recorder is currently installed, so don't genenerate a key. We check for // null inside each API that consumes an FfiKey, just in case a recorder was // installed in a racy way. ptr::null_mut() } else { let name = unsafe { CStr::from_ptr(name) }.to_str().unwrap(); let labels = unsafe { slice::from_raw_parts(label_names, labels_len) }; let values = unsafe { slice::from_raw_parts(label_values, labels_len) }; let stringify = |s: &[_]| { s.iter() .map(|&p| unsafe { CStr::from_ptr(p) }) .map(|cs| cs.to_string_lossy().into_owned()) .collect::<Vec<_>>() }; let labels = stringify(labels); let values = stringify(values); let labels: Vec<_> = labels .into_iter() .zip(values.into_iter()) .map(|(name, value)| Label::new(name, value)) .collect(); Box::into_raw(Box::new(FfiKey { inner: Key::from_parts(name, labels), })) } } #[no_mangle] pub extern "C" fn metrics_static_increment_counter(callsite: *const FfiCallsite, value: u64) { if let Some(recorder) = try_recorder() { let callsite = unsafe { callsite.as_ref().unwrap() }; recorder.increment_counter(&callsite.key, value); } } #[no_mangle] pub extern "C" fn metrics_increment_counter(key: *mut FfiKey, value: u64) { if let Some(recorder) = try_recorder() { if !key.is_null() { let key = unsafe { Box::from_raw(key) }; recorder.increment_counter(&key.inner, value); } } } #[no_mangle] pub extern "C" fn metrics_static_update_gauge(callsite: *const FfiCallsite, value: c_double) { if let Some(recorder) = try_recorder() { let callsite = unsafe { callsite.as_ref().unwrap() }; recorder.update_gauge(&callsite.key, GaugeValue::Absolute(value)); } } #[no_mangle] pub extern "C" fn metrics_update_gauge(key: *mut FfiKey, value: c_double) { if let Some(recorder) = try_recorder() { if !key.is_null() { let key = unsafe { Box::from_raw(key) }; recorder.update_gauge(&key.inner, GaugeValue::Absolute(value)); } } } #[no_mangle] pub extern "C" fn metrics_static_increment_gauge(callsite: *const FfiCallsite, value: c_double) { if let Some(recorder) = try_recorder() { let callsite = unsafe { callsite.as_ref().unwrap() }; recorder.update_gauge(&callsite.key, GaugeValue::Increment(value)); } } #[no_mangle] pub extern "C" fn metrics_increment_gauge(key: *mut FfiKey, value: c_double) { if let Some(recorder) = try_recorder() { if !key.is_null() { let key = unsafe { Box::from_raw(key) }; recorder.update_gauge(&key.inner, GaugeValue::Increment(value)); } } } #[no_mangle] pub extern "C" fn metrics_static_decrement_gauge(callsite: *const FfiCallsite, value: c_double) { if let Some(recorder) = try_recorder() { let callsite = unsafe { callsite.as_ref().unwrap() }; recorder.update_gauge(&callsite.key, GaugeValue::Decrement(value)); } } #[no_mangle] pub extern "C" fn metrics_decrement_gauge(key: *mut FfiKey, value: c_double) { if let Some(recorder) = try_recorder() { if !key.is_null() { let key = unsafe { Box::from_raw(key) }; recorder.update_gauge(&key.inner, GaugeValue::Decrement(value)); } } } #[no_mangle] pub extern "C" fn metrics_static_record_histogram(callsite: *const FfiCallsite, value: c_double) { if let Some(recorder) = try_recorder() { let callsite = unsafe { callsite.as_ref().unwrap() }; recorder.record_histogram(&callsite.key, value); } } #[no_mangle] pub extern "C" fn metrics_record_histogram(key: *mut FfiKey, value: c_double) { if let Some(recorder) = try_recorder() { if !key.is_null() { let key = unsafe { Box::from_raw(key) }; recorder.record_histogram(&key.inner, value); } } }
true
794a9c5d00621f26d34a2fe2bc7344959d7eef70
Rust
travismiller/not80
/src/main.rs
UTF-8
2,441
2.734375
3
[]
no_license
extern crate dotenv; #[macro_use] extern crate error_chain; extern crate futures; extern crate hyper; use dotenv::dotenv; use futures::future::Future; use hyper::{StatusCode}; use hyper::header::{ContentLength, ContentType, Host, Location}; use hyper::server::{Http, Request, Response, Service}; use std::env; use std::net::SocketAddr; use std::str; error_chain! { foreign_links { AddrParse(std::net::AddrParseError); Hyper(hyper::Error); Utf8(std::str::Utf8Error); } } struct Not80; impl Not80 { fn location_from_request(&self, request: &Request) -> String { let host = request.headers().get::<Host>() .expect("Host was not included."); let query = match request.query() { Some(q) => format!("?{}", q), None => "".to_string() }; format!("https://{}{}{}", host, request.path(), query) } fn content_from_location(&self, location: &String) -> String { format!("<!doctype>\n<html><body><a href=\"{}\">{}</a></body></html>\n", location, location) } fn location_and_content(&self, request: &Request) -> (String, String) { let location = self.location_from_request(&request); let content = self.content_from_location(&location); (location, content) } } impl Service for Not80 { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = Box<Future<Item=Self::Response, Error=Self::Error>>; fn call(&self, request: Request) -> Self::Future { let (location, content) = self.location_and_content(&request); let response = Response::new() .with_status(StatusCode::Found) .with_header(Location::new(location)) .with_header(ContentLength(content.len() as u64)) .with_header(ContentType::html()) .with_body(content); Box::new(futures::future::ok(response)) } } fn http_server(listen: &String) -> Result<()> { let address: SocketAddr = listen.parse()?; let server = Http::new().bind(&address, || Ok(Not80))?; server.run()?; Ok(()) } fn run() -> Result<()> { dotenv().ok(); let listen: String = match env::var("LISTEN") { Ok(value) => value, Err(_) => panic!("Environment variable LISTEN must be defined."), }; println!("{}", listen); http_server(&listen)?; Ok(()) } quick_main!(run);
true
37c87f5486b320e748d30b230ecb83552e74fe4a
Rust
jujinesy/storycraft_loco-protocol-rs
/src/network.rs
UTF-8
5,585
2.828125
3
[ "MIT" ]
permissive
/* * Created on Sat Nov 28 2020 * * Copyright (c) storycraft. Licensed under the MIT Licence. */ use std::{collections::HashMap, io::{self, Read, Write}, sync::mpsc::Receiver, sync::mpsc::SendError, sync::mpsc::{Sender, channel}}; use crate::command::{self, Command, processor::CommandProcessor}; #[derive(Debug)] pub enum Error { Command(command::Error), Channel, Socket(io::Error) } impl From<command::Error> for Error { fn from(err: command::Error) -> Self { Error::Command(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::Socket(err) } } impl<A> From<SendError<A>> for Error { fn from(_: SendError<A>) -> Self { Error::Channel } } /// ConnectionChannel holds Sender and Receiver crossed with another ConnectionChannel pair. /// Usually considered as user side and server side pair. pub struct ConnectionChannel { id: u32, sender: Sender<Command>, receiver: Receiver<Command>, } impl ConnectionChannel { pub fn new_pair(id: u32) -> (ConnectionChannel, ConnectionChannel) { let user = channel::<Command>(); let socket = channel::<Command>(); ( ConnectionChannel { id, sender: user.0, receiver: socket.1, }, ConnectionChannel { id, sender: socket.0, receiver: user.1 } ) } pub fn id(&self) -> u32 { self.id } pub fn sender(&self) -> &Sender<Command> { &self.sender } pub fn receiver(&self) -> &Receiver<Command> { &self.receiver } } /// ChannelConnection wrap command stream and process it. /// The response command will only send to sender channel. /// If response command doesn't have sender, It will treat as broadcast command and will be sent to every channel attached. pub struct ChannelConnection<A: Read + Write> { processor: CommandProcessor<A>, next_channel_id: u32, channel_map: HashMap<u32, ConnectionChannel>, command_channel: HashMap<i32, u32> } impl<A: Read + Write> ChannelConnection<A> { pub fn new(processor: CommandProcessor<A>) -> Self { Self { processor, next_channel_id: 0, channel_map: HashMap::new(), command_channel: HashMap::new() } } pub fn processor(&self) -> &CommandProcessor<A> { &self.processor } pub fn channel_map(&self) -> &HashMap<u32, ConnectionChannel> { &self.channel_map } /// Attach channel between instance. /// The returned ConnectionChannel struct is user side Channel. pub fn create_channel(&mut self) -> ConnectionChannel { let (user_channel, socket_channel) = ConnectionChannel::new_pair(self.next_channel_id); self.next_channel_id += 1; self.channel_map.insert(user_channel.id(), socket_channel); user_channel } pub fn detach_channel(&mut self, channel: ConnectionChannel) -> (ConnectionChannel, Option<ConnectionChannel>) { let id = channel.id(); (channel, self.channel_map.remove(&id)) } pub fn process(&mut self) -> Result<(), Error> { let mut command_list = Vec::<Command>::new(); for channel in self.channel_map.values() { for command in channel.receiver().try_iter() { self.command_channel.insert(command.header.id, channel.id()); command_list.push(command); } } self.processor.write_all_command(command_list)?; let command = self.processor.read_command()?; match command { Some(command) => { match self.command_channel.remove(&command.header.id) { Some(channel_id) => { match self.channel_map.get(&channel_id) { Some(channel) => { channel.sender.send(command)?; } None => {} } } None => { for channel in self.channel_map.values() { channel.sender().send(command.clone())?; } } } } None => {} } Ok(()) } } pub type ResponseHandler = fn(Command, Command); /// Handle command responses from ConnectionChannel pub struct ChannelHandler { pub channel: ConnectionChannel, command_map: HashMap<i32, (Command, ResponseHandler)> } impl ChannelHandler { pub fn new(channel: ConnectionChannel) -> Self { Self { channel, command_map: HashMap::new() } } pub fn send_command(&mut self, command: Command, response_handler: ResponseHandler) -> Result<(), SendError<Command>> { self.command_map.insert(command.header.id, (command.clone(), response_handler)); self.channel.sender().send(command) } pub fn handle(&mut self) { let iter = self.channel.receiver().try_iter(); for response in iter { let id = response.header.id; match self.command_map.remove(&id) { Some(request_set) => { let response_handler = request_set.1; response_handler(response, request_set.0); } None => {} }; } } }
true
fa01d1970e05a34f85faa2d0016c4fc2d78ed3e9
Rust
abonander/rust-image
/src/gif/mod.rs
UTF-8
789
2.703125
3
[ "MIT" ]
permissive
//! Decoding of GIF Images //! //! GIF (Graphics Interchange Format) is an image format that supports lossless compression. //! //! # Related Links //! * http://www.w3.org/Graphics/GIF/spec-gif89a.txt - The GIF Specification //! pub use self::decoder::GIFDecoder; pub use self::encoder::Encoder as GIFEncoder; pub use self::encoder::ColorMode; mod decoder; mod encoder; #[derive(FromPrimitive)] /// Known block types enum Block { Image = 0x2C, Extension = 0x21, Trailer = 0x3B } #[derive(FromPrimitive)] /// Known GIF extensions enum Extension { Text = 0x01, Control = 0xF9, Comment = 0xFE, Application = 0xFF } #[derive(FromPrimitive)] /// Method to dispose the image enum DisposalMethod { Undefined = 0, None = 1, Previous = 2, Background = 3 }
true
7d4a4f7ba79407d188298a7c9fac90237ee29650
Rust
dai1975/fiatproof
/src/bitcoin/protocol/message/ping_message.rs
UTF-8
1,621
2.8125
3
[ "Apache-2.0" ]
permissive
#[derive(Debug,Default,Clone)] pub struct PingMessage { pub nonce: u64, } use super::message::{ Message, COMMAND_LENGTH }; impl Message for PingMessage { const COMMAND:[u8; COMMAND_LENGTH] = [0x70, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; } impl std::fmt::Display for PingMessage { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Ping(nonce={})", self.nonce) } } impl PingMessage { pub fn reset_nonce(&mut self) { use rand::Rng; let mut rng = rand::rngs::OsRng::new().unwrap(); // This rng is cryptographic level, is it too secure? self.nonce = rng.gen::<u64>(); } } use crate::bitcoin::serialize::{ Serializer as BitcoinSerializer, Serializee as BitcoinSerializee, Deserializer as BitcoinDeserializer, Deserializee as BitcoinDeserializee, }; impl BitcoinSerializee for PingMessage { type P = (); fn serialize<W: std::io::Write>(&self, _p:&Self::P, e:&BitcoinSerializer, ws:&mut W) -> crate::Result<usize> { let mut r:usize = 0; use super::super::apriori::BIP0031_VERSION; if BIP0031_VERSION < e.medium().version() { r += e.serialize_u64le(ws, self.nonce)?; } Ok(r) } } impl BitcoinDeserializee for PingMessage { type P = (); fn deserialize<R: std::io::Read>(&mut self, _p:&Self::P, d:&BitcoinDeserializer, rs:&mut R) -> crate::Result<usize> { let mut r:usize = 0; use super::super::apriori::BIP0031_VERSION; if BIP0031_VERSION < d.medium().version() { r += d.deserialize_u64le(rs, &mut self.nonce)?; } Ok(r) } }
true
0f263d5d139f06762bf5e85e34bf6991fc75604b
Rust
johnz133/hyper
/src/http2/notes.rs
UTF-8
1,664
2.796875
3
[ "MIT" ]
permissive
pub enum HttpFrame { //3 frames pub struct HttpConnection<S> where S: TransportStream { pub fn with_stream(stream: S) -> HttpConnection<S> { pub fn send_frame<F: Frame>(&mut self, frame: F) -> HttpResult<()> { pub fn recv_frame(&mut self) -> HttpResult<HttpFrame> { pub struct ClientConnection<TS, S> where TS: TransportStream, S: Session { pub fn new(stream: TS, session: S) -> ClientConnection<TS, S> { pub fn with_connection(conn: HttpConnection<TS>, session: S) -> ClientConnection<TS, S> { pub fn init(&mut self) -> HttpResult<()> { pub fn send_request(&mut self, req: Request) -> HttpResult<()> { pub fn handle_next_frame(&mut self) -> HttpResut<()> { pub type Header // tuple of 2 Vec<u8> pub struct Response { pub fn new(stream_id: StreamId, headers: Vec<Header>, body: Vec<u8>) -> Response { pub fn status_code(&self) -> HttpResult<u16> { pub struct Request { //StreamId //headers //body // from http2/mod.rs pub type HttpResult<T> = Result<T, HttpError>; SimpleClient //conn ClientConnection/HttpConnection //next stream id << Fix? //host pub fn connect(host: &str, port: u16) -> HttpResult<SimpleClient> { pub fn request(&mut self, method: &[u8], path: &[u8], extras: &[Header]) -> HttpResult<StreamId> { pub fn get_response(&mut self, stream_id: StreamId) -> HttpResult<Response> { // net.rs pub trait NetworkConnector { /// Type of Stream to create type Stream: NetworkStream + Send; /// Connect to a remote address. fn connect(&mut self, host: &str, port: u16, scheme: &str) -> io::Result<Self::Stream>; }
true
83bb7eb12fa99672ef3877a5e6846038ab95af57
Rust
Xiantas/Render
/src/camera.rs
UTF-8
482
2.96875
3
[]
no_license
/* Définition de la caméra 'fov' paramètre l'angle de la vision de la caméra */ #![allow(non_snake_case)] use crate::rotation::{Rotation, Coords}; pub struct Camera { pub pos: Coords, pub rot: Rotation, fov: f64 } impl Camera { pub fn new(pos: Coords, rot: Rotation, fov: f64) -> Camera { Camera { pos, rot, fov: fov.max(0.0) } } pub fn fov(&self) -> f64 { self.fov } pub fn set_fov(&mut self, new_fov: f64) { self.fov = new_fov.max(0.0); } }
true
79203d8a848fbaf0bac709d6500b572b6aaac235
Rust
gf712/advent-of-code-2019
/day2/rust/day2/src/lib.rs
UTF-8
1,675
3.484375
3
[]
no_license
fn process_operations(vec: &mut Vec<usize>) { let mut i: usize = 0; while i < vec.len() { let value = match vec[i] { 1 => vec[vec[i + 1]] + vec[vec[i + 2]], 2 => vec[vec[i + 1]] * vec[vec[i + 2]], _ => return, }; let pos = vec[i + 3]; vec[pos] = value; i += 4; } } fn remove_whitespace(s: &mut String) { s.retain(|c| !c.is_whitespace()); } pub fn add_launch_code(string: String, noun: String, verb: String) -> String { let mut result_vec = Vec::<String>::new(); let mut internal_string = string; remove_whitespace(&mut internal_string); let mut iter = internal_string.split(","); result_vec.push(iter.next().unwrap().to_string()); result_vec.push(noun); result_vec.push(verb); iter.next(); iter.next(); for el in iter { result_vec.push(el.to_string()); } return result_vec.join(","); } pub fn parse(string: String) -> String { let mut result_vec = Vec::<usize>::new(); let mut internal_string = string; remove_whitespace(&mut internal_string); // for convenience translate string to Vec<usize> for el in internal_string.split(",") { let value = el.parse::<usize>().expect("Unable to parse value as int"); result_vec.push(value); } process_operations(&mut result_vec); let mut string_result_vec = Vec::<String>::with_capacity(result_vec.len()); // convert Vec<usize> to string and then join (more convenient than adding the ",") for el in result_vec.iter() { string_result_vec.push(el.to_string()); } return string_result_vec.join(","); }
true
8ab4a91af684fcc4f65de7f447dae539fb2a73a9
Rust
noobLue/tmc-langs-rust
/tmc-langs-framework/src/command.rs
UTF-8
8,162
3.1875
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Custom wrapper for Command that supports timeouts and contains custom error handling. use crate::{error::CommandError, TmcError}; use std::io::Read; use std::time::Duration; use std::{ffi::OsStr, thread::JoinHandle}; use std::{fs::File, io::Write}; pub use subprocess::ExitStatus; use subprocess::{Exec, PopenError, Redirection}; /// Wrapper around subprocess::Exec #[must_use] pub struct TmcCommand { exec: Exec, stdin: Option<String>, } impl TmcCommand { /// Creates a new command pub fn new(cmd: impl AsRef<OsStr>) -> Self { Self { exec: Exec::cmd(cmd).env("LANG", "en_US.UTF-8"), stdin: None, } } /// Creates a new command with piped stdout/stderr. pub fn piped(cmd: impl AsRef<OsStr>) -> Self { Self { exec: Exec::cmd(cmd) .stdout(Redirection::Pipe) .stderr(Redirection::Pipe) .env("LANG", "en_US.UTF-8"), stdin: None, } } /// Allows modification of the internal command without providing access to it. pub fn with(self, f: impl FnOnce(Exec) -> Exec) -> Self { Self { exec: f(self.exec), ..self } } /// Gives the command data to write into stdin. pub fn set_stdin_data(self, data: String) -> Self { Self { exec: self.exec.stdin(Redirection::Pipe), stdin: Some(data), } } // executes the given command and collects its output fn execute(self, timeout: Option<Duration>, checked: bool) -> Result<Output, TmcError> { let cmd = self.exec.to_cmdline_lossy(); log::info!("executing {}", cmd); let Self { exec, stdin } = self; // starts executing the command let mut popen = exec.popen().map_err(|e| popen_to_tmc_err(cmd.clone(), e))?; let stdin_handle = spawn_writer(popen.stdin.take(), stdin); let stdout_handle = spawn_reader(popen.stdout.take()); let stderr_handle = spawn_reader(popen.stderr.take()); let exit_status = if let Some(timeout) = timeout { // timeout set let exit_status = popen .wait_timeout(timeout) .map_err(|e| popen_to_tmc_err(cmd.clone(), e))?; match exit_status { Some(exit_status) => exit_status, None => { // None means that we timed out popen .terminate() .map_err(|e| CommandError::Terminate(cmd.clone(), e))?; let stdout = stdout_handle .join() .expect("the thread should not be able to panic"); let stderr = stderr_handle .join() .expect("the thread should not be able to panic"); return Err(TmcError::Command(CommandError::TimeOut { command: cmd, timeout, stdout: String::from_utf8_lossy(&stdout).into_owned(), stderr: String::from_utf8_lossy(&stderr).into_owned(), })); } } } else { // no timeout, block until done popen.wait().map_err(|e| popen_to_tmc_err(cmd.clone(), e))? }; log::info!("finished executing {}", cmd); stdin_handle .join() .expect("the thread should not be able to panic"); let stdout = stdout_handle .join() .expect("the thread should not be able to panic"); let stderr = stderr_handle .join() .expect("the thread should not be able to panic"); // on success, log stdout trace and stderr debug // on failure if checked, log warn // on failure if not checked, log debug if !exit_status.success() { // if checked is set, error with failed exit status if checked { log::warn!("stdout: {}", String::from_utf8_lossy(&stdout).into_owned()); log::warn!("stderr: {}", String::from_utf8_lossy(&stderr).into_owned()); return Err(CommandError::Failed { command: cmd, status: exit_status, stdout: String::from_utf8_lossy(&stdout).into_owned(), stderr: String::from_utf8_lossy(&stderr).into_owned(), } .into()); } else { log::debug!("stdout: {}", String::from_utf8_lossy(&stdout).into_owned()); log::debug!("stderr: {}", String::from_utf8_lossy(&stderr).into_owned()); } } else { log::trace!("stdout: {}", String::from_utf8_lossy(&stdout).into_owned()); log::debug!("stderr: {}", String::from_utf8_lossy(&stderr).into_owned()); } Ok(Output { status: exit_status, stdout, stderr, }) } /// Executes the command and waits for its output. pub fn status(self) -> Result<ExitStatus, TmcError> { self.execute(None, false).map(|o| o.status) } /// Executes the command and waits for its output. pub fn output(self) -> Result<Output, TmcError> { self.execute(None, false) } /// Executes the command and waits for its output and errors if the status is not successful. pub fn output_checked(self) -> Result<Output, TmcError> { self.execute(None, true) } /// Executes the command and waits for its output with the given timeout. pub fn output_with_timeout(self, timeout: Duration) -> Result<Output, TmcError> { self.execute(Some(timeout), false) } /// Executes the command and waits for its output with the given timeout and errors if the status is not successful. pub fn output_with_timeout_checked(self, timeout: Duration) -> Result<Output, TmcError> { self.execute(Some(timeout), true) } } // it's assumed the thread will never panic fn spawn_writer(file: Option<File>, data: Option<String>) -> JoinHandle<()> { std::thread::spawn(move || { if let Some(mut file) = file { if let Some(data) = data { log::debug!("writing data"); if let Err(err) = file.write_all(data.as_bytes()) { log::error!("failed to write data in writer thread: {}", err); } } } }) } // it's assumed the thread will never panic fn spawn_reader(file: Option<File>) -> JoinHandle<Vec<u8>> { std::thread::spawn(move || { if let Some(mut file) = file { let mut buf = vec![]; if let Err(err) = file.read_to_end(&mut buf) { log::error!("failed to read data in reader thread: {}", err); } buf } else { vec![] } }) } // convenience function to convert an error while checking for command not found error fn popen_to_tmc_err(cmd: String, err: PopenError) -> TmcError { if let PopenError::IoError(io) = &err { if let std::io::ErrorKind::NotFound = io.kind() { TmcError::Command(CommandError::NotFound { cmd, source: err }) } else { TmcError::Command(CommandError::FailedToRun(cmd, err)) } } else { TmcError::Command(CommandError::Popen(cmd, err)) } } #[derive(Debug)] pub struct Output { pub status: ExitStatus, pub stdout: Vec<u8>, pub stderr: Vec<u8>, } #[cfg(test)] mod test { use super::*; #[test] fn timeout() { let cmd = TmcCommand::piped("sleep").with(|e| e.arg("1")); assert!(matches!( cmd.output_with_timeout(Duration::from_nanos(1)), Err(TmcError::Command(CommandError::TimeOut { .. })) )); } #[test] fn not_found() { let cmd = TmcCommand::piped("nonexistent command"); assert!(matches!( cmd.output(), Err(TmcError::Command(CommandError::NotFound { .. })) )); } }
true
e79dc2cd6c0b6f1458a54d6da9d711de62aae0c9
Rust
yzhs/sokoban
/src/save/collection_state.rs
UTF-8
5,446
2.84375
3
[]
no_license
use std::fs::File; use std::path::Path; use crate::util::DATA_DIR; use super::level_state::*; use super::{SaveError, UpdateResponse}; #[derive(Debug, Serialize, Deserialize)] pub struct CollectionState { pub name: String, pub collection_solved: bool, #[serde(default)] pub levels_solved: u32, pub levels: Vec<LevelState>, } #[derive(Debug, Serialize, Deserialize)] pub struct StatsOnlyCollectionState { pub name: String, pub collection_solved: bool, #[serde(default)] pub levels_solved: u32, } impl CollectionState { /// Create a new `CollectionState` with no solved levels. pub fn new(name: &str) -> Self { CollectionState { name: name.to_string(), collection_solved: false, levels_solved: 0, levels: vec![], } } pub fn load_stats(name: &str) -> Self { Self::load_helper(name, true) } /// Try to load the `CollectionState` for the level set with the given name. If that fails, /// return a new empty `CollectionState`. pub fn load(name: &str) -> Self { Self::load_helper(name, false) } fn load_helper(name: &str, stats_only: bool) -> Self { let path = DATA_DIR.join(name); Self::load_cbor(&path, stats_only) .or_else(|| Self::load_json(&path, stats_only)) .unwrap_or_else(|| Self::new(name)) } fn from_stats(stats: StatsOnlyCollectionState) -> Self { Self { name: stats.name, collection_solved: stats.collection_solved, levels_solved: stats.levels_solved, levels: vec![], } } fn load_json(path: &Path, stats_only: bool) -> Option<Self> { let file = File::open(path.with_extension("json")).ok(); if stats_only { let stats: Option<StatsOnlyCollectionState> = file.and_then(|file| ::serde_json::from_reader(file).ok()); stats.map(Self::from_stats) } else { file.and_then(|file| ::serde_json::from_reader(file).ok()) } } fn load_cbor(path: &Path, stats_only: bool) -> Option<Self> { let file = File::open(path.with_extension("cbor")).ok()?; let result = if stats_only { let stats: StatsOnlyCollectionState = serde_cbor::from_reader(file).expect("Could not read cbor file"); Self::from_stats(stats) } else { serde_cbor::from_reader(file).expect("Could not read cbor file") }; Some(result) } /// Save the current state to disc. pub fn save(&mut self, name: &str) -> Result<(), SaveError> { self.levels_solved = self.levels_finished() as u32; self.save_cbor(name) } fn save_cbor(&self, name: &str) -> Result<(), SaveError> { let mut path = DATA_DIR.join(name); path.set_extension("cbor"); File::create(path) .map_err(SaveError::from) .and_then(|mut file| ::serde_cbor::to_writer(&mut file, &self).map_err(SaveError::from)) .map(|_| ()) } /// If a better or more complete solution for the current level is available, replace the old /// one with it. pub fn update(&mut self, index: usize, level_state: LevelState) -> UpdateResponse { if index >= self.levels.len() { self.levels.push(level_state); UpdateResponse::FirstTimeSolved } else { use self::LevelState::*; match self.levels[index].clone() { Started { .. } => { self.levels[index] = level_state; UpdateResponse::FirstTimeSolved } Finished { least_moves: ref lm_old, least_pushes: ref lp_old, } => { if let Finished { least_moves: ref lm, least_pushes: ref lp, .. } = level_state { self.levels[index] = Finished { least_moves: lm_old.min_moves(lm), least_pushes: lp_old.min_pushes(lp), }; let highscore_moves = lm_old.less_moves(lm); let highscore_pushes = lp_old.less_pushes(lp); UpdateResponse::Update { moves: highscore_moves, pushes: highscore_pushes, } } else { UpdateResponse::Update { moves: false, pushes: false, } } } } } } /// How many levels have been finished. pub fn levels_finished(&self) -> usize { let n = self.levels.len(); if n == 0 || !self.levels[0].is_finished() { 0 } else if self.levels[n - 1].is_finished() { n } else { n - 1 } } pub fn number_of_levels(&self) -> usize { self.levels.len() } pub fn number_of_solved_levels(&self) -> usize { if self.levels.is_empty() { self.levels_solved as usize } else { self.levels_finished() } } }
true
57455f64a992a0af36b45f41ea4e0984fb53a121
Rust
Embracethevoid/evjson
/src/evjson.rs
UTF-8
17,094
3.546875
4
[]
no_license
use std::collections::HashMap; // use std::ops::{Index, IndexMut}; #[derive(Debug, PartialEq)] pub enum Number { Integer(i64), Float(f64), } #[derive(Debug, PartialEq)] pub enum EVValue { Object(EVObject), Array(Vec<EVValue>), Str(String), Number(Number), Boolean(bool), Null, } // pub struct EVObject { // data:HashMap // } pub type EVObject = HashMap<String, Box<EVValue>>; pub fn new() -> EVObject { let data: HashMap<String, Box<EVValue>> = HashMap::new(); data } pub fn stringify(object: &EVObject, space: u8) -> String { stringify_object(object, space, 0) } fn stringify_object(object: &EVObject, space: u8, current_space: u8) -> String { let spaces: String = if space == 0 { String::from(" ".repeat(current_space as usize)) } else { format!("\n{}", " ".repeat((space + current_space) as usize)) }; let spaces_end: String = if space == 0 { String::from("") } else { format!("\n{}", " ".repeat(current_space as usize)) }; let space_between_items: String = if space == 0 { String::from(",") } else { format!(",\n{}", " ".repeat((current_space + space) as usize)) }; let mut pairs: Vec<String> = Vec::new(); for (key, value) in object { pairs.push(format!( "\"{}\" : {}", key, stringify_value(value, space, current_space + space) )); } return format!( "{{{}{}{}}}", spaces, pairs.join(&space_between_items), spaces_end ); } pub fn stringify_value(value: &EVValue, space: u8, current_space: u8) -> String { let spaces: String = if space == 0 { String::from(" ".repeat(current_space as usize)) } else { format!("\n{}", " ".repeat((space + current_space) as usize)) }; let spaces_end: String = if space == 0 { String::from("") } else { format!("\n{}", " ".repeat(current_space as usize)) }; match value { EVValue::Str(s) => format!("\"{}\"", s.as_str()), EVValue::Number(n) => match n { Number::Integer(i) => format!("{}", i), Number::Float(f) => format!("{}", f), }, EVValue::Array(a) => { let mut tmp = Vec::new(); for v in a { tmp.push(stringify_value(v, space, current_space + space)) } format!( "[{}{}{}]", spaces, tmp.join(&format!(",{}", spaces)), spaces_end ) } EVValue::Object(o) => stringify_object(o, space, current_space), EVValue::Boolean(b) => if *b { String::from("true") } else { String::from("false") }, EVValue::Null => String::from("null"), } } fn parse_key(index: usize, chars: &Vec<char>) -> Result<(usize, String), String> { let mut _index = index; loop { if _index < chars.len() { let c = chars[_index]; match c { ' ' | '\t' | '\n' => (), '\"' => { return parse_string(_index + 1, chars); } _ => { return Err(format!( "Invalid Syntax of charactor {},at position {}.", c, _index )) } } } else { return Err("invalid end of JSON".to_string()); } _index += 1; } } fn parse_array(index: usize, chars: &Vec<char>) -> Result<(usize, EVValue), String> { let mut _index = index; let mut _list: Vec<EVValue> = Vec::new(); loop { if _index < chars.len() { loop { if _index < chars.len() { let c = chars[_index]; match c { ' ' | '\n' | '\t' => _index += 1, ',' if !_list.is_empty() => break, ']' => return Ok((_index + 1, EVValue::Array(_list))), _ => { let (_ind, _value) = parse_value(_index, chars)?; _index = _ind; _list.push(_value); } } } else { return Err(String::from("Invalid End of JSON file")); } } } else { return Err(String::from("Invalid End of JSON file")); } _index += 1; } } fn parse_pair(index: usize, chars: &Vec<char>) -> Result<(usize, String, EVValue), String> { let mut _index = index; let (_ind, _key) = parse_key(index, chars)?; _index = _ind; loop { if _index < chars.len() { let c = chars[_index]; match c { ' ' | '\t' | '\n' => (), ':' => { _index += 1; break; } _ => { return Err(format!( "Invalid Syntax of charactor {},at position {}.", c, _index )) } } } else { return Err("Invalid end of JSON".to_string()); } _index += 1; } let (_ind, _value) = parse_value(_index, chars)?; return Ok((_ind, _key, _value)); } fn parse_object(index: usize, chars: &Vec<char>) -> Result<(usize, EVObject), String> { let mut object = new(); let mut _index = index; loop { if _index < chars.len() { loop { if _index < chars.len() { let c = chars[_index]; match c { ' ' | '\t' | '\n' => _index += 1, ',' if !object.is_empty() => { break; } '}' => { return Ok((_index + 1, object)); } _ => { let (_ind, _key, _value) = parse_pair(_index, chars)?; object.insert(_key, Box::new(_value)); _index = _ind; } } } else { return Err("Invalid end".to_string()); } } } else { return Err(String::from("Invalid JSON Ending")); } _index += 1; } } fn parse_number(_index: usize, chars: &Vec<char>) -> Result<(usize, EVValue), String> { let mut index = _index; let mut dot = false; let mut num = String::from(""); loop { if index < chars.len() { let c = chars[index]; match c { '0'...'9' | '-' => { num.push(c); } '.' if !dot => { num.push(c); dot = true; } _ => { if dot { match num.parse::<f64>() { Ok(_f) => return Ok((index, EVValue::Number(Number::Float(_f)))), _ => return Err("failed to parse number".to_string()), } } else { match num.parse::<i64>() { Ok(_i) => return Ok((index, EVValue::Number(Number::Integer(_i)))), _ => return Err("failed to parse number".to_string()), } } } } } else { if dot { match num.parse::<f64>() { Ok(_f) => return Ok((index, EVValue::Number(Number::Float(_f)))), _ => return Err("failed to parse number".to_string()), } } else { match num.parse::<i64>() { Ok(_i) => return Ok((index, EVValue::Number(Number::Integer(_i)))), _ => return Err("failed to parse number".to_string()), } } } index += 1; } } fn parse_boolean(index: usize, chars: &Vec<char>) -> Result<(usize, EVValue), String> { let mut _index = index; let c = chars[_index]; match c { 't' => { if index + 4 <= chars.len() && chars[index..index + 4] == ['t', 'r', 'u', 'e'] { return Ok((index + 4, EVValue::Boolean(true))); } else { return Err(format!( "Invalid Syntax of charactor {},at position {}.", c, _index )); } } 'f' => { if index + 5 <= chars.len() && chars[index..index + 5] == ['f', 'a', 'l', 's', 'e'] { return Ok((index + 5, EVValue::Boolean(false))); } else { return Err(format!( "Invalid Syntax of charactor {},at position {}.", c, _index )); } } _ => { return Err(format!( "Invalid Syntax of charactor {},at position {}.", c, _index )); } } } fn parse_null(index: usize, chars: &Vec<char>) -> Result<(usize, EVValue), String> { if index + 4 <= chars.len() && chars[index..index + 4] == ['n', 'u', 'l', 'l'] { return Ok((index + 4, EVValue::Null)); } else { return Err(format!( "Invalid Syntax of charactor {},at position {}.", chars[index], index )); } } fn parse_value(index: usize, chars: &Vec<char>) -> Result<(usize, EVValue), String> { let mut _index: usize = index; loop { if _index < chars.len() { let c = chars[_index]; match c { ' ' | '\t' | '\n' => (), '\"' => { let (_ind, _str) = parse_string(_index + 1, chars)?; return Ok((_ind, EVValue::Str(_str))); } '[' => return parse_array(_index + 1, chars), //parseArray(chars), '{' => { let (_ind, _object) = parse_object(_index + 1, chars)?; return Ok((_ind, EVValue::Object(_object))); } //parse_object 't' | 'f' => return parse_boolean(_index, chars), 'n' => return parse_null(_index, chars), //parse bool and null '0'...'9' | '-' => { let (_ind, _num) = parse_number(_index, chars)?; return Ok((_ind, _num)); } _ => { return Err(format!( "Invalid Syntax of charactor {},at position {}.", c, _index )); } } } else { return Err("".to_string()); } _index += 1; } } fn parse_string(index: usize, chars: &Vec<char>) -> Result<(usize, String), String> { let mut s = String::from(""); let mut _index = index; loop { if _index < chars.len() { let c = chars[_index]; match c { '\"' => return Ok((_index + 1, s)), _ => s.push(c), } } else { break; } _index += 1; } return Err("Invalid JSON end".to_string()); } pub fn parse(_input: String) -> Result<EVValue, String> { let chars: Vec<char> = _input.chars().collect(); let mut result: Option<EVValue> = None; let mut _index: usize = 0; loop { if _index < chars.len() { let (_ind, _value) = parse_value(_index, &chars)?; if _ind >= chars.len() { return Ok(_value); } result = Some(_value); _index = _ind; let c = chars[_index]; match c { ' ' | '\t' | '\n' => _index += 1, _ => { return Err(format!( "Invalid Syntax of charactor {},at position {}.", c, _index )) } } } else { match result { Some(_v) => return Ok(_v), _ => return Err("failed to parse".to_string()), } } } } #[cfg(test)] mod tests { use super::*; /* parse string */ #[test] fn it_parses_string_from_begining() { assert_eq!( Ok((5 as usize, "fire".to_string())), parse_string(0, &vec!['f', 'i', 'r', 'e', '\"', '\"']) ) } #[test] fn it_returns_err_if_string_does_not_end() { assert_eq!( Err("Invalid JSON end".to_string()), parse_string(0, &vec!['f', 'i', 'r', 'e']) ) } /* parse number */ #[test] fn it_parses_a_float() { assert_eq!( Ok((3 as usize, EVValue::Number(Number::Float(1.2)))), parse_number(0, &vec!['1', '.', '2', ' ']) ) } #[test] fn it_parses_a_integer() { assert_eq!( Ok((2 as usize, EVValue::Number(Number::Integer(12)))), parse_number(0, &vec!['1', '2', ' ']) ) } #[test] fn it_parses_a_negative_float() { assert_eq!( Ok((4 as usize, EVValue::Number(Number::Float(-1.2)))), parse_number(0, &vec!['-', '1', '.', '2', ']']) ) } #[test] fn it_parses_a_negative_integer() { assert_eq!( Ok((3 as usize, EVValue::Number(Number::Integer(-12)))), parse_number(0, &vec!['-', '1', '2', ']']) ) } #[test] fn it_returns_an_err_if_only_have_negative_symbol() { assert_eq!( Err("failed to parse number".to_string()), parse_number(0, &vec!['-', ']']) ) } /* parse boolean */ #[test] fn it_parses_a_true() { assert_eq!( Ok((6 as usize, EVValue::Boolean(true))), parse_boolean(2, &vec![' ', ':', 't', 'r', 'u', 'e']) ) } #[test] fn it_parses_a_false() { assert_eq!( Ok((7 as usize, EVValue::Boolean(false))), parse_boolean(2, &vec![' ', ':', 'f', 'a', 'l', 's', 'e']) ) } #[test] fn it_returns_error_when_parsing_part_of_true() { assert_eq!( Err(format!( "Invalid Syntax of charactor {},at position {}.", 't', 2 )), parse_boolean(2, &vec![' ', ':', 't', 'r', 'u']) ) } #[test] fn it_returns_error_when_parsing_part_of_false() { assert_eq!( Err(format!( "Invalid Syntax of charactor {},at position {}.", 'f', 2 )), parse_boolean(2, &vec![' ', ':', 'f', 'r', 'u']) ) } /* parsing null */ #[test] fn it_parses_a_null() { assert_eq!( Ok((6 as usize, EVValue::Null)), parse_null(2, &vec![' ', ':', 'n', 'u', 'l', 'l']) ) } #[test] fn it_returns_error_when_parsing_part_of_null() { assert_eq!( Err(format!( "Invalid Syntax of charactor {},at position {}.", 'n', 2 )), parse_null(2, &vec![' ', ':', 'n']) ) } /* parsing array */ #[test] fn it_parses_an_empty_array() { assert_eq!( Ok((6 as usize, EVValue::Array(vec![]))), parse_array(2, &vec![' ', ' ', ' ', ' ', ' ', ']']) ) } #[test] fn it_parses_an_array_with_a_string() { assert_eq!( Ok(( 6 as usize, EVValue::Array(vec![EVValue::Str("a".to_string())]) )), parse_array(0, &vec![' ', '\"', 'a', '\"', ' ', ']']) ) } #[test] fn it_parses_an_array_with_two_strings() { assert_eq!( Ok(( 11 as usize, EVValue::Array(vec![ EVValue::Str("a".to_string()), EVValue::Str("a".to_string()) ]) )), parse_array( 0, &vec![' ', '\"', 'a', '\"', ',', ' ', '\"', 'a', '\"', ',', ']'] ) ) } /* parse key */ #[test] fn it_parses_a_key() { assert_eq!( Ok((4 as usize, "a".to_string())), parse_key(0, &vec![' ', '\"', 'a', '\"']) ) } #[test] fn it_returns_error_for_part_of_key() { assert_eq!( Err("Invalid JSON end".to_string()), parse_key(0, &vec![' ', '\"']) ) } #[test] fn it_returns_error_for_invalid_charactor() { assert_eq!( Err("Invalid Syntax of charactor a,at position 1.".to_string()), parse_key(0, &vec![' ', 'a']) ) } }
true
874c2afccf42a00760a3f626da83394df1111edd
Rust
k0nserv/advent-of-rust-2018
/src/day01.rs
UTF-8
1,396
3.59375
4
[ "MIT" ]
permissive
use std::collections::HashSet; fn parse<'a>(input: &'a str) -> impl Iterator<Item = i64> + 'a { input .split(|c: char| c == ',' || c.is_whitespace()) .map(|n| n.trim()) .filter(|n| n.len() > 1) .map(|number| number.parse::<i64>().expect("Expected only valid numbers")) } pub fn star_one(input: &str) -> i64 { parse(input).sum() } pub fn star_two(input: &str) -> i64 { let instructions = parse(input).collect::<Vec<_>>(); let mut seen_frequencies = HashSet::new(); seen_frequencies.insert(0); let mut current_value = 0; let mut idx = 0; loop { let instruction = instructions[idx % instructions.len()]; current_value += instruction; if !seen_frequencies.insert(current_value) { break current_value; } idx += 1; } } #[cfg(test)] mod tests { use super::{star_one, star_two}; #[test] fn test_star_one() { assert_eq!(star_one("+1, -2, +3, +1"), 3); assert_eq!(star_one("+1, +1, +1"), 3); assert_eq!(star_one("+1, +1, -2"), 0); assert_eq!(star_one("-1, -2, -3"), -6); } #[test] fn test_star_two() { assert_eq!(star_two("+1, -1"), 0); assert_eq!(star_two("+3, +3, +4, -2, -4"), 10); assert_eq!(star_two("-6, +3, +8, +5, -6"), 5); assert_eq!(star_two("+7, +7, -2, -7, -4"), 14); } }
true
49b203ce7d103f53b65496576f086a17b66dbbb1
Rust
adrianchitescu/aoc20-rs
/utils/src/lib.rs
UTF-8
368
2.75
3
[]
no_license
pub mod utils { use std::{env, fs}; use std::io::{Error, ErrorKind, Result}; pub fn get_file_input(arg_position : usize) -> Result<String> { if let Some(file_name) = env::args().nth(arg_position) { fs::read_to_string(file_name) } else { Err(Error::new(ErrorKind::InvalidInput, "Invalid file_name")) } } }
true
18005279a9b5e1438a4d1cbcf1409dc65f3198e5
Rust
vincenthz/tesserae
/examples/tesseraed/editor/swatch.rs
UTF-8
1,966
3.28125
3
[ "BSD-3-Clause" ]
permissive
use std::fs::File; use std::path::Path; use std::ops::{Index, IndexMut}; use std::io; use std::io::{Read,Cursor}; use sdl2::pixels::Color; use byteorder::{ReadBytesExt,WriteBytesExt}; const SWATCH_SIZE: usize = 256; pub struct Swatch { data: Vec<Color>, } impl Index<usize> for Swatch { type Output = Color; fn index(&self, index: usize) -> &Color { &self.data[index] } } impl IndexMut<usize> for Swatch { fn index_mut(&mut self, index: usize) -> &mut Color { &mut self.data[index] } } impl Swatch { fn new() -> Swatch { Swatch { data: Vec::new(), } } pub fn default() -> Swatch { let f = include_bytes!("../../../swatch"); Swatch::load_from(Cursor::new(&f[..])) } fn read_color<R:Read>(mut f : R) -> io::Result<Color> { let r = f.read_u8()?; let g = f.read_u8()?; let b = f.read_u8()?; let a = f.read_u8()?; Ok(Color::RGBA(r,g,b,a)) } pub fn load_from<R: Read>(mut input : R) -> Swatch { let mut ts = Swatch::new(); let mut c = 0; loop { match Swatch::read_color(&mut input) { Ok(u) => { if c >= SWATCH_SIZE { break } else { ts.data.push(u); c += 1} }, _ => break } } while c < SWATCH_SIZE { c += 1; ts.data.push(Color::RGBA(0,255,0,0)); } ts } pub fn load_file<P: AsRef<Path>>(path : P) -> io::Result<Swatch> { let f = File::open(path)?; Ok(Swatch::load_from(f)) } pub fn store<P: AsRef<Path>>(&self, path : P) -> io::Result<()> { let mut f = File::create(path)?; for i in &self.data { f.write_u8(i.r)?; f.write_u8(i.g)?; f.write_u8(i.b)?; f.write_u8(i.a)?; } Ok(()) } pub fn len(&self) -> usize { self.data.len() } }
true
1a0c9933321d3e625890861f4ce009193a0d4d21
Rust
r2gnl/xaynet
/rust/xaynet-analytics/src/sender.rs
UTF-8
904
2.765625
3
[ "Apache-2.0" ]
permissive
//! In this file `Sender` is just stubbed and will need to be implemented. use anyhow::{Error, Result}; use crate::data_combination::data_points::data_point::DataPoint; /// `Sender` receives a `Vec<DataPoint>` from the `DataCombiner`. /// /// It will need to call the exposed `calculate()` method on each `DataPoint` variant and compose the messages /// that will then need to reach the XayNet coordinator. /// /// These messages should contain not only the actual data that is the output of calling `calculate()` on the variant, /// but also some extra data so that the coordinator knows how to aggregate each `DataPoint` variant. /// This is in line with the research done on the “global spec” idea. pub struct Sender; impl Sender { pub fn send(&self, _data_points: Vec<DataPoint>) -> Result<(), Error> { // TODO: https://xainag.atlassian.net/browse/XN-1647 todo!() } }
true
02bf5781b978df01dbaa7af77f375c0db2c4ef99
Rust
GGist/bip-rs
/bip_handshake/src/message/complete.rs
UTF-8
1,599
3.046875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
use std::net::SocketAddr; use message::protocol::Protocol; use message::extensions::{Extensions}; use bip_util::bt::{InfoHash, PeerId}; /// Message containing completed handshaking information. pub struct CompleteMessage<S> { prot: Protocol, ext: Extensions, hash: InfoHash, pid: PeerId, addr: SocketAddr, sock: S } impl<S> CompleteMessage<S> { /// Create a new `CompleteMessage` over the given socket S. pub fn new(prot: Protocol, ext: Extensions, hash: InfoHash, pid: PeerId, addr: SocketAddr, sock: S) -> CompleteMessage<S> { CompleteMessage{ prot: prot, ext: ext, hash: hash, pid: pid, addr: addr, sock: sock } } /// Protocol that this peer is operating over. pub fn protocol(&self) -> &Protocol { &self.prot } /// Extensions that both you and the peer support. pub fn extensions(&self) -> &Extensions { &self.ext } /// Hash that the peer is interested in. pub fn hash(&self) -> &InfoHash { &self.hash } /// Id that the peer has given itself. pub fn peer_id(&self) -> &PeerId { &self.pid } /// Address the peer is connected to us on. pub fn address(&self) -> &SocketAddr { &self.addr } /// Socket of some type S, that we use to communicate with the peer. pub fn socket(&self) -> &S { &self.sock } /// Break the `CompleteMessage` into its parts. pub fn into_parts(self) -> (Protocol, Extensions, InfoHash, PeerId, SocketAddr, S) { (self.prot, self.ext, self.hash, self.pid, self.addr, self.sock) } }
true
05121797d3653bd4779d1553d457f338843fae00
Rust
alistair23/opentitan
/sw/host/rom_ext_image_tools/signer/image/src/image.rs
UTF-8
3,197
2.875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #![deny(warnings)] #![deny(unused)] #![deny(unsafe_code)] use crate::manifest; use thiserror::Error; #[derive(Error, Debug, PartialEq)] pub enum ImageError { #[error("Expected at most {len} bytes for offset {offset}, received {data_len}.")] FieldData { offset: usize, len: usize, data_len: usize, }, } /// A thin wrapper around a Vec to help with setting ROM_EXT manifest fields. #[derive(Debug)] pub struct Image { data: Vec<u8>, } impl Image { /// Sets the value of a ROM_EXT manifest field. pub fn set_manifest_field<I>( &mut self, field: &manifest::ManifestField, field_data: I, ) -> Result<(), ImageError> where I: IntoIterator<Item = u8>, I::IntoIter: ExactSizeIterator, { let field_data = field_data.into_iter(); if field_data.len() > field.size_bytes { Err(ImageError::FieldData { offset: field.offset, len: field.size_bytes, data_len: field_data.len(), }) } else { self.data.splice( field.offset..(field.offset + field_data.len()), field_data, ); Ok(()) } } /// Returns the signed bytes of the image. pub fn signed_bytes(&self) -> &[u8] { &self.data[manifest::ROM_EXT_SIGNED_AREA_START_OFFSET..] } } impl AsRef<[u8]> for Image { fn as_ref(&self) -> &[u8] { &self.data } } impl From<Vec<u8>> for Image { fn from(data: Vec<u8>) -> Self { Image { data } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_set_manifest_field() -> Result<(), ImageError> { let mut image = Image::from(vec![0; 1024]); let field = manifest::ROM_EXT_IMAGE_LENGTH; let val: [u8; 4] = [0xA5; 4]; image.set_manifest_field(&field, val.iter().cloned())?; assert_eq!( image.as_ref()[field.offset..field.offset + field.size_bytes], val ); Ok(()) } #[test] fn test_set_manifest_field_error() { let mut image = Image::from(vec![0; 1024]); let field = manifest::ROM_EXT_IMAGE_LENGTH; let val: [u8; 6] = [0xA5; 6]; assert_eq!( image.set_manifest_field(&field, val.iter().cloned()), Err(ImageError::FieldData { offset: field.offset, len: field.size_bytes, data_len: 6 }) ); } #[test] fn test_signed_bytes() -> Result<(), ImageError> { let mut image = Image::from(vec![0; 1024]); let field = manifest::ROM_EXT_IMAGE_SIGNATURE; let val: [u8; manifest::ROM_EXT_IMAGE_SIGNATURE.size_bytes] = [0xA5; manifest::ROM_EXT_IMAGE_SIGNATURE.size_bytes]; image.set_manifest_field(&field, val.iter().cloned())?; assert_eq!( image.as_ref()[field.offset..field.offset + field.size_bytes], val ); Ok(()) } }
true
16d16926164cfa954b7422b1fc4cd71837c17bbd
Rust
peppizza/songbird-yt-dlp
/src/driver/connection/error.rs
UTF-8
4,659
2.5625
3
[ "ISC" ]
permissive
//! Connection errors and convenience types. use crate::{ driver::tasks::{error::Recipient, message::*}, ws::Error as WsError, }; use flume::SendError; use serde_json::Error as JsonError; use std::{error::Error as StdError, fmt, io::Error as IoError}; #[cfg(not(feature = "tokio-02-marker"))] use tokio::time::error::Elapsed; #[cfg(feature = "tokio-02-marker")] use tokio_compat::time::Elapsed; use xsalsa20poly1305::aead::Error as CryptoError; /// Errors encountered while connecting to a Discord voice server over the driver. #[derive(Debug)] #[non_exhaustive] pub enum Error { /// The driver hung up an internal signaller, either due to another connection attempt /// or a crash. AttemptDiscarded, /// An error occurred during [en/de]cryption of voice packets or key generation. Crypto(CryptoError), /// Server did not return the expected crypto mode during negotiation. CryptoModeInvalid, /// Selected crypto mode was not offered by server. CryptoModeUnavailable, /// An indicator that an endpoint URL was invalid. EndpointUrl, /// Discord hello/ready handshake was violated. ExpectedHandshake, /// Discord failed to correctly respond to IP discovery. IllegalDiscoveryResponse, /// Could not parse Discord's view of our IP. IllegalIp, /// Miscellaneous I/O error. Io(IoError), /// JSON (de)serialization error. Json(JsonError), /// Failed to message other background tasks after connection establishment. InterconnectFailure(Recipient), /// Error communicating with gateway server over WebSocket. Ws(WsError), /// Connection attempt timed out. TimedOut, } impl From<CryptoError> for Error { fn from(e: CryptoError) -> Self { Error::Crypto(e) } } impl From<IoError> for Error { fn from(e: IoError) -> Error { Error::Io(e) } } impl From<JsonError> for Error { fn from(e: JsonError) -> Error { Error::Json(e) } } impl From<SendError<WsMessage>> for Error { fn from(_e: SendError<WsMessage>) -> Error { Error::InterconnectFailure(Recipient::AuxNetwork) } } impl From<SendError<EventMessage>> for Error { fn from(_e: SendError<EventMessage>) -> Error { Error::InterconnectFailure(Recipient::Event) } } impl From<SendError<MixerMessage>> for Error { fn from(_e: SendError<MixerMessage>) -> Error { Error::InterconnectFailure(Recipient::Mixer) } } impl From<WsError> for Error { fn from(e: WsError) -> Error { Error::Ws(e) } } impl From<Elapsed> for Error { fn from(_e: Elapsed) -> Error { Error::TimedOut } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "failed to connect to Discord RTP server: ")?; use Error::*; match self { AttemptDiscarded => write!(f, "connection attempt was aborted/discarded"), Crypto(e) => e.fmt(f), CryptoModeInvalid => write!(f, "server changed negotiated encryption mode"), CryptoModeUnavailable => write!(f, "server did not offer chosen encryption mode"), EndpointUrl => write!(f, "endpoint URL received from gateway was invalid"), ExpectedHandshake => write!(f, "voice initialisation protocol was violated"), IllegalDiscoveryResponse => write!(f, "IP discovery/NAT punching response was invalid"), IllegalIp => write!(f, "IP discovery/NAT punching response had bad IP value"), Io(e) => e.fmt(f), Json(e) => e.fmt(f), InterconnectFailure(e) => write!(f, "failed to contact other task ({:?})", e), Ws(e) => write!(f, "websocket issue ({:?}).", e), TimedOut => write!(f, "connection attempt timed out"), } } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { match self { Error::AttemptDiscarded => None, Error::Crypto(e) => e.source(), Error::CryptoModeInvalid => None, Error::CryptoModeUnavailable => None, Error::EndpointUrl => None, Error::ExpectedHandshake => None, Error::IllegalDiscoveryResponse => None, Error::IllegalIp => None, Error::Io(e) => e.source(), Error::Json(e) => e.source(), Error::InterconnectFailure(_) => None, Error::Ws(_) => None, Error::TimedOut => None, } } } /// Convenience type for Discord voice/driver connection error handling. pub type Result<T> = std::result::Result<T, Error>;
true
ca6ff933975412289f199226ae4df42d0f7f3d88
Rust
cibingeorge/rquickjs
/core/src/value/function/types.rs
UTF-8
9,333
3.359375
3
[ "MIT" ]
permissive
use crate::{AsFunction, Ctx, Function, IntoJs, ParallelSend, Result, Value}; use std::{ cell::RefCell, marker::PhantomData, ops::{Deref, DerefMut}, }; /// The wrapper for method functions /// /// The method-like functions is functions which get `this` as the first argument. This wrapper allows receive `this` directly as first argument and do not requires using [`This`] for that purpose. /// /// ``` /// # use rquickjs::{Runtime, Context, Result, Method, Function, This}; /// # let rt = Runtime::new().unwrap(); /// # let ctx = Context::full(&rt).unwrap(); /// # ctx.with(|ctx| -> Result<()> { /// # /// let func = Function::new(ctx, Method(|this: i32, factor: i32| { /// this * factor /// }))?; /// assert_eq!(func.call::<_, i32>((This(3), 2))?, 6); /// # /// # Ok(()) /// # }).unwrap(); /// ``` #[repr(transparent)] pub struct Method<F>(pub F); /// The wrapper for function to convert is into JS /// /// The Rust functions should be wrapped to convert it to JS using [`IntoJs`] trait. /// /// ``` /// # use rquickjs::{Runtime, Context, Result, Func}; /// # let rt = Runtime::new().unwrap(); /// # let ctx = Context::full(&rt).unwrap(); /// # ctx.with(|ctx| -> Result<()> { /// # /// // Anonymous function /// ctx.globals().set("sum", Func::from(|a: i32, b: i32| a + b))?; /// assert_eq!(ctx.eval::<i32, _>("sum(3, 2)")?, 5); /// assert_eq!(ctx.eval::<usize, _>("sum.length")?, 2); /// assert!(ctx.eval::<Option<String>, _>("sum.name")?.is_none()); /// /// // Named function /// ctx.globals().set("prod", Func::new("multiply", |a: i32, b: i32| a * b))?; /// assert_eq!(ctx.eval::<i32, _>("prod(3, 2)")?, 6); /// assert_eq!(ctx.eval::<usize, _>("prod.length")?, 2); /// assert_eq!(ctx.eval::<String, _>("prod.name")?, "multiply"); /// # /// # Ok(()) /// # }).unwrap(); /// ``` #[repr(transparent)] pub struct Func<F>(pub F); /// The wrapper for async functons /// /// This type wraps returned future into [`Promised`](crate::Promised) /// /// ``` /// # use rquickjs::{Runtime, Context, Result, Function, Async}; /// # let rt = Runtime::new().unwrap(); /// # let ctx = Context::full(&rt).unwrap(); /// # ctx.with(|ctx| -> Result<()> { /// # /// async fn my_func() {} /// let func = Function::new(ctx, Async(my_func)); /// # /// # Ok(()) /// # }).unwrap(); /// ``` #[cfg(feature = "futures")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))] #[repr(transparent)] pub struct Async<F>(pub F); /// The wrapper for mutable functions /// /// This wrapper is useful for closures which encloses mutable state. #[repr(transparent)] pub struct MutFn<F>(RefCell<F>); impl<F> From<F> for MutFn<F> { fn from(func: F) -> Self { Self(RefCell::new(func)) } } /// The wrapper for once functions /// /// This wrapper is useful for callbacks which can be invoked only once. #[repr(transparent)] pub struct OnceFn<F>(RefCell<Option<F>>); impl<F> From<F> for OnceFn<F> { fn from(func: F) -> Self { Self(RefCell::new(Some(func))) } } /// The wrapper to get `this` from input /// /// ``` /// # use rquickjs::{Runtime, Context, Result, This, Function}; /// # let rt = Runtime::new().unwrap(); /// # let ctx = Context::full(&rt).unwrap(); /// # ctx.with(|ctx| -> Result<()> { /// # /// // Get the `this` value via arguments /// let func = Function::new(ctx, |this: This<i32>, factor: i32| { /// this.into_inner() * factor /// })?; /// // Pass the `this` value to a function /// assert_eq!(func.call::<_, i32>((This(3), 2))?, 6); /// # /// # Ok(()) /// # }).unwrap(); /// ``` #[derive(Clone, Copy, Debug, Default)] #[repr(transparent)] pub struct This<T>(pub T); /// The wrapper to get optional argument from input /// /// The [`Option`] type cannot be used for that purpose because it implements [`FromJs`](crate::FromJs) trait and requires the argument which may be `undefined`. /// /// ``` /// # use rquickjs::{Runtime, Context, Result, Opt, Function}; /// # let rt = Runtime::new().unwrap(); /// # let ctx = Context::full(&rt).unwrap(); /// # ctx.with(|ctx| -> Result<()> { /// # /// let func = Function::new(ctx, |required: i32, optional: Opt<i32>| { /// required * optional.into_inner().unwrap_or(1) /// })?; /// assert_eq!(func.call::<_, i32>((3,))?, 3); /// assert_eq!(func.call::<_, i32>((3, 1))?, 3); /// assert_eq!(func.call::<_, i32>((3, 2))?, 6); /// # /// # Ok(()) /// # }).unwrap(); /// ``` #[derive(Clone, Copy, Debug, Default)] #[repr(transparent)] pub struct Opt<T>(pub Option<T>); /// The wrapper the rest arguments from input /// /// The [`Vec`] type cannot be used for that purpose because it implements [`FromJs`](crate::FromJs) and already used to convert JS arrays. /// /// ``` /// # use rquickjs::{Runtime, Context, Result, Rest, Function}; /// # let rt = Runtime::new().unwrap(); /// # let ctx = Context::full(&rt).unwrap(); /// # ctx.with(|ctx| -> Result<()> { /// # /// let func = Function::new(ctx, |required: i32, optional: Rest<i32>| { /// optional.into_inner().into_iter().fold(required, |prod, arg| prod * arg) /// })?; /// assert_eq!(func.call::<_, i32>((3,))?, 3); /// assert_eq!(func.call::<_, i32>((3, 2))?, 6); /// assert_eq!(func.call::<_, i32>((3, 2, 1))?, 6); /// assert_eq!(func.call::<_, i32>((3, 2, 1, 4))?, 24); /// # /// # Ok(()) /// # }).unwrap(); /// ``` #[derive(Clone, Default)] pub struct Rest<T>(pub Vec<T>); macro_rules! type_impls { ($($type:ident <$($params:ident),*>($($fields:tt)*): $($impls:ident)*;)*) => { $(type_impls!{@impls $type [$($params)*]($($fields)*) $($impls)*})* }; (@impls $type:ident[$($params:ident)*]($($fields:tt)*) $impl:ident $($impls:ident)*) => { type_impls!{@impl $impl($($fields)*) $type $($params)*} type_impls!{@impls $type[$($params)*]($($fields)*) $($impls)*} }; (@impls $type:ident[$($params:ident)*]($($fields:tt)*)) => {}; (@impl into_inner($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => { impl<$param $(, $params)*> $type<$param $(, $params)*> { pub fn into_inner(self) -> $field { self.0 } } }; (@impl Into($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => { impl<$param $(, $params)*> From<$type<$param $(, $params)*>> for $field { fn from(this: $type<$param $(, $params)*>) -> Self { this.0 } } }; (@impl From($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => { impl<$param $(, $params)*> From<$field> for $type<$param $(, $params)*> { fn from(value: $field) -> Self { Self(value $(, type_impls!(@def $fields))*) } } }; (@impl AsRef($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => { impl<$param $(, $params)*> AsRef<$field> for $type<$param $(, $params)*> { fn as_ref(&self) -> &$field { &self.0 } } }; (@impl AsMut($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => { impl<$param $(, $params)*> AsMut<$field> for $type<$param $(, $params)*> { fn as_mut(&mut self) -> &mut $field { &mut self.0 } } }; (@impl Deref($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => { impl<$param $(, $params)*> Deref for $type<$param $(, $params)*> { type Target = $field; fn deref(&self) -> &Self::Target { &self.0 } } }; (@impl DerefMut($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => { impl<$param $(, $params)*> DerefMut for $type<$param $(, $params)*> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } }; (@def $($t:tt)*) => { Default::default() }; } impl<F, A, R> From<F> for Func<(F, PhantomData<(A, R)>)> { fn from(func: F) -> Self { Self((func, PhantomData)) } } impl<'js, F, A, R> IntoJs<'js> for Func<(F, PhantomData<(A, R)>)> where F: AsFunction<'js, A, R> + ParallelSend + 'static, { fn into_js(self, ctx: Ctx<'js>) -> Result<Value<'js>> { let data = self.0; Function::new(ctx, data.0)?.into_js(ctx) } } impl<N, F, A, R> Func<(N, F, PhantomData<(A, R)>)> { pub fn new(name: N, func: F) -> Self { Self((name, func, PhantomData)) } } impl<'js, N, F, A, R> IntoJs<'js> for Func<(N, F, PhantomData<(A, R)>)> where N: AsRef<str>, F: AsFunction<'js, A, R> + ParallelSend + 'static, { fn into_js(self, ctx: Ctx<'js>) -> Result<Value<'js>> { let data = self.0; let func = Function::new(ctx, data.1)?; func.set_name(data.0)?; func.into_js(ctx) } } type_impls! { Func<F>(F): AsRef Deref; MutFn<F>(RefCell<F>): AsRef Deref; OnceFn<F>(RefCell<Option<F>>): AsRef Deref; Method<F>(F): AsRef Deref; This<T>(T): into_inner From AsRef AsMut Deref DerefMut; Opt<T>(Option<T>): into_inner Into From AsRef AsMut Deref DerefMut; Rest<T>(Vec<T>): into_inner Into From AsRef AsMut Deref DerefMut; } #[cfg(feature = "futures")] type_impls! { Async<F>(F): AsRef Deref; } impl<T> Rest<T> { pub fn new() -> Self { Self(Vec::new()) } }
true
a4c5be0552a64492437b0269ddc93fd192c06358
Rust
funn1est/leetcode-rust
/src/solutions/n2_add_two_numbers/mod.rs
UTF-8
1,998
3.296875
3
[]
no_license
#[allow(unused_imports)] use super::libs::linked_list::{vec_to_list_node, ListNode}; /// https://leetcode.com/problems/add-two-numbers/ /// /// https://leetcode-cn.com/problems/add-two-numbers/ pub struct Solution {} impl Solution { pub fn add_two_numbers( l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>, ) -> Option<Box<ListNode>> { let (mut l1, mut l2) = (l1, l2); let mut dummy = Some(Box::new(ListNode::new(-1))); let mut copy = &mut dummy; let mut carry = 0; while l1.is_some() || l2.is_some() { let v1 = if let Some(node) = l1 { l1 = node.next; node.val } else { 0 }; let v2 = if let Some(node) = l2 { l2 = node.next; node.val } else { 0 }; let mut sum = v1 + v2 + carry; carry = sum / 10; sum = sum % 10; copy.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum))); copy = &mut copy.as_mut().unwrap().next; } if carry != 0 { copy.as_mut().unwrap().next = Some(Box::new(ListNode::new(carry))); } dummy.unwrap().next } } #[cfg(test)] mod test { use super::*; #[test] fn test_add_two_numbers() { assert_eq!( Solution::add_two_numbers( vec_to_list_node(vec![2, 4, 3]), vec_to_list_node(vec![5, 6, 4]) ), vec_to_list_node(vec![7, 0, 8]) ); assert_eq!( Solution::add_two_numbers( vec_to_list_node(vec![2, 4, 6]), vec_to_list_node(vec![5, 5, 4]) ), vec_to_list_node(vec![7, 9, 0, 1]) ); assert_eq!( Solution::add_two_numbers(vec_to_list_node(vec![1, 8]), vec_to_list_node(vec![0])), vec_to_list_node(vec![1, 8]) ); } }
true
daa43c27a0ea3f633b95116d15f0ed7b527b7602
Rust
MaulingMonkey/rust-reviews
/src/bin/diff.rs
UTF-8
1,906
2.765625
3
[]
no_license
use std::process::{Command, exit}; use std::path::PathBuf; fn main() { let mut args = std::env::args(); let _exe = args.next(); let krate = args.next().unwrap_or_else(|| { eprintln!("Usage: cargo diff [crate] [version]"); exit(1); }); let vers = args.next().unwrap_or_else(|| { eprintln!("Usage: cargo diff [crate] [version]"); exit(1); }); // NOTE: cargo seems to use some kind of semi-binary format now:~\.cargo\registry\index\github.com-1ecc6299db9ec823\.cache // crates_index OTOH uses the raw textual format... so it needs to update let index = crates_index::Index::new_cargo_default(); let krate = index.crate_(&krate).unwrap_or_else(|| { eprintln!("No such crate {:?}", krate); exit(1); }); let mut registry_src = PathBuf::from(index.path()); registry_src.pop(); // github.com-1ecc6299db9ec823 registry_src.pop(); // index registry_src.push("src"); registry_src.push("github.com-1ecc6299db9ec823"); let mut prev : Option<String> = None; for version in krate.versions().iter().filter(|v| !v.is_yanked()).map(|v| v.version().to_string()) { if version == vers { if let Some(prev) = prev { eprintln!("diffing {} => {}", prev, vers); let src = registry_src.join(format!("{}-{}", krate.name(), prev)); let dst = registry_src.join(format!("{}-{}", krate.name(), vers)); //Command::new("cargo").args(&["crev", "crate", "diff", "--src", &prev, "--dst", &vers, krate.name()]).status().unwrap(); Command::new("git").args(&["--no-pager", "-c", "core.autocrlf=false", "diff", "--ignore-cr-at-eol", "--no-index"]).arg(src).arg(dst).status().unwrap(); } else { eprintln!("{} has no previous version", vers); exit(1); } return; } prev = Some(version); } }
true
2c986073907bc61e9bc90de3dbdd11816601b3f6
Rust
allchain/s3-server
/src/ops/delete_object.rs
UTF-8
2,110
2.625
3
[ "MIT" ]
permissive
//! [`DeleteObject`](https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html) use crate::error::S3Result; use crate::output::{wrap_output, S3Output}; use crate::utils::{RequestExt, ResponseExt}; use crate::{BoxStdError, Request, Response}; use hyper::StatusCode; use serde::Deserialize; use crate::dto::{DeleteObjectError, DeleteObjectOutput, DeleteObjectRequest}; use crate::headers::names::{ X_AMZ_BYPASS_GOVERNANCE_RETENTION, X_AMZ_DELETE_MARKER, X_AMZ_MFA, X_AMZ_REQUEST_CHARGED, X_AMZ_REQUEST_PAYER, X_AMZ_VERSION_ID, }; #[derive(Debug, Deserialize)] /// `DeleteObject` request query struct Query { /// versionId #[serde(rename = "versionId")] version_id: Option<String>, } /// extract operation request pub fn extract(req: &Request, bucket: &str, key: &str) -> Result<DeleteObjectRequest, BoxStdError> { let mut input: DeleteObjectRequest = DeleteObjectRequest { bucket: bucket.into(), key: key.into(), ..DeleteObjectRequest::default() }; req.assign_from_optional_header( &*X_AMZ_BYPASS_GOVERNANCE_RETENTION, &mut input.bypass_governance_retention, )?; req.assign_from_optional_header(&*X_AMZ_MFA, &mut input.mfa)?; req.assign_from_optional_header(&*X_AMZ_REQUEST_PAYER, &mut input.request_payer)?; if let Some(query) = req.extract_query::<Query>()? { input.version_id = query.version_id; } Ok(input) } impl S3Output for DeleteObjectOutput { fn try_into_response(self) -> S3Result<Response> { wrap_output(|res| { res.set_status(StatusCode::NO_CONTENT); res.set_optional_header( || X_AMZ_DELETE_MARKER.clone(), self.delete_marker.map(|b| b.to_string()), )?; res.set_optional_header(|| X_AMZ_VERSION_ID.clone(), self.version_id)?; res.set_optional_header(|| X_AMZ_REQUEST_CHARGED.clone(), self.request_charged)?; Ok(()) }) } } impl S3Output for DeleteObjectError { fn try_into_response(self) -> S3Result<Response> { match self {} } }
true
a6cb1333bf7bfb00e97e0634d5fbcc3a6481a408
Rust
gobanos/cargo-aoc
/cargo-aoc/src/app.rs
UTF-8
17,563
2.875
3
[ "MIT", "Apache-2.0" ]
permissive
use aoc_runner_internal::Day; use aoc_runner_internal::Part; use clap::ArgMatches; use credentials::CredentialsManager; use date::AOCDate; use project::ProjectManager; use reqwest::header::{COOKIE, USER_AGENT}; use reqwest::blocking::Client; use reqwest::StatusCode; use std::error; use std::fs; use std::fs::File; use std::io::Write; use std::path::Path; use std::process; const CARGO_AOC_USER_AGENT: &str = "github.com/gobanos/cargo-aoc by gregory.obanos@gmail.com"; pub struct AOCApp {} impl AOCApp { /// Creates a new instance of the application pub fn new() -> Self { AOCApp {} } /// Executes the "credientals" subcommand of the app pub fn execute_credentials(&self, sub_args: &ArgMatches) { let mut creds_manager = CredentialsManager::new(); if let Some(new_session) = sub_args.value_of("set") { // Tries to set the session token match creds_manager.set_session_token(new_session.into()) { Ok(()) => println!("Credentials sucessfully changed!"), Err(e) => println!("Error changing credentials: {}", e), } } // Displays the stored session token match creds_manager.get_session_token() { Ok(cred) => println!("Current credentials: {}", cred), Err(e) => println!("Error: {}", e), } } /// Executes the "input" subcommand of the app pub fn execute_input(&self, sub_args: &ArgMatches) { // Gets the token or exit if it's not referenced. let token = CredentialsManager::new().get_session_token().expect( "Error: you need to setup your AOC token using \"cargo aoc credentials -s {token}\"", ); // Creates the AOCDate struct from the arguments (defaults to today...) let date: AOCDate = AOCDate::new(sub_args); println!( "Requesting input for year {}, day {} ...", date.year, date.day ); // Creates an HTTP Client let client = Client::new(); // Cookie formatting ... let formated_token = format!("session={}", token); // Sends the query to the right URL, with the user token let res = client .get(&date.request_url()) .header(USER_AGENT, CARGO_AOC_USER_AGENT) .header(COOKIE, formated_token) .send(); // Depending on the StatusCode of the request, we'll write errors or try to write // the result of the HTTP Request to a file match res { Ok(response) => match response.status() { StatusCode::OK => { let filename = date.filename(); let dir = date.directory(); // Creates the file-tree to store inputs // TODO: Maybe use crate's infos to get its root in the filesystem ? fs::create_dir_all(&dir).unwrap_or_else(|_| panic!("Could not create input directory: {}", dir)); // Gets the body from the response and outputs everything to a file let body = response.text().expect("Could not read content from input"); let mut file = File::create(&filename).unwrap_or_else(|_| panic!("Could not create file {}", filename)); file.write_all(body.as_bytes()).unwrap_or_else(|_| panic!("Could not write to {}", filename)); } sc => println!( "Could not find corresponding input. Are the day, year, and token correctly set ? Status: {}\ Message: {}", sc, response.text().unwrap_or_else(|_| String::new()) ), }, Err(e) => println!("Failed to get a response: {}", e), } } fn download_input(&self, day: Day, year: u32) -> Result<(), Box<dyn error::Error>> { let date = AOCDate { day: u32::from(day.0), year: year as i32, }; let filename = date.filename(); let filename = Path::new(&filename); if filename.exists() { return Ok(()); } let token = CredentialsManager::new().get_session_token()?; // Creates an HTTP Client let client = Client::new(); // Cookie formatting ... let formated_token = format!("session={}", token); let response = client .get(&date.request_url()) .header(USER_AGENT, CARGO_AOC_USER_AGENT) .header(COOKIE, formated_token) .send()?; match response.status() { StatusCode::OK => { let dir = date.directory(); // Creates the file-tree to store inputs // TODO: Maybe use crate's infos to get its root in the filesystem ? fs::create_dir_all(&dir)?; // Gets the body from the response and outputs everything to a file let body = response.text()?; let mut file = File::create(&filename)?; file.write_all(body.as_bytes())?; } sc => return Err(format!( "Could not find corresponding input. Are the day, year, and token correctly set ? Status: {}\ Message: {}", sc, response.text().unwrap_or_else(|_| String::new()) ).into()), } Ok(()) } pub fn execute_default(&self, args: &ArgMatches) -> Result<(), Box<dyn error::Error>> { let day: Option<Day> = args .value_of("day") .map(|d| d.parse().expect("Failed to parse day")); let part: Option<Part> = args .value_of("part") .map(|p| p.parse().expect("Failed to parse part")); let pm = ProjectManager::new()?; let day_parts = pm.build_project()?; let day = day.unwrap_or_else(|| day_parts.last().expect("No implementation found").day); let year = day_parts.year; let cargo_content = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/Cargo-run.toml.tpl" )) .replace("{CRATE_NAME}", &pm.name) .replace( "{PROFILE}", if args.is_present("profile") { "[profile.release]\ndebug = true" } else { "" }, ); let template = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/src/runner.rs.tpl" )); let mut body = String::new(); for dp in day_parts.iter().filter(|dp| dp.day == day).filter(|dp| { if let Some(p) = part { dp.part == p } else { true } }) { let (name, display) = if let Some(n) = &dp.name { ( format!("day{}_part{}_{}", dp.day.0, dp.part.0, n.to_lowercase()), format!("Day {} - Part {} - {}", dp.day.0, dp.part.0, n), ) } else { ( format!("day{}_part{}", dp.day.0, dp.part.0), format!("Day {} - Part {}", dp.day.0, dp.part.0), ) }; body += &template .replace("{DAY}", &day.0.to_string()) .replace("{RUNNER_NAME}", &name) .replace("{RUNNER_DISPLAY}", &display); } if body.is_empty() { return Err("No matching day & part found".into()); } self.download_input(day, year)?; let main_content = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/src/main.rs.tpl" )) .replace("{CRATE_SLUG}", &pm.slug) .replace("{YEAR}", &day_parts.year.to_string()) .replace( "{INPUT}", &template_input(day, year, args.value_of("input")), ) .replace("{BODY}", &body); fs::create_dir_all("target/aoc/aoc-autobuild/src") .expect("failed to create autobuild directory"); fs::write("target/aoc/aoc-autobuild/Cargo.toml", &cargo_content) .expect("failed to write Cargo.toml"); fs::write("target/aoc/aoc-autobuild/src/main.rs", &main_content) .expect("failed to write src/main.rs"); let status = process::Command::new("cargo") .args(&["run", "--release"]) .current_dir("target/aoc/aoc-autobuild") .spawn() .expect("Failed to run cargo") .wait() .expect("Failed to wait for cargo"); if !status.success() { process::exit(status.code().unwrap_or(-1)); } Ok(()) } pub fn execute_bench(&self, args: &ArgMatches) -> Result<(), Box<dyn error::Error>> { let day: Option<Day> = args .value_of("day") .map(|d| d.parse().expect("Failed to parse day")); let part: Option<Part> = args .value_of("part") .map(|p| p.parse().expect("Failed to parse part")); let pm = ProjectManager::new()?; let day_parts = pm.build_project()?; let day = day.unwrap_or_else(|| day_parts.last().expect("No implementation found").day); let year = day_parts.year; let cargo_content = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/Cargo-bench.toml.tpl" )) .replace("{CRATE_NAME}", &pm.name) .replace( "{PROFILE}", if args.is_present("profile") { "[profile.release]\ndebug = true" } else { "" }, ); let bench_tpl = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/benches/aoc_benchmark.rs.tpl" )); let part_tpl = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/benches/part.rs.tpl" )); let gen_tpl = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/benches/gen.rs.tpl" )); let impl_tpl = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/benches/impl.rs.tpl" )); let gen_impl_tpl = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/benches/gen_impl.rs.tpl" )); let matching_parts = day_parts.iter().filter(|dp| dp.day == day).filter(|dp| { if let Some(p) = part { dp.part == p } else { true } }); let mut parts: Vec<_> = matching_parts.clone().map(|dp| dp.part).collect(); parts.sort(); parts.dedup(); let body: String = parts .into_iter() .map(|p| { let part_name = format!("day{}_part{}", day.0, p.0); part_tpl .replace("{PART_NAME}", &part_name) .replace("{DAY}", &day.0.to_string()) .replace("{PART}", &p.0.to_string()) .replace( "{IMPLS}", &matching_parts .clone() .filter(|dp| dp.part == p) .map(|dp| { impl_tpl .replace( "{RUNNER_NAME}", &if let Some(n) = &dp.name { format!( "day{}_part{}_{}", dp.day.0, dp.part.0, n.to_lowercase() ) } else { format!("day{}_part{}", dp.day.0, dp.part.0) }, ) .replace("{DAY}", &dp.day.0.to_string()) .replace( "{NAME}", if let Some(n) = &dp.name { &n } else { "(default)" }, ) .replace("{PART_NAME}", &part_name) }) .collect::<String>(), ) }) .collect(); if body.is_empty() { return Err("No matching day & part found".into()); } let gens = if args.is_present("generator") { let mut parts: Vec<_> = matching_parts.clone().map(|dp| dp.part).collect(); parts.sort(); parts.dedup(); parts .into_iter() .map(|p| { let gen_name = format!("day{}", day.0); gen_tpl .replace("{GEN_NAME}", &gen_name) .replace("{DAY}", &day.0.to_string()) .replace( "{IMPLS}", &matching_parts .clone() .filter(|dp| dp.part == p) .map(|dp| { gen_impl_tpl .replace( "{RUNNER_NAME}", &if let Some(n) = &dp.name { format!( "day{}_part{}_{}", dp.day.0, dp.part.0, n.to_lowercase() ) } else { format!("day{}_part{}", dp.day.0, dp.part.0) }, ) .replace("{DAY}", &dp.day.0.to_string()) .replace( "{NAME}", if let Some(n) = &dp.name { &n } else { "(default)" }, ) .replace("{GEN_NAME}", &gen_name) }) .collect::<String>(), ) }) .collect() } else { String::new() }; self.download_input(day, year)?; let main_content = bench_tpl .replace("{CRATE_SLUG}", &pm.slug) .replace("{PARTS}", &body) .replace("{GENS}", &gens) .replace( "{BENCHMARKS}", if args.is_present("generator") { "aoc_benchmark, input_benchmark" } else { "aoc_benchmark" }, ) .replace( "{INPUTS}", &template_input(day, year, args.value_of("input")), ); fs::create_dir_all("target/aoc/aoc-autobench/benches") .expect("failed to create autobench directory"); fs::write("target/aoc/aoc-autobench/Cargo.toml", &cargo_content) .expect("failed to write Cargo.toml"); fs::write( "target/aoc/aoc-autobench/benches/aoc_benchmark.rs", &main_content, ) .expect("failed to write src/aoc_benchmark.rs"); let status = process::Command::new("cargo") .args(&["bench"]) .current_dir("target/aoc/aoc-autobench") .spawn() .expect("Failed to run cargo") .wait() .expect("Failed to wait for cargo"); if !status.success() { process::exit(status.code().unwrap_or(-1)); } if args.is_present("open") { let index = "target/aoc/aoc-autobench/target/criterion/report/index.html"; if !Path::new(index).exists() { return Err("Report is missing, perhaps gnuplot is missing ?".into()); } webbrowser::open(index)?; } Ok(()) } } fn template_input(day: Day, year: u32, input: Option<&str>) -> String { let day = day.0.to_string(); let path = input .map(|p| { if Path::new(p).is_relative() { format!("../../../../{}", p) } else { p.to_string() } }) .unwrap_or_else(|| format!("../../../../input/{}/day{}.txt", year, &day)); include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/template/input.rs.tpl" )) .replace("{PATH}", &path) .replace("{DAY}", &day) }
true
b943b29a09475e8399b64acfbc8b95c553b70ad5
Rust
ericrallen/advent-of-code
/2022/advent/src/days/day_three.rs
UTF-8
2,864
3.015625
3
[ "MIT" ]
permissive
use crate::PART_TWO_INDICATOR; static EMPTY_STR: &str = ""; static CHARACTERS: &'static str = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; static ELVES_IN_GROUP: usize = 3; fn check_duplicates<'a>(item: char, pocket: &str) -> Vec<&str> { let test: Vec<&str> = pocket.matches(item).collect(); return test; } fn find_duplicates<'a>(pocket_one: &'a str, pocket_two: &'a str) -> Vec<&'a str> { let mut duplicate_items: Vec<&str> = pocket_one.chars().map(|x| check_duplicates(x, pocket_two)).flatten().filter(|&x| x != EMPTY_STR).collect(); duplicate_items.dedup(); log!("{:?}", duplicate_items); return duplicate_items; } fn convert_to_priority(item: char) -> i32 { let priority_value = CHARACTERS.find(item).unwrap_or(0) as i32; log!("ITEM: {}", priority_value); return priority_value; } fn find_group_badge<'a>(groups: &&[&'a str]) -> char { let group_one = groups.get(0).unwrap_or(&EMPTY_STR); let group_two = groups.get(1).unwrap_or(&EMPTY_STR); let group_three = groups.get(2).unwrap_or(&EMPTY_STR); log!("{:?}, {:?}, {:?}", group_one, group_two, group_three); let mut group_id: Vec<_> = group_one.chars().filter(|x| group_two.matches(*x).collect::<Vec<&str>>().len() > 0 && group_three.matches(*x).collect::<Vec<&str>>().len() > 0).collect(); group_id.dedup(); log!("{:?}", group_id); let group_badge = group_id.get(0).unwrap_or(&CHARACTERS.chars().nth(0).unwrap()).to_owned(); log!("{:?}", group_badge); return group_badge; } fn part_one(input: String) -> String { let packs: Vec<&str> = input.split_whitespace().collect(); log!("{:?}", packs); let pockets: Vec<(&str, &str)> = packs.iter().map(|x| x.split_at(x.len() / 2)).collect(); log!("{:?}", pockets); let duplicates: Vec<&str> = pockets.iter().map(|(x, y)| find_duplicates(&x, &y)).flatten().collect(); log!("{:?}", duplicates); let priorities: Vec<i32> = duplicates.join("").chars().map(|x| convert_to_priority(x)).collect(); log!("{:?}", priorities); let total_priority: i32 = priorities.iter().sum(); log!("{:?}", total_priority); return format!("{}", total_priority); } fn part_two(input: String) -> String { let packs: Vec<&str> = input.split_whitespace().collect(); log!("{:?}", packs); let groups: Vec<&[&str]> = packs.chunks(ELVES_IN_GROUP).collect(); log!("{:?}", groups); let badges: Vec<char> = groups.iter().map(|x| find_group_badge(x)).collect(); log!("{:?}", badges); let priorities: Vec<i32> = badges.iter().map(|x| convert_to_priority(*x)).collect(); log!("{:?}", priorities); let total_priority: i32 = priorities.iter().sum(); log!("{:?}", total_priority); return format!("{}", total_priority); } pub fn main(input: String, part: &str) -> String { match part { PART_TWO_INDICATOR => return part_two(input), _ => return part_one(input) } }
true
1e560f504d20acba15e953d1074b486a91c24820
Rust
dylatos9230/WaGraphic
/src/programs/color_2d_gradient.rs
UTF-8
4,434
2.515625
3
[ "MIT" ]
permissive
use super::super::tools; use js_sys::WebAssembly; use wasm_bindgen::JsCast; use web_sys::WebGlRenderingContext as GL; use web_sys::*; pub struct Color2DGradient { program: WebGlProgram, index_count: i32, color_buffer: WebGlBuffer, rect_vertice_buffer: WebGlBuffer, u_opacity: WebGlUniformLocation, u_transform: WebGlUniformLocation, } impl Color2DGradient { pub fn new(gl: &WebGlRenderingContext) -> Self { let program = tools::link_program( &gl, super::super::shaders::vertex::color_2d_gradient::SHADER, super::super::shaders::fragment::varying_color_from_vertex::SHADER, ) .unwrap(); let vertices_rect: [f32; 8] = [0., 1., 0., 0., 1., 1., 1., 0.]; let indices_rect: [u16; 6] = [0, 1, 2, 2, 1, 3]; let memory_buffer = wasm_bindgen::memory() .dyn_into::<WebAssembly::Memory>() .unwrap() .buffer(); let vertices_location = vertices_rect.as_ptr() as u32 / 4; let vert_array = js_sys::Float32Array::new(&memory_buffer).subarray( vertices_location, vertices_location + vertices_rect.len() as u32, ); let buffer_rect = gl.create_buffer().ok_or("failed to create buffer").unwrap(); gl.bind_buffer(GL::ARRAY_BUFFER, Some(&buffer_rect)); gl.buffer_data_with_array_buffer_view(GL::ARRAY_BUFFER, &vert_array, GL::STATIC_DRAW); let indices_memory_buffer = wasm_bindgen::memory() .dyn_into::<WebAssembly::Memory>() .unwrap() .buffer(); let indices_location = indices_rect.as_ptr() as u32 / 2; let indices_array = js_sys::Uint16Array::new(&indices_memory_buffer).subarray( indices_location, indices_location + indices_rect.len() as u32, ); let buffer_indices = gl.create_buffer().unwrap(); gl.bind_buffer(GL::ELEMENT_ARRAY_BUFFER, Some(&buffer_indices)); gl.buffer_data_with_array_buffer_view( GL::ELEMENT_ARRAY_BUFFER, &indices_array, GL::STATIC_DRAW, ); Self { u_opacity: gl.get_uniform_location(&program, "uOpacity").unwrap(), u_transform: gl.get_uniform_location(&program, "uTransform").unwrap(), rect_vertice_buffer: buffer_rect, index_count: indices_array.length() as i32, color_buffer: gl.create_buffer().ok_or("failed to create buffer").unwrap(), program: program, } } pub fn render( &self, gl: &WebGlRenderingContext, bottom: f32, top: f32, left: f32, right: f32, canvas_height: f32, canvas_width: f32, ) { gl.use_program(Some(&self.program)); gl.bind_buffer(GL::ARRAY_BUFFER, Some(&self.rect_vertice_buffer)); gl.vertex_attrib_pointer_with_i32(0, 2, GL::FLOAT, false, 0, 0); gl.enable_vertex_attrib_array(0); gl.bind_buffer(GL::ARRAY_BUFFER, Some(&self.color_buffer)); gl.vertex_attrib_pointer_with_i32(1, 4, GL::FLOAT, false, 0, 0); gl.enable_vertex_attrib_array(1); let colors: [f32; 16] = [ 1., 0., 0., 1., 0., 1., 0., 1., 0., 0., 1., 1., 1., 1., 1., 1., ]; let colors_memory_buffer = wasm_bindgen::memory() .dyn_into::<WebAssembly::Memory>() .unwrap() .buffer(); let color_vals_location = colors.as_ptr() as u32 / 4; let color_vals_array = js_sys::Float32Array::new(&colors_memory_buffer).subarray(color_vals_location, color_vals_location + colors.len() as u32); gl.buffer_data_with_array_buffer_view(GL::ARRAY_BUFFER, &color_vals_array, GL::DYNAMIC_DRAW); gl.uniform1f(Some(&self.u_opacity), 1.); let translation_mat = tools::translation_matrix( 2. * left / canvas_width - 1., 2. * bottom / canvas_height - 1., 0., ); let scale_mat = tools::scaling_matrix( 2. * (right - left) / canvas_width, 2. * (top - bottom) / canvas_height, 0., ); let transform_mat = tools::mult_matrix_4(scale_mat, translation_mat); gl.uniform_matrix4fv_with_f32_array(Some(&self.u_transform), false, &transform_mat); gl.draw_elements_with_i32(GL::TRIANGLES, self.index_count, GL::UNSIGNED_SHORT, 0); } }
true
6845cc76ff9b5958a07a05ca72b0cc8d95da8342
Rust
lawrencecrane/adventofcode2020
/day10/src/lib.rs
UTF-8
2,923
3.328125
3
[]
no_license
use itertools::Itertools; use std::collections::HashMap; impl Adapters { // Adds the charging outlet and device's built-in adapter to data and sorts it pub fn new(mut data: Vec<usize>) -> Self { data.push(0); data.push(*data.iter().max().unwrap() + 3); data.sort(); Self { data } } pub fn count_jolt_differences(&self) -> [usize; 3] { count_jolt_differences(self) } pub fn n_arrangements(&self) -> usize { n_arrangements(self) } } fn n_arrangements(adapters: &Adapters) -> usize { let paths = adapters .data .iter() .cartesian_product(1..4) .map(|(adapter, diff)| (adapter, adapter + diff)) .filter(|(_, next)| adapters.data.contains(next)) .fold(HashMap::pathmap(), |mut paths, (adapter, next)| { let n_origin = *paths.get(adapter).unwrap_or(&0); *paths.entry(next).or_insert(0) += n_origin; paths }); *paths.get(adapters.data.last().unwrap()).unwrap_or(&0) } trait PathMap { fn pathmap() -> Self; } impl PathMap for HashMap<usize, usize> { fn pathmap() -> Self { let mut pathmap = HashMap::new(); pathmap.insert(0, 1); pathmap } } fn count_jolt_differences(adapters: &Adapters) -> [usize; 3] { let (_, counts) = adapters .data .iter() .skip(1) .fold((0, [0, 0, 0]), |(prev, mut counts), adapter| { counts[adapter - prev - 1] += 1; (*adapter, counts) }); counts } pub struct Adapters { data: Vec<usize>, } #[cfg(test)] mod tests { use super::Adapters; fn create_small_factory() -> Adapters { Adapters::new(vec![16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4]) } fn create_big_factory() -> Adapters { Adapters::new(vec![ 28, 33, 18, 42, 31, 14, 46, 20, 48, 47, 24, 23, 49, 45, 19, 38, 39, 11, 1, 32, 25, 35, 8, 17, 7, 9, 4, 2, 34, 10, 3, ]) } #[test] fn test_count_jolt_differences() { assert_eq!( super::count_jolt_differences(&create_small_factory()), [7, 0, 5] ); assert_eq!( super::count_jolt_differences(&create_big_factory()), [22, 0, 10] ); } #[test] fn test_n_arrangements() { assert_eq!(super::n_arrangements(&create_small_factory()), 8); assert_eq!(super::n_arrangements(&create_big_factory()), 19208); // [0, 2, 3, 6] and [0, 3, 6] assert_eq!(super::n_arrangements(&Adapters::new(vec![2, 3])), 2); // Can start with: [0, 2, 3, 4], [0, 3, 4], [0, 2 ,4] // Can end with: [7, 8, 9, 12], [7, 9, 12] // Combinations: 3 * 2 = 6 assert_eq!( super::n_arrangements(&Adapters::new(vec![2, 3, 4, 7, 8, 9])), 6 ); } }
true
2107cb1386cd62871a42e9e38fe95d5c414136d3
Rust
narcisobenigno/sars-plot
/src/row.rs
UTF-8
1,784
3.015625
3
[]
no_license
use serde::Deserialize; #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct Row { #[serde(rename = "data de publicação")] pub data_de_publicacao: String, #[serde(rename = "UF")] pub uf: String, #[serde(rename = "Unidade da Federação")] pub unidade_da_federacao: String, #[serde(rename = "Tipo")] pub tipo: String, #[serde(rename = "dado")] pub dado: String, #[serde(rename = "escala")] pub escala: String, #[serde(rename = "Ano epidemiológico")] pub ano_epidemiologico: String, #[serde(rename = "Semana epidemiológica")] pub semana_epidemiologica: String, #[serde(rename = "Situação do dado")] pub situacao_do_dado: String, #[serde(rename = "Casos semanais reportados até a última atualização")] pub casos_semanais_reportados_ate_a_ultima_atualizacao: String, #[serde(rename = "limite inferior da estimativa")] pub limite_inferior_da_estimativa: String, #[serde(rename = "casos estimados")] pub casos_estimados: String, #[serde(rename = "média móvel")] pub media_movel: String, #[serde(rename = "limite superior da estimativa")] pub limite_superior_da_estimativa: String, #[serde(rename = "Percentual em relação ao país")] pub percentual_em_relacao_ao_pais: String, #[serde(rename = "População")] pub populacao: String, #[serde(rename = "limiar pré-epidêmico")] pub limiar_pre_epidemico: String, #[serde(rename = "intensidade alta")] pub intensidade_alta: String, #[serde(rename = "intensidade muito alta")] pub intensidade_muito_alta: String, #[serde(rename = "nível semanal")] pub nivel_semanal: String, #[serde(rename = "nível por média móvel")] pub nivel_por_media_movel: String, }
true
ea9f16f547ffc01f0f6d36360bafaa744c83b45e
Rust
mgottschlag/rp2040-pac
/src/resets.rs
UTF-8
1,499
2.53125
3
[ "BSD-3-Clause" ]
permissive
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Reset control. If a bit is set it means the peripheral is in reset. 0 means the peripheral's reset is deasserted."] pub reset: crate::Reg<reset::RESET_SPEC>, #[doc = "0x04 - Watchdog select. If a bit is set then the watchdog will reset this peripheral when the watchdog fires."] pub wdsel: crate::Reg<wdsel::WDSEL_SPEC>, #[doc = "0x08 - Reset done. If a bit is set then a reset done signal has been returned by the peripheral. This indicates that the peripheral's registers are ready to be accessed."] pub reset_done: crate::Reg<reset_done::RESET_DONE_SPEC>, } #[doc = "RESET register accessor: an alias for `Reg<RESET_SPEC>`"] pub type RESET = crate::Reg<reset::RESET_SPEC>; #[doc = "Reset control. If a bit is set it means the peripheral is in reset. 0 means the peripheral's reset is deasserted."] pub mod reset; #[doc = "WDSEL register accessor: an alias for `Reg<WDSEL_SPEC>`"] pub type WDSEL = crate::Reg<wdsel::WDSEL_SPEC>; #[doc = "Watchdog select. If a bit is set then the watchdog will reset this peripheral when the watchdog fires."] pub mod wdsel; #[doc = "RESET_DONE register accessor: an alias for `Reg<RESET_DONE_SPEC>`"] pub type RESET_DONE = crate::Reg<reset_done::RESET_DONE_SPEC>; #[doc = "Reset done. If a bit is set then a reset done signal has been returned by the peripheral. This indicates that the peripheral's registers are ready to be accessed."] pub mod reset_done;
true
950df6696d8eec30477f0ebea31b9a5461ddec89
Rust
hisland/my-learn
/rust-programming-2/00-common-programming-concepts/04-const-can-not-use-runtime-value.rs
UTF-8
146
2.90625
3
[]
no_license
fn two() -> u32 { 3 + 2 } fn main() { const FOO: u32 = two(); // 不能使用运行时值作为 const 的值 print!("{:?}", FOO); }
true