text
stringlengths
8
4.13M
// Copyright 2019, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use crate::{envelope::Network, storage::DbConnectionUrl}; use std::time::Duration; /// The default maximum number of messages that can be stored using the Store-and-forward middleware pub const SAF_MSG_CACHE_STORAGE_CAPACITY: usize = 10_000; /// The default time-to-live duration used for storage of low priority messages by the Store-and-forward middleware pub const SAF_LOW_PRIORITY_MSG_STORAGE_TTL: Duration = Duration::from_secs(6 * 60 * 60); // 6 hours /// The default time-to-live duration used for storage of high priority messages by the Store-and-forward middleware pub const SAF_HIGH_PRIORITY_MSG_STORAGE_TTL: Duration = Duration::from_secs(3 * 24 * 60 * 60); // 3 days /// The default number of peer nodes that a message has to be closer to, to be considered a neighbour pub const DEFAULT_NUM_NEIGHBOURING_NODES: usize = 10; #[derive(Debug, Clone)] pub struct DhtConfig { /// The `DbConnectionUrl` for the Dht database. Default: In-memory database pub database_url: DbConnectionUrl, /// The size of the buffer (channel) which holds pending outbound message requests. /// Default: 20 pub outbound_buffer_size: usize, /// The maximum number of peer nodes that a message has to be closer to, to be considered a neighbour /// Default: 10 pub num_neighbouring_nodes: usize, /// A request to retrieve stored messages will be ignored if the requesting node is /// not within one of this nodes _n_ closest nodes. /// Default 8 pub saf_num_closest_nodes: usize, /// The maximum number of messages to return from a store and forward retrieval request. /// Default: 100 pub saf_max_returned_messages: usize, /// The maximum number of messages that can be stored using the Store-and-forward middleware. Default: 10_000 pub saf_msg_cache_storage_capacity: usize, /// The time-to-live duration used for storage of low priority messages by the Store-and-forward middleware. /// Default: 6 hours pub saf_low_priority_msg_storage_ttl: Duration, /// The time-to-live duration used for storage of high priority messages by the Store-and-forward middleware. /// Default: 3 days pub saf_high_priority_msg_storage_ttl: Duration, /// The limit on the message size to store in SAF storage in bytes. Default 500 KiB pub saf_max_message_size: usize, /// When true, store and forward messages are requested from peers on connect (Default: true) pub saf_auto_request: bool, /// The max capacity of the message hash cache /// Default: 10000 pub msg_hash_cache_capacity: usize, /// The time-to-live for items in the message hash cache /// Default: 300s (5 mins) pub msg_hash_cache_ttl: Duration, /// Sets the number of failed attempts in-a-row to tolerate before temporarily excluding this peer from broadcast /// messages. /// Default: 3 pub broadcast_cooldown_max_attempts: usize, /// Sets the period to wait before including this peer in broadcast messages after /// `broadcast_cooldown_max_attempts` failed attempts. This helps prevent thrashing the comms layer /// with connection attempts to a peer which is offline. /// Default: 30 minutes pub broadcast_cooldown_period: Duration, /// The duration to wait for a peer discovery to complete before giving up. /// Default: 2 minutes pub discovery_request_timeout: Duration, /// The active Network. Default: TestNet pub network: Network, } impl DhtConfig { pub fn default_testnet() -> Self { Default::default() } pub fn default_mainnet() -> Self { Self { network: Network::MainNet, ..Default::default() } } pub fn default_local_test() -> Self { Self { network: Network::LocalTest, database_url: DbConnectionUrl::Memory, saf_auto_request: false, ..Default::default() } } } impl Default for DhtConfig { fn default() -> Self { Self { num_neighbouring_nodes: DEFAULT_NUM_NEIGHBOURING_NODES, saf_num_closest_nodes: 10, saf_max_returned_messages: 50, outbound_buffer_size: 20, saf_msg_cache_storage_capacity: SAF_MSG_CACHE_STORAGE_CAPACITY, saf_low_priority_msg_storage_ttl: SAF_LOW_PRIORITY_MSG_STORAGE_TTL, saf_high_priority_msg_storage_ttl: SAF_HIGH_PRIORITY_MSG_STORAGE_TTL, saf_auto_request: true, saf_max_message_size: 512 * 1024, // 500 KiB msg_hash_cache_capacity: 10_000, msg_hash_cache_ttl: Duration::from_secs(5 * 60), broadcast_cooldown_max_attempts: 3, database_url: DbConnectionUrl::Memory, broadcast_cooldown_period: Duration::from_secs(60 * 30), discovery_request_timeout: Duration::from_secs(2 * 60), network: Network::TestNet, } } }
#[macro_use] extern crate slog; use hyper_tls::HttpsConnector; /// Short hand for our HTTPS enabled outbound HTTP client. type HttpClient = hyper::Client<HttpsConnector<hyper::client::HttpConnector>>; pub mod db; pub mod error; pub mod github; pub mod rest; pub mod settings;
use na::{Point4}; pub type Color = Point4<f32>; #[derive(Debug)] pub struct Material { ambient: Color, diffuse: Color, specular: Color, specular_power: f32, reflection: f32 } impl Material { pub fn new() -> Material { Material { ambient: Color::new(0.0, 0.0, 0.0, 0.0), diffuse: Color::new(0.0, 0.0, 0.0, 0.0), specular: Color::new(0.0, 0.0, 0.0, 0.0), specular_power: 0.0, reflection: 0.0 } } pub fn ambient<'a>(&'a mut self, ambient: Color) -> &'a mut Material { self.ambient = ambient; self } pub fn diffuse<'a>(&'a mut self, diffuse: Color) -> &'a mut Material { self.diffuse = diffuse; self } }
#![feature(test)] #![cfg_attr(test, deny(warnings))] extern crate futures; extern crate test; extern crate tokio_sync; type Medium = [usize; 64]; type Large = [Medium; 64]; mod tokio { use futures::{future, Async, Future, Sink, Stream}; use std::thread; use test::{self, Bencher}; use tokio_sync::mpsc::*; #[bench] fn bounded_new_medium(b: &mut Bencher) { b.iter(|| { let _ = test::black_box(&channel::<super::Medium>(1_000)); }) } #[bench] fn unbounded_new_medium(b: &mut Bencher) { b.iter(|| { let _ = test::black_box(&unbounded_channel::<super::Medium>()); }) } #[bench] fn bounded_new_large(b: &mut Bencher) { b.iter(|| { let _ = test::black_box(&channel::<super::Large>(1_000)); }) } #[bench] fn unbounded_new_large(b: &mut Bencher) { b.iter(|| { let _ = test::black_box(&unbounded_channel::<super::Large>()); }) } #[bench] fn send_one_message(b: &mut Bencher) { b.iter(|| { let (mut tx, mut rx) = channel(1_000); // Send tx.try_send(1).unwrap(); // Receive assert_eq!(Async::Ready(Some(1)), rx.poll().unwrap()); }) } #[bench] fn send_one_message_large(b: &mut Bencher) { b.iter(|| { let (mut tx, mut rx) = channel::<super::Large>(1_000); // Send let _ = tx.try_send([[0; 64]; 64]); // Receive let _ = test::black_box(&rx.poll()); }) } #[bench] fn bounded_rx_not_ready(b: &mut Bencher) { let (_tx, mut rx) = channel::<i32>(1_000); b.iter(|| { future::lazy(|| { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn bounded_tx_poll_ready(b: &mut Bencher) { let (mut tx, _rx) = channel::<i32>(1); b.iter(|| { future::lazy(|| { assert!(tx.poll_ready().unwrap().is_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn bounded_tx_poll_not_ready(b: &mut Bencher) { let (mut tx, _rx) = channel::<i32>(1); tx.try_send(1).unwrap(); b.iter(|| { future::lazy(|| { assert!(tx.poll_ready().unwrap().is_not_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn unbounded_rx_not_ready(b: &mut Bencher) { let (_tx, mut rx) = unbounded_channel::<i32>(); b.iter(|| { future::lazy(|| { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn unbounded_rx_not_ready_x5(b: &mut Bencher) { let (_tx, mut rx) = unbounded_channel::<i32>(); b.iter(|| { future::lazy(|| { assert!(rx.poll().unwrap().is_not_ready()); assert!(rx.poll().unwrap().is_not_ready()); assert!(rx.poll().unwrap().is_not_ready()); assert!(rx.poll().unwrap().is_not_ready()); assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn bounded_uncontended_1(b: &mut Bencher) { b.iter(|| { let (mut tx, mut rx) = channel(1_000); for i in 0..1000 { tx.try_send(i).unwrap(); // No need to create a task, because poll is not going to park. assert_eq!(Async::Ready(Some(i)), rx.poll().unwrap()); } }) } #[bench] fn bounded_uncontended_1_large(b: &mut Bencher) { b.iter(|| { let (mut tx, mut rx) = channel::<super::Large>(1_000); for i in 0..1000 { let _ = tx.try_send([[i; 64]; 64]); // No need to create a task, because poll is not going to park. let _ = test::black_box(&rx.poll()); } }) } #[bench] fn bounded_uncontended_2(b: &mut Bencher) { b.iter(|| { let (mut tx, mut rx) = channel(1000); for i in 0..1000 { tx.try_send(i).unwrap(); } for i in 0..1000 { // No need to create a task, because poll is not going to park. assert_eq!(Async::Ready(Some(i)), rx.poll().unwrap()); } }) } #[bench] fn contended_unbounded_tx(b: &mut Bencher) { let mut threads = vec![]; let mut txs = vec![]; for _ in 0..4 { let (tx, rx) = ::std::sync::mpsc::channel::<Sender<i32>>(); txs.push(tx); threads.push(thread::spawn(move || { for mut tx in rx.iter() { for i in 0..1_000 { tx.try_send(i).unwrap(); } } })); } b.iter(|| { // TODO make unbounded let (tx, rx) = channel::<i32>(1_000_000); for th in &txs { th.send(tx.clone()).unwrap(); } drop(tx); let rx = rx.wait().take(4 * 1_000); for v in rx { let _ = test::black_box(v); } }); drop(txs); for th in threads { th.join().unwrap(); } } #[bench] fn contended_bounded_tx(b: &mut Bencher) { const THREADS: usize = 4; const ITERS: usize = 100; let mut threads = vec![]; let mut txs = vec![]; for _ in 0..THREADS { let (tx, rx) = ::std::sync::mpsc::channel::<Sender<i32>>(); txs.push(tx); threads.push(thread::spawn(move || { for tx in rx.iter() { let mut tx = tx.wait(); for i in 0..ITERS { tx.send(i as i32).unwrap(); } } })); } b.iter(|| { let (tx, rx) = channel::<i32>(1); for th in &txs { th.send(tx.clone()).unwrap(); } drop(tx); let rx = rx.wait().take(THREADS * ITERS); for v in rx { let _ = test::black_box(v); } }); drop(txs); for th in threads { th.join().unwrap(); } } } mod legacy { use futures::sync::mpsc::*; use futures::{future, Async, Future, Sink, Stream}; use std::thread; use test::{self, Bencher}; #[bench] fn bounded_new_medium(b: &mut Bencher) { b.iter(|| { let _ = test::black_box(&channel::<super::Medium>(1_000)); }) } #[bench] fn unbounded_new_medium(b: &mut Bencher) { b.iter(|| { let _ = test::black_box(&unbounded::<super::Medium>()); }) } #[bench] fn bounded_new_large(b: &mut Bencher) { b.iter(|| { let _ = test::black_box(&channel::<super::Large>(1_000)); }) } #[bench] fn unbounded_new_large(b: &mut Bencher) { b.iter(|| { let _ = test::black_box(&unbounded::<super::Large>()); }) } #[bench] fn send_one_message(b: &mut Bencher) { b.iter(|| { let (mut tx, mut rx) = channel(1_000); // Send tx.try_send(1).unwrap(); // Receive assert_eq!(Ok(Async::Ready(Some(1))), rx.poll()); }) } #[bench] fn send_one_message_large(b: &mut Bencher) { b.iter(|| { let (mut tx, mut rx) = channel::<super::Large>(1_000); // Send let _ = tx.try_send([[0; 64]; 64]); // Receive let _ = test::black_box(&rx.poll()); }) } #[bench] fn bounded_rx_not_ready(b: &mut Bencher) { let (_tx, mut rx) = channel::<i32>(1_000); b.iter(|| { future::lazy(|| { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn bounded_tx_poll_ready(b: &mut Bencher) { let (mut tx, _rx) = channel::<i32>(0); b.iter(|| { future::lazy(|| { assert!(tx.poll_ready().unwrap().is_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn bounded_tx_poll_not_ready(b: &mut Bencher) { let (mut tx, _rx) = channel::<i32>(0); tx.try_send(1).unwrap(); b.iter(|| { future::lazy(|| { assert!(tx.poll_ready().unwrap().is_not_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn unbounded_rx_not_ready(b: &mut Bencher) { let (_tx, mut rx) = unbounded::<i32>(); b.iter(|| { future::lazy(|| { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn unbounded_rx_not_ready_x5(b: &mut Bencher) { let (_tx, mut rx) = unbounded::<i32>(); b.iter(|| { future::lazy(|| { assert!(rx.poll().unwrap().is_not_ready()); assert!(rx.poll().unwrap().is_not_ready()); assert!(rx.poll().unwrap().is_not_ready()); assert!(rx.poll().unwrap().is_not_ready()); assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) }) .wait() .unwrap(); }) } #[bench] fn unbounded_uncontended_1(b: &mut Bencher) { b.iter(|| { let (tx, mut rx) = unbounded(); for i in 0..1000 { UnboundedSender::unbounded_send(&tx, i).expect("send"); // No need to create a task, because poll is not going to park. assert_eq!(Ok(Async::Ready(Some(i))), rx.poll()); } }) } #[bench] fn unbounded_uncontended_1_large(b: &mut Bencher) { b.iter(|| { let (tx, mut rx) = unbounded::<super::Large>(); for i in 0..1000 { let _ = UnboundedSender::unbounded_send(&tx, [[i; 64]; 64]); // No need to create a task, because poll is not going to park. let _ = test::black_box(&rx.poll()); } }) } #[bench] fn unbounded_uncontended_2(b: &mut Bencher) { b.iter(|| { let (tx, mut rx) = unbounded(); for i in 0..1000 { UnboundedSender::unbounded_send(&tx, i).expect("send"); } for i in 0..1000 { // No need to create a task, because poll is not going to park. assert_eq!(Ok(Async::Ready(Some(i))), rx.poll()); } }) } #[bench] fn multi_thread_unbounded_tx(b: &mut Bencher) { let mut threads = vec![]; let mut txs = vec![]; for _ in 0..4 { let (tx, rx) = ::std::sync::mpsc::channel::<Sender<i32>>(); txs.push(tx); threads.push(thread::spawn(move || { for mut tx in rx.iter() { for i in 0..1_000 { tx.try_send(i).unwrap(); } } })); } b.iter(|| { let (tx, rx) = channel::<i32>(1_000_000); for th in &txs { th.send(tx.clone()).unwrap(); } drop(tx); let rx = rx.wait().take(4 * 1_000); for v in rx { let _ = test::black_box(v); } }); drop(txs); for th in threads { th.join().unwrap(); } } #[bench] fn contended_bounded_tx(b: &mut Bencher) { const THREADS: usize = 4; const ITERS: usize = 100; let mut threads = vec![]; let mut txs = vec![]; for _ in 0..THREADS { let (tx, rx) = ::std::sync::mpsc::channel::<Sender<i32>>(); txs.push(tx); threads.push(thread::spawn(move || { for tx in rx.iter() { let mut tx = tx.wait(); for i in 0..ITERS { tx.send(i as i32).unwrap(); } } })); } b.iter(|| { let (tx, rx) = channel::<i32>(1); for th in &txs { th.send(tx.clone()).unwrap(); } drop(tx); let rx = rx.wait().take(THREADS * ITERS); for v in rx { let _ = test::black_box(v); } }); drop(txs); for th in threads { th.join().unwrap(); } } }
use std::fs; use std::io; use std::io::prelude::*; use std::os::unix::fs::PermissionsExt; /// Encodes any byte stream with uuencoding. #[derive(Debug)] pub struct Encoder<T: Read> { /// File name, displayed in the output header. pub filename: String, /// Permissions mode, displayed in the output header; pub mode: u32, /// Input stream, which is being encoded. pub reader: T, } impl Encoder<io::Cursor<Vec<u8>>> { /// Constructs an `Encoder`, which reads data from the buffer. /// /// #Usage: /// /// ``` /// use uue::Encoder; /// /// let buf = Vec::new(); /// let enc = Encoder::from_bytes("vfile.txt".to_string(), 0o644, buf); /// ``` pub fn from_bytes(name: String, mode: u32, buf: Vec<u8>) -> Self { Encoder { filename: name, mode: mode, reader: io::Cursor::new(buf), } } } impl Encoder<fs::File> { /// Constructs an `Encoder` which reads data from `file`, which's name is assumed to be `name`. /// /// Permissions mode is extracted from file's metadata. /// /// # Usage: /// /// ``` /// use std::fs; /// # use std::io::Result; /// use uue::Encoder; /// /// # fn f () -> Result<()> { /// let filename = "input.txt".to_string(); /// let file = try!(fs::File::open(&filename)); /// let enc = Encoder::from_file(filename, file); /// # Ok(()) /// # } /// ``` pub fn from_file(name: String, file: fs::File) -> Self { Encoder { filename: name, mode: file.metadata().unwrap().permissions().mode(), reader: file, } } } impl<T: Read> Encoder<T> { /// Constructs an `Encoder` with given fields. pub fn new(name: String, mode: u32, read: T) -> Self { Encoder { filename: name, mode: mode, reader: read, } } /// Consumes the encoder to read, encode and write encoded data into `dst`. /// /// To encode the data into `Vec<u8>`, pass it as `&mut`: /// /// ``` /// use uue::Encoder; /// /// let input = &[1u8, 2u8, 3u8][..]; /// let mut output = Vec::<u8>::new(); /// /// let enc = Encoder::new("file.txt".to_string(), 0o644, input); /// enc.encode_to(&mut output); /// ``` pub fn encode_to<W: Write>(mut self, mut dst: W) -> io::Result<()> { try!(write!(dst, "begin {:o} {}\n", self.mode, self.filename)); loop { let mut buf = [0u8; 45]; let size = match try!(self.reader.read(&mut buf)) { 0 => break, s => s, }; try!(dst.write(&[(size + 32) as u8])); let padded_size = match size % 3 { 2 => size + 1, 1 => size + 2, _ => size, }; let line = &buf[..padded_size]; for chunk in line.chunks(3) { let mut split: [u8; 4] = split_3b_in_4(chunk); for i in 0..4 { split[i] += 32; } try!(dst.write(&split)); } try!(dst.write(b"\n")); } try!(dst.write(b"`\nend\n")); Ok(()) } } fn split_3b_in_4(bytes: &[u8]) -> [u8; 4] { assert!(bytes.len() >= 3); let mut total = ((bytes[0] as u32) << 16) + ((bytes[1] as u32) << 8) + (bytes[2] as u32); let mut out_bytes = [0; 4]; let mut split_next_6 = || { let old_total = total; total = total >> 6; (old_total & 0b111111) as u8 }; for i in (0..4).rev() { out_bytes[i] = split_next_6(); } out_bytes } #[cfg(test)] mod tests { use super::*; use std::str; #[test] fn encoding_cat() { let filename = "cat.txt".to_string(); let mode = 0o644; let input = Vec::from("Cat"); let mut output = Vec::new(); let enc = Encoder::from_bytes(filename, mode, input); enc.encode_to(&mut output).unwrap(); assert_eq!(str::from_utf8(&output).unwrap(), "begin 644 cat.txt\n#0V%T\n`\nend\n") } #[test] fn encoding_text() { let filename = "file.txt".to_string(); let mode = 0o444; let input = Vec::from("I feel very strongly about you doing duty. Would you give me a \ little more documentation about your reading in French? I am glad \ you are happy — but I never believe much in happiness. I never \ believe in misery either. Those are things you see on the stage \ or the screen or the printed pages, they never really happen to \ you in life.\n"); let mut output = Vec::new(); let aim = r#"begin 444 file.txt M22!F965L('9E<GD@<W1R;VYG;'D@86)O=70@>6]U(&1O:6YG(&1U='DN(%=O M=6QD('EO=2!G:79E(&UE(&$@;&ET=&QE(&UO<F4@9&]C=6UE;G1A=&EO;B!A M8F]U="!Y;W5R(')E861I;F<@:6X@1G)E;F-H/R!)(&%M(&=L860@>6]U(&%R M92!H87!P>2#B@)0@8G5T($D@;F5V97(@8F5L:65V92!M=6-H(&EN(&AA<'!I M;F5S<RX@22!N979E<B!B96QI979E(&EN(&UI<V5R>2!E:71H97(N(%1H;W-E M(&%R92!T:&EN9W,@>6]U('-E92!O;B!T:&4@<W1A9V4@;W(@=&AE('-C<F5E M;B!O<B!T:&4@<')I;G1E9"!P86=E<RP@=&AE>2!N979E<B!R96%L;'D@:&%P 4<&5N('1O('EO=2!I;B!L:69E+@H ` end "#; let enc = Encoder::from_bytes(filename, mode, input); enc.encode_to(&mut output).unwrap(); assert_eq!(str::from_utf8(&output).unwrap(), aim); } }
#[doc = "Reader of register CR2"] pub type R = crate::R<u32, super::CR2>; #[doc = "Writer for register CR2"] pub type W = crate::W<u32, super::CR2>; #[doc = "Register CR2 `reset()`'s with value 0"] impl crate::ResetValue for super::CR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Rx buffer DMA enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXDMAEN_A { #[doc = "0: Rx buffer DMA disabled"] DISABLED = 0, #[doc = "1: Rx buffer DMA enabled"] ENABLED = 1, } impl From<RXDMAEN_A> for bool { #[inline(always)] fn from(variant: RXDMAEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RXDMAEN`"] pub type RXDMAEN_R = crate::R<bool, RXDMAEN_A>; impl RXDMAEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RXDMAEN_A { match self.bits { false => RXDMAEN_A::DISABLED, true => RXDMAEN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == RXDMAEN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == RXDMAEN_A::ENABLED } } #[doc = "Write proxy for field `RXDMAEN`"] pub struct RXDMAEN_W<'a> { w: &'a mut W, } impl<'a> RXDMAEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RXDMAEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Rx buffer DMA disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(RXDMAEN_A::DISABLED) } #[doc = "Rx buffer DMA enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(RXDMAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Tx buffer DMA enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXDMAEN_A { #[doc = "0: Tx buffer DMA disabled"] DISABLED = 0, #[doc = "1: Tx buffer DMA enabled"] ENABLED = 1, } impl From<TXDMAEN_A> for bool { #[inline(always)] fn from(variant: TXDMAEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TXDMAEN`"] pub type TXDMAEN_R = crate::R<bool, TXDMAEN_A>; impl TXDMAEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TXDMAEN_A { match self.bits { false => TXDMAEN_A::DISABLED, true => TXDMAEN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TXDMAEN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TXDMAEN_A::ENABLED } } #[doc = "Write proxy for field `TXDMAEN`"] pub struct TXDMAEN_W<'a> { w: &'a mut W, } impl<'a> TXDMAEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TXDMAEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Tx buffer DMA disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(TXDMAEN_A::DISABLED) } #[doc = "Tx buffer DMA enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(TXDMAEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "SS output enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SSOE_A { #[doc = "0: SS output is disabled in master mode"] DISABLED = 0, #[doc = "1: SS output is enabled in master mode"] ENABLED = 1, } impl From<SSOE_A> for bool { #[inline(always)] fn from(variant: SSOE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SSOE`"] pub type SSOE_R = crate::R<bool, SSOE_A>; impl SSOE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SSOE_A { match self.bits { false => SSOE_A::DISABLED, true => SSOE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == SSOE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == SSOE_A::ENABLED } } #[doc = "Write proxy for field `SSOE`"] pub struct SSOE_W<'a> { w: &'a mut W, } impl<'a> SSOE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SSOE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "SS output is disabled in master mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(SSOE_A::DISABLED) } #[doc = "SS output is enabled in master mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(SSOE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "NSS pulse management\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSSP_A { #[doc = "0: No NSS pulse"] NOPULSE = 0, #[doc = "1: NSS pulse generated"] PULSEGENERATED = 1, } impl From<NSSP_A> for bool { #[inline(always)] fn from(variant: NSSP_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `NSSP`"] pub type NSSP_R = crate::R<bool, NSSP_A>; impl NSSP_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> NSSP_A { match self.bits { false => NSSP_A::NOPULSE, true => NSSP_A::PULSEGENERATED, } } #[doc = "Checks if the value of the field is `NOPULSE`"] #[inline(always)] pub fn is_no_pulse(&self) -> bool { *self == NSSP_A::NOPULSE } #[doc = "Checks if the value of the field is `PULSEGENERATED`"] #[inline(always)] pub fn is_pulse_generated(&self) -> bool { *self == NSSP_A::PULSEGENERATED } } #[doc = "Write proxy for field `NSSP`"] pub struct NSSP_W<'a> { w: &'a mut W, } impl<'a> NSSP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: NSSP_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No NSS pulse"] #[inline(always)] pub fn no_pulse(self) -> &'a mut W { self.variant(NSSP_A::NOPULSE) } #[doc = "NSS pulse generated"] #[inline(always)] pub fn pulse_generated(self) -> &'a mut W { self.variant(NSSP_A::PULSEGENERATED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Frame format\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FRF_A { #[doc = "0: SPI Motorola mode"] MOTOROLA = 0, #[doc = "1: SPI TI mode"] TI = 1, } impl From<FRF_A> for bool { #[inline(always)] fn from(variant: FRF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `FRF`"] pub type FRF_R = crate::R<bool, FRF_A>; impl FRF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FRF_A { match self.bits { false => FRF_A::MOTOROLA, true => FRF_A::TI, } } #[doc = "Checks if the value of the field is `MOTOROLA`"] #[inline(always)] pub fn is_motorola(&self) -> bool { *self == FRF_A::MOTOROLA } #[doc = "Checks if the value of the field is `TI`"] #[inline(always)] pub fn is_ti(&self) -> bool { *self == FRF_A::TI } } #[doc = "Write proxy for field `FRF`"] pub struct FRF_W<'a> { w: &'a mut W, } impl<'a> FRF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FRF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "SPI Motorola mode"] #[inline(always)] pub fn motorola(self) -> &'a mut W { self.variant(FRF_A::MOTOROLA) } #[doc = "SPI TI mode"] #[inline(always)] pub fn ti(self) -> &'a mut W { self.variant(FRF_A::TI) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Error interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ERRIE_A { #[doc = "0: Error interrupt masked"] MASKED = 0, #[doc = "1: Error interrupt not masked"] NOTMASKED = 1, } impl From<ERRIE_A> for bool { #[inline(always)] fn from(variant: ERRIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ERRIE`"] pub type ERRIE_R = crate::R<bool, ERRIE_A>; impl ERRIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ERRIE_A { match self.bits { false => ERRIE_A::MASKED, true => ERRIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == ERRIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == ERRIE_A::NOTMASKED } } #[doc = "Write proxy for field `ERRIE`"] pub struct ERRIE_W<'a> { w: &'a mut W, } impl<'a> ERRIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ERRIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Error interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(ERRIE_A::MASKED) } #[doc = "Error interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(ERRIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "RX buffer not empty interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXNEIE_A { #[doc = "0: RXE interrupt masked"] MASKED = 0, #[doc = "1: RXE interrupt not masked"] NOTMASKED = 1, } impl From<RXNEIE_A> for bool { #[inline(always)] fn from(variant: RXNEIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RXNEIE`"] pub type RXNEIE_R = crate::R<bool, RXNEIE_A>; impl RXNEIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RXNEIE_A { match self.bits { false => RXNEIE_A::MASKED, true => RXNEIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == RXNEIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == RXNEIE_A::NOTMASKED } } #[doc = "Write proxy for field `RXNEIE`"] pub struct RXNEIE_W<'a> { w: &'a mut W, } impl<'a> RXNEIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RXNEIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "RXE interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(RXNEIE_A::MASKED) } #[doc = "RXE interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(RXNEIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Tx buffer empty interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXEIE_A { #[doc = "0: TXE interrupt masked"] MASKED = 0, #[doc = "1: TXE interrupt not masked"] NOTMASKED = 1, } impl From<TXEIE_A> for bool { #[inline(always)] fn from(variant: TXEIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TXEIE`"] pub type TXEIE_R = crate::R<bool, TXEIE_A>; impl TXEIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TXEIE_A { match self.bits { false => TXEIE_A::MASKED, true => TXEIE_A::NOTMASKED, } } #[doc = "Checks if the value of the field is `MASKED`"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == TXEIE_A::MASKED } #[doc = "Checks if the value of the field is `NOTMASKED`"] #[inline(always)] pub fn is_not_masked(&self) -> bool { *self == TXEIE_A::NOTMASKED } } #[doc = "Write proxy for field `TXEIE`"] pub struct TXEIE_W<'a> { w: &'a mut W, } impl<'a> TXEIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TXEIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "TXE interrupt masked"] #[inline(always)] pub fn masked(self) -> &'a mut W { self.variant(TXEIE_A::MASKED) } #[doc = "TXE interrupt not masked"] #[inline(always)] pub fn not_masked(self) -> &'a mut W { self.variant(TXEIE_A::NOTMASKED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Data size\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum DS_A { #[doc = "3: 4-bit"] FOURBIT = 3, #[doc = "4: 5-bit"] FIVEBIT = 4, #[doc = "5: 6-bit"] SIXBIT = 5, #[doc = "6: 7-bit"] SEVENBIT = 6, #[doc = "7: 8-bit"] EIGHTBIT = 7, #[doc = "8: 9-bit"] NINEBIT = 8, #[doc = "9: 10-bit"] TENBIT = 9, #[doc = "10: 11-bit"] ELEVENBIT = 10, #[doc = "11: 12-bit"] TWELVEBIT = 11, #[doc = "12: 13-bit"] THIRTEENBIT = 12, #[doc = "13: 14-bit"] FOURTEENBIT = 13, #[doc = "14: 15-bit"] FIFTEENBIT = 14, #[doc = "15: 16-bit"] SIXTEENBIT = 15, } impl From<DS_A> for u8 { #[inline(always)] fn from(variant: DS_A) -> Self { variant as _ } } #[doc = "Reader of field `DS`"] pub type DS_R = crate::R<u8, DS_A>; impl DS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, DS_A> { use crate::Variant::*; match self.bits { 3 => Val(DS_A::FOURBIT), 4 => Val(DS_A::FIVEBIT), 5 => Val(DS_A::SIXBIT), 6 => Val(DS_A::SEVENBIT), 7 => Val(DS_A::EIGHTBIT), 8 => Val(DS_A::NINEBIT), 9 => Val(DS_A::TENBIT), 10 => Val(DS_A::ELEVENBIT), 11 => Val(DS_A::TWELVEBIT), 12 => Val(DS_A::THIRTEENBIT), 13 => Val(DS_A::FOURTEENBIT), 14 => Val(DS_A::FIFTEENBIT), 15 => Val(DS_A::SIXTEENBIT), i => Res(i), } } #[doc = "Checks if the value of the field is `FOURBIT`"] #[inline(always)] pub fn is_four_bit(&self) -> bool { *self == DS_A::FOURBIT } #[doc = "Checks if the value of the field is `FIVEBIT`"] #[inline(always)] pub fn is_five_bit(&self) -> bool { *self == DS_A::FIVEBIT } #[doc = "Checks if the value of the field is `SIXBIT`"] #[inline(always)] pub fn is_six_bit(&self) -> bool { *self == DS_A::SIXBIT } #[doc = "Checks if the value of the field is `SEVENBIT`"] #[inline(always)] pub fn is_seven_bit(&self) -> bool { *self == DS_A::SEVENBIT } #[doc = "Checks if the value of the field is `EIGHTBIT`"] #[inline(always)] pub fn is_eight_bit(&self) -> bool { *self == DS_A::EIGHTBIT } #[doc = "Checks if the value of the field is `NINEBIT`"] #[inline(always)] pub fn is_nine_bit(&self) -> bool { *self == DS_A::NINEBIT } #[doc = "Checks if the value of the field is `TENBIT`"] #[inline(always)] pub fn is_ten_bit(&self) -> bool { *self == DS_A::TENBIT } #[doc = "Checks if the value of the field is `ELEVENBIT`"] #[inline(always)] pub fn is_eleven_bit(&self) -> bool { *self == DS_A::ELEVENBIT } #[doc = "Checks if the value of the field is `TWELVEBIT`"] #[inline(always)] pub fn is_twelve_bit(&self) -> bool { *self == DS_A::TWELVEBIT } #[doc = "Checks if the value of the field is `THIRTEENBIT`"] #[inline(always)] pub fn is_thirteen_bit(&self) -> bool { *self == DS_A::THIRTEENBIT } #[doc = "Checks if the value of the field is `FOURTEENBIT`"] #[inline(always)] pub fn is_fourteen_bit(&self) -> bool { *self == DS_A::FOURTEENBIT } #[doc = "Checks if the value of the field is `FIFTEENBIT`"] #[inline(always)] pub fn is_fifteen_bit(&self) -> bool { *self == DS_A::FIFTEENBIT } #[doc = "Checks if the value of the field is `SIXTEENBIT`"] #[inline(always)] pub fn is_sixteen_bit(&self) -> bool { *self == DS_A::SIXTEENBIT } } #[doc = "Write proxy for field `DS`"] pub struct DS_W<'a> { w: &'a mut W, } impl<'a> DS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DS_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "4-bit"] #[inline(always)] pub fn four_bit(self) -> &'a mut W { self.variant(DS_A::FOURBIT) } #[doc = "5-bit"] #[inline(always)] pub fn five_bit(self) -> &'a mut W { self.variant(DS_A::FIVEBIT) } #[doc = "6-bit"] #[inline(always)] pub fn six_bit(self) -> &'a mut W { self.variant(DS_A::SIXBIT) } #[doc = "7-bit"] #[inline(always)] pub fn seven_bit(self) -> &'a mut W { self.variant(DS_A::SEVENBIT) } #[doc = "8-bit"] #[inline(always)] pub fn eight_bit(self) -> &'a mut W { self.variant(DS_A::EIGHTBIT) } #[doc = "9-bit"] #[inline(always)] pub fn nine_bit(self) -> &'a mut W { self.variant(DS_A::NINEBIT) } #[doc = "10-bit"] #[inline(always)] pub fn ten_bit(self) -> &'a mut W { self.variant(DS_A::TENBIT) } #[doc = "11-bit"] #[inline(always)] pub fn eleven_bit(self) -> &'a mut W { self.variant(DS_A::ELEVENBIT) } #[doc = "12-bit"] #[inline(always)] pub fn twelve_bit(self) -> &'a mut W { self.variant(DS_A::TWELVEBIT) } #[doc = "13-bit"] #[inline(always)] pub fn thirteen_bit(self) -> &'a mut W { self.variant(DS_A::THIRTEENBIT) } #[doc = "14-bit"] #[inline(always)] pub fn fourteen_bit(self) -> &'a mut W { self.variant(DS_A::FOURTEENBIT) } #[doc = "15-bit"] #[inline(always)] pub fn fifteen_bit(self) -> &'a mut W { self.variant(DS_A::FIFTEENBIT) } #[doc = "16-bit"] #[inline(always)] pub fn sixteen_bit(self) -> &'a mut W { self.variant(DS_A::SIXTEENBIT) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "FIFO reception threshold\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FRXTH_A { #[doc = "0: RXNE event is generated if the FIFO level is greater than or equal to 1/2 (16-bit)"] HALF = 0, #[doc = "1: RXNE event is generated if the FIFO level is greater than or equal to 1/4 (8-bit)"] QUARTER = 1, } impl From<FRXTH_A> for bool { #[inline(always)] fn from(variant: FRXTH_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `FRXTH`"] pub type FRXTH_R = crate::R<bool, FRXTH_A>; impl FRXTH_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FRXTH_A { match self.bits { false => FRXTH_A::HALF, true => FRXTH_A::QUARTER, } } #[doc = "Checks if the value of the field is `HALF`"] #[inline(always)] pub fn is_half(&self) -> bool { *self == FRXTH_A::HALF } #[doc = "Checks if the value of the field is `QUARTER`"] #[inline(always)] pub fn is_quarter(&self) -> bool { *self == FRXTH_A::QUARTER } } #[doc = "Write proxy for field `FRXTH`"] pub struct FRXTH_W<'a> { w: &'a mut W, } impl<'a> FRXTH_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FRXTH_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "RXNE event is generated if the FIFO level is greater than or equal to 1/2 (16-bit)"] #[inline(always)] pub fn half(self) -> &'a mut W { self.variant(FRXTH_A::HALF) } #[doc = "RXNE event is generated if the FIFO level is greater than or equal to 1/4 (8-bit)"] #[inline(always)] pub fn quarter(self) -> &'a mut W { self.variant(FRXTH_A::QUARTER) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Last DMA transfer for reception\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LDMA_RX_A { #[doc = "0: Number of data to transfer for receive is even"] EVEN = 0, #[doc = "1: Number of data to transfer for receive is odd"] ODD = 1, } impl From<LDMA_RX_A> for bool { #[inline(always)] fn from(variant: LDMA_RX_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LDMA_RX`"] pub type LDMA_RX_R = crate::R<bool, LDMA_RX_A>; impl LDMA_RX_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LDMA_RX_A { match self.bits { false => LDMA_RX_A::EVEN, true => LDMA_RX_A::ODD, } } #[doc = "Checks if the value of the field is `EVEN`"] #[inline(always)] pub fn is_even(&self) -> bool { *self == LDMA_RX_A::EVEN } #[doc = "Checks if the value of the field is `ODD`"] #[inline(always)] pub fn is_odd(&self) -> bool { *self == LDMA_RX_A::ODD } } #[doc = "Write proxy for field `LDMA_RX`"] pub struct LDMA_RX_W<'a> { w: &'a mut W, } impl<'a> LDMA_RX_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LDMA_RX_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Number of data to transfer for receive is even"] #[inline(always)] pub fn even(self) -> &'a mut W { self.variant(LDMA_RX_A::EVEN) } #[doc = "Number of data to transfer for receive is odd"] #[inline(always)] pub fn odd(self) -> &'a mut W { self.variant(LDMA_RX_A::ODD) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Last DMA transfer for transmission\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LDMA_TX_A { #[doc = "0: Number of data to transfer for transmit is even"] EVEN = 0, #[doc = "1: Number of data to transfer for transmit is odd"] ODD = 1, } impl From<LDMA_TX_A> for bool { #[inline(always)] fn from(variant: LDMA_TX_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LDMA_TX`"] pub type LDMA_TX_R = crate::R<bool, LDMA_TX_A>; impl LDMA_TX_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LDMA_TX_A { match self.bits { false => LDMA_TX_A::EVEN, true => LDMA_TX_A::ODD, } } #[doc = "Checks if the value of the field is `EVEN`"] #[inline(always)] pub fn is_even(&self) -> bool { *self == LDMA_TX_A::EVEN } #[doc = "Checks if the value of the field is `ODD`"] #[inline(always)] pub fn is_odd(&self) -> bool { *self == LDMA_TX_A::ODD } } #[doc = "Write proxy for field `LDMA_TX`"] pub struct LDMA_TX_W<'a> { w: &'a mut W, } impl<'a> LDMA_TX_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LDMA_TX_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Number of data to transfer for transmit is even"] #[inline(always)] pub fn even(self) -> &'a mut W { self.variant(LDMA_TX_A::EVEN) } #[doc = "Number of data to transfer for transmit is odd"] #[inline(always)] pub fn odd(self) -> &'a mut W { self.variant(LDMA_TX_A::ODD) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } impl R { #[doc = "Bit 0 - Rx buffer DMA enable"] #[inline(always)] pub fn rxdmaen(&self) -> RXDMAEN_R { RXDMAEN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Tx buffer DMA enable"] #[inline(always)] pub fn txdmaen(&self) -> TXDMAEN_R { TXDMAEN_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - SS output enable"] #[inline(always)] pub fn ssoe(&self) -> SSOE_R { SSOE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - NSS pulse management"] #[inline(always)] pub fn nssp(&self) -> NSSP_R { NSSP_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Frame format"] #[inline(always)] pub fn frf(&self) -> FRF_R { FRF_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Error interrupt enable"] #[inline(always)] pub fn errie(&self) -> ERRIE_R { ERRIE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - RX buffer not empty interrupt enable"] #[inline(always)] pub fn rxneie(&self) -> RXNEIE_R { RXNEIE_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - Tx buffer empty interrupt enable"] #[inline(always)] pub fn txeie(&self) -> TXEIE_R { TXEIE_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bits 8:11 - Data size"] #[inline(always)] pub fn ds(&self) -> DS_R { DS_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bit 12 - FIFO reception threshold"] #[inline(always)] pub fn frxth(&self) -> FRXTH_R { FRXTH_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - Last DMA transfer for reception"] #[inline(always)] pub fn ldma_rx(&self) -> LDMA_RX_R { LDMA_RX_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - Last DMA transfer for transmission"] #[inline(always)] pub fn ldma_tx(&self) -> LDMA_TX_R { LDMA_TX_R::new(((self.bits >> 14) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Rx buffer DMA enable"] #[inline(always)] pub fn rxdmaen(&mut self) -> RXDMAEN_W { RXDMAEN_W { w: self } } #[doc = "Bit 1 - Tx buffer DMA enable"] #[inline(always)] pub fn txdmaen(&mut self) -> TXDMAEN_W { TXDMAEN_W { w: self } } #[doc = "Bit 2 - SS output enable"] #[inline(always)] pub fn ssoe(&mut self) -> SSOE_W { SSOE_W { w: self } } #[doc = "Bit 3 - NSS pulse management"] #[inline(always)] pub fn nssp(&mut self) -> NSSP_W { NSSP_W { w: self } } #[doc = "Bit 4 - Frame format"] #[inline(always)] pub fn frf(&mut self) -> FRF_W { FRF_W { w: self } } #[doc = "Bit 5 - Error interrupt enable"] #[inline(always)] pub fn errie(&mut self) -> ERRIE_W { ERRIE_W { w: self } } #[doc = "Bit 6 - RX buffer not empty interrupt enable"] #[inline(always)] pub fn rxneie(&mut self) -> RXNEIE_W { RXNEIE_W { w: self } } #[doc = "Bit 7 - Tx buffer empty interrupt enable"] #[inline(always)] pub fn txeie(&mut self) -> TXEIE_W { TXEIE_W { w: self } } #[doc = "Bits 8:11 - Data size"] #[inline(always)] pub fn ds(&mut self) -> DS_W { DS_W { w: self } } #[doc = "Bit 12 - FIFO reception threshold"] #[inline(always)] pub fn frxth(&mut self) -> FRXTH_W { FRXTH_W { w: self } } #[doc = "Bit 13 - Last DMA transfer for reception"] #[inline(always)] pub fn ldma_rx(&mut self) -> LDMA_RX_W { LDMA_RX_W { w: self } } #[doc = "Bit 14 - Last DMA transfer for transmission"] #[inline(always)] pub fn ldma_tx(&mut self) -> LDMA_TX_W { LDMA_TX_W { w: self } } }
use std::io; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; use tokio::net::UdpSocket; use tokio_io::codec::{Decoder, Encoder}; use bytes::{BufMut, BytesMut}; /// A unified `Stream` and `Sink` interface to an underlying `UdpSocket`, using /// the `Encoder` and `Decoder` traits to encode and decode frames. /// /// Raw UDP sockets work with datagrams, but higher-level code usually wants to /// batch these into meaningful chunks, called "frames". This method layers /// framing on top of this socket by using the `Encoder` and `Decoder` traits to /// handle encoding and decoding of messages frames. Note that the incoming and /// outgoing frame types may be distinct. /// /// This function returns a *single* object that is both `Stream` and `Sink`; /// grouping this into a single object is often useful for layering things which /// require both read and write access to the underlying object. /// /// If you want to work more directly with the streams and sink, consider /// calling `split` on the `UdpFramed` returned by this method, which will break /// them into separate objects, allowing them to interact more easily. #[must_use = "sinks do nothing unless polled"] #[derive(Debug)] pub struct UdpFramed<C> { socket: UdpSocket, codec: C, rd: BytesMut, wr: BytesMut, out_addr: SocketAddr, flushed: bool, } impl<C: Decoder> Stream for UdpFramed<C> { type Item = (C::Item, SocketAddr); type Error = C::Error; fn poll(&mut self) -> Poll<Option<(Self::Item)>, Self::Error> { self.rd.reserve(INITIAL_RD_CAPACITY); let (n, addr) = unsafe { // Read into the buffer without having to initialize the memory. let (n, addr) = try_ready!(self.socket.poll_recv_from(self.rd.bytes_mut())); self.rd.advance_mut(n); (n, addr) }; trace!("received {} bytes, decoding", n); let frame_res = self.codec.decode(&mut self.rd); self.rd.clear(); let frame = frame_res?; let result = frame.map(|frame| (frame, addr)); // frame -> (frame, addr) trace!("frame decoded from buffer"); Ok(Async::Ready(result)) } } impl<C: Encoder> Sink for UdpFramed<C> { type SinkItem = (C::Item, SocketAddr); type SinkError = C::Error; fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> { trace!("sending frame"); if !self.flushed { match self.poll_complete() { Ok(Async::Ready(())) => {} _ => return Ok(AsyncSink::NotReady(item)), } } let (frame, out_addr) = item; self.codec.encode(frame, &mut self.wr)?; self.out_addr = out_addr; self.flushed = false; trace!("frame encoded; length={}", self.wr.len()); Ok(AsyncSink::Ready) } fn poll_complete(&mut self) -> Poll<(), C::Error> { if self.flushed { return Ok(Async::Ready(())); } trace!("flushing frame; length={}", self.wr.len()); let n = match self.socket.poll_send_to(&self.wr, &self.out_addr) { Ok(Async::Ready(n)) => n, Ok(Async::NotReady) => return Ok(Async::NotReady), Err(e) => { if e.kind() == ::std::io::ErrorKind::WouldBlock { return Ok(Async::NotReady); } debug!("error sending frame: {:?}", e); return Ok(Async::Ready(())); } }; trace!("written {}", n); let wrote_all = n == self.wr.len(); self.wr.clear(); self.flushed = true; if wrote_all { Ok(Async::Ready(())) } else { Err(io::Error::new( io::ErrorKind::Other, "failed to write entire datagram to socket", ).into()) } } fn close(&mut self) -> Poll<(), C::Error> { try_ready!(self.poll_complete()); Ok(().into()) } } const INITIAL_RD_CAPACITY: usize = 64 * 1024; const INITIAL_WR_CAPACITY: usize = 8 * 1024; #[allow(dead_code)] impl<C> UdpFramed<C> { /// Create a new `UdpFramed` backed by the given socket and codec. /// /// See struct level documention for more details. pub fn new(socket: UdpSocket, codec: C) -> UdpFramed<C> { UdpFramed { socket: socket, codec: codec, out_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0)), rd: BytesMut::with_capacity(INITIAL_RD_CAPACITY), wr: BytesMut::with_capacity(INITIAL_WR_CAPACITY), flushed: true, } } /// Returns a reference to the underlying I/O stream wrapped by `Framed`. /// /// # Note /// /// Care should be taken to not tamper with the underlying stream of data /// coming in as it may corrupt the stream of frames otherwise being worked /// with. pub fn get_ref(&self) -> &UdpSocket { &self.socket } /// Returns a mutable reference to the underlying I/O stream wrapped by /// `Framed`. /// /// # Note /// /// Care should be taken to not tamper with the underlying stream of data /// coming in as it may corrupt the stream of frames otherwise being worked /// with. pub fn get_mut(&mut self) -> &mut UdpSocket { &mut self.socket } /// Consumes the `Framed`, returning its underlying I/O stream. pub fn into_inner(self) -> UdpSocket { self.socket } }
use rune::ast; use rune::macros; use rune::{quote, Parser, Spanned, TokenStream}; use runestick::SpannedError; /// Implementation for the `stringy_math!` macro. pub(crate) fn stringy_math(stream: &TokenStream) -> runestick::Result<TokenStream> { let mut parser = Parser::from_token_stream(stream); let mut output = quote!(0); while !parser.is_eof()? { let op = parser.parse::<ast::Ident>()?; let arg = parser.parse::<ast::Expr>()?; output = match macros::resolve(op)?.as_ref() { "add" => quote!((#output) + #arg), "sub" => quote!((#output) - #arg), "div" => quote!((#output) / #arg), "mul" => quote!((#output) * #arg), _ => return Err(SpannedError::msg(op.span(), "unsupported operation").into()), } } parser.eof()?; Ok(output.into_token_stream()) }
use std::error; use std::fs; use cgmath::{InnerSpace, Vector3}; use image::DynamicImage; use log::debug; use crate::geometry::Triangle; use crate::render::Renderer; pub struct Face { pub vertex: u32, pub texture: u32, pub normal: u32, } pub struct Object { pub faces: Vec<Vec<Face>>, pub vertices: Vec<Vector3<f64>>, pub normals: Vec<Vector3<f64>>, pub textures: Vec<Vector3<f64>>, pub texture: DynamicImage, } impl Object { pub fn new(path: String, texture: DynamicImage) -> Result<Object, Box<error::Error>> { debug!("Loading object: {}", path); let file_contents = fs::read_to_string(path)?; let mut faces: Vec<Vec<Face>> = Vec::new(); let mut vertices: Vec<Vector3<f64>> = Vec::new(); let mut textures: Vec<Vector3<f64>> = Vec::new(); let mut normals: Vec<Vector3<f64>> = Vec::new(); for line in file_contents.lines() { let mut line: Vec<&str> = line.split_whitespace().collect(); if line.is_empty() { continue; } let line_type = line.remove(0); match line_type { "f" => faces.push(Object::parse_face(&line)), "vt" => match line.len() { 1 => textures.push(Vector3::new(line[0].parse::<f64>().unwrap(), 0., 0.)), 2 => textures.push(Vector3::new( line[0].parse::<f64>().unwrap(), line[1].parse::<f64>().unwrap(), 0., )), 3 => textures.push(Vector3::new( line[0].parse::<f64>().unwrap(), line[1].parse::<f64>().unwrap(), line[2].parse::<f64>().unwrap(), )), _ => {} }, "vn" => normals.push(Vector3::new( line[0].parse::<f64>().unwrap(), line[1].parse::<f64>().unwrap(), line[2].parse::<f64>().unwrap(), )), "v" => vertices.push(Vector3::new( line[0].parse::<f64>().unwrap(), line[1].parse::<f64>().unwrap(), line[2].parse::<f64>().unwrap(), )), _ => {} } } Ok(Object { faces, vertices, normals, textures, texture, }) } fn parse_face(line: &[&str]) -> Vec<Face> { let mut face: Vec<Face> = Vec::new(); for reference in line { let reference: Vec<&str> = reference.split('/').collect(); match reference.len() { 1 => { face.push(Face { vertex: reference[0].parse::<u32>().unwrap(), texture: 0 as u32, normal: 0 as u32, }); } 2 => { face.push(Face { vertex: reference[0].parse::<u32>().unwrap(), texture: reference[1].parse::<u32>().unwrap(), normal: 0 as u32, }); } 3 => { face.push(Face { vertex: reference[0].parse::<u32>().unwrap(), texture: reference[1].parse::<u32>().unwrap(), normal: reference[2].parse::<u32>().unwrap(), }); } _ => {} } } face } fn calc_intensity(vertices: &[Vector3<f64>]) -> f64 { let n: Vector3<f64> = (vertices[2] - vertices[0]).cross(vertices[1] - vertices[0]); let n = n.normalize(); let light_direction: Vector3<f64> = Vector3::new(0., 0., -1.); n.dot(light_direction) } pub fn render(&self, renderer: &mut impl Renderer) -> Result<bool, Box<error::Error>> { let (width, height) = renderer.get_size(); for face in &self.faces { let mut vertices: Vec<Vector3<f64>> = Vec::new(); let mut texture_vertices: Vec<Vector3<f64>> = Vec::new(); for vertex in face { vertices.push(self.vertices[(vertex.vertex - 1) as usize]); texture_vertices.push(self.textures[(vertex.texture - 1) as usize]); } let intensity = Object::calc_intensity(&vertices); if intensity <= 0. { continue; } for vertex in &mut vertices { vertex.x = (vertex.x + 1.) * f64::from(width) / 2.0; vertex.y = (vertex.y + 1.) * f64::from(height) / 2.0; } for index in 1..vertices.len() - 1 { Triangle::new( vertices[0], vertices[index], vertices[index + 1], &self.texture, &texture_vertices, intensity, )? .render(renderer)?; } } Ok(true) } }
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use crate::lexer::preprocessor::context::PreprocContext; use crate::lexer::{Lexer, LocToken, Token}; #[derive(Clone, Debug, PartialEq)] pub struct Destructor { pub name: String, } pub(crate) struct DtorParser<'a, 'b, PC: PreprocContext> { lexer: &'b mut Lexer<'a, PC>, } impl<'a, 'b, PC: PreprocContext> DtorParser<'a, 'b, PC> { pub(crate) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self { Self { lexer } } pub(crate) fn parse(self, tok: Option<LocToken>) -> (Option<LocToken>, Option<Destructor>) { let tok = tok.unwrap_or_else(|| self.lexer.next_useful()); if tok.tok != Token::Tilde { return (Some(tok), None); } let tok = self.lexer.next_useful(); if let Token::Identifier(name) = tok.tok { (None, Some(Destructor { name })) } else { unreachable!("Invalid token in dtor name: {:?}", tok) } } }
#[derive(Debug, PartialEq, Eq)] enum NestedInteger { Int(i32), List(Vec<NestedInteger>), } struct Solution {} impl Solution { fn sum(nested_integer: &NestedInteger, depth: i32) -> i32 { match nested_integer { NestedInteger::Int(i) => i * depth, NestedInteger::List(l) => { l.iter().map(|n| Solution::sum(n, depth + 1)).sum() } } } pub fn depth_sum(nested_list: Vec<NestedInteger>) -> i32 { Solution::sum(&NestedInteger::List(nested_list), 0) } } #[cfg(test)] mod tests { use crate::{NestedInteger, Solution}; fn test(nested_list: Vec<NestedInteger>, expected: i32) { assert_eq!(Solution::depth_sum(nested_list), expected) } #[test] fn example1() { test( vec![ NestedInteger::List(vec![ NestedInteger::Int(1), NestedInteger::Int(1), ]), NestedInteger::Int(2), NestedInteger::List(vec![ NestedInteger::Int(1), NestedInteger::Int(1), ]), ], 10, ) } #[test] fn example2() { test( vec![ NestedInteger::Int(1), NestedInteger::List(vec![ NestedInteger::Int(4), NestedInteger::List(vec![ NestedInteger::Int(6), ]) ]) ], 27, ) } #[test] fn example3() { test( vec![ NestedInteger::Int(0), ], 0, ) } }
extern crate kdtree_na; extern crate nalgebra; extern crate num_traits; use std::sync::atomic::{AtomicUsize, Ordering}; use nalgebra::constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint}; use nalgebra::{storage::Storage, vector, DVector, Dim, Matrix, Norm, SimdComplexField, Vector2}; use num_traits::Zero; use kdtree_na::KdTree; pub struct EuclideanNormSquaredCounted<'a> { norm_count: &'a AtomicUsize, distance_count: &'a AtomicUsize, } impl<'a, X: SimdComplexField> Norm<X> for EuclideanNormSquaredCounted<'a> { #[inline] fn norm<R, C, S>(&self, m: &Matrix<X, R, C, S>) -> X::SimdRealField where R: Dim, C: Dim, S: Storage<X, R, C>, { self.norm_count.fetch_add(1, Ordering::SeqCst); m.norm_squared() } #[inline] fn metric_distance<R1, C1, S1, R2, C2, S2>( &self, m1: &Matrix<X, R1, C1, S1>, m2: &Matrix<X, R2, C2, S2>, ) -> X::SimdRealField where R1: Dim, C1: Dim, S1: Storage<X, R1, C1>, R2: Dim, C2: Dim, S2: Storage<X, R2, C2>, ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2>, { self.distance_count.fetch_add(1, Ordering::SeqCst); m1.zip_fold(m2, X::SimdRealField::zero(), |acc, a, b| { let diff = a - b; acc + diff.simd_modulus_squared() }) } } static POINT_A: (Vector2<f64>, usize) = (vector![0f64, 0f64], 0); static POINT_B: (Vector2<f64>, usize) = (vector![1f64, 1f64], 1); static POINT_C: (Vector2<f64>, usize) = (vector![2f64, 2f64], 2); static POINT_D: (Vector2<f64>, usize) = (vector![3f64, 3f64], 3); #[test] fn it_works_with_static() { let capacity_per_node = 2; let mut kdtree = KdTree::with_capacity_static(capacity_per_node); let norm_count = AtomicUsize::new(0); let distance_count = AtomicUsize::new(0); let norm = EuclideanNormSquaredCounted { norm_count: &norm_count, distance_count: &distance_count, }; kdtree.add(&POINT_A.0, POINT_A.1).unwrap(); kdtree.add(&POINT_B.0, POINT_B.1).unwrap(); kdtree.add(&POINT_C.0, POINT_C.1).unwrap(); kdtree.add(&POINT_D.0, POINT_D.1).unwrap(); kdtree.nearest(&POINT_A.0, 0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 0); kdtree.nearest(&POINT_A.0, 1, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); kdtree.nearest(&POINT_A.0, 2, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 4); kdtree.nearest(&POINT_A.0, 3, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); kdtree.nearest(&POINT_A.0, 4, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); kdtree.nearest(&POINT_A.0, 5, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); kdtree.nearest(&POINT_B.0, 4, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); kdtree.within(&POINT_A.0, 0.0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); kdtree.within(&POINT_B.0, 1.0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 3); kdtree.within(&POINT_B.0, 2.0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); let mut iter = kdtree.iter_nearest(&POINT_A.0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 0); iter.next().unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); iter.next().unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); iter.next().unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); iter.next().unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 0); } #[test] fn it_works_with_dynamic() { let dimensions = 2; let capacity_per_node = 2; let mut kdtree = KdTree::with_capacity_dynamic(2, capacity_per_node); let norm_count = AtomicUsize::new(0); let distance_count = AtomicUsize::new(0); let norm = EuclideanNormSquaredCounted { norm_count: &norm_count, distance_count: &distance_count, }; let point_a = ( DVector::from_iterator(dimensions, POINT_A.0.iter().cloned()), POINT_A.1, ); let point_b = ( DVector::from_iterator(dimensions, POINT_B.0.iter().cloned()), POINT_B.1, ); let point_c = ( DVector::from_iterator(dimensions, POINT_C.0.iter().cloned()), POINT_C.1, ); let point_d = ( DVector::from_iterator(dimensions, POINT_D.0.iter().cloned()), POINT_D.1, ); kdtree.add(&point_a.0, point_a.1).unwrap(); kdtree.add(&point_b.0, point_b.1).unwrap(); kdtree.add(&point_c.0, point_c.1).unwrap(); kdtree.add(&point_d.0, point_d.1).unwrap(); kdtree.nearest(&point_a.0, 0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 0); kdtree.nearest(&point_a.0, 1, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); kdtree.nearest(&point_a.0, 2, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 4); kdtree.nearest(&point_a.0, 3, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); kdtree.nearest(&point_a.0, 4, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); kdtree.nearest(&point_a.0, 5, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); kdtree.nearest(&point_b.0, 4, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); kdtree.within(&point_a.0, 0.0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); kdtree.within(&point_b.0, 1.0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 3); kdtree.within(&point_b.0, 2.0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 6); let mut iter = kdtree.iter_nearest(&point_a.0, &norm).unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 0); iter.next().unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); iter.next().unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); iter.next().unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 2); iter.next().unwrap(); assert_eq!(norm_count.swap(0, Ordering::SeqCst), 0); assert_eq!(distance_count.swap(0, Ordering::SeqCst), 0); }
use super::*; #[test] fn with_binary_encoding_atom_that_does_not_exist_errors_badarg() { // :erlang.term_to_binary(:non_existent_0) tried_to_convert_to_an_atom_that_doesnt_exist(vec![ 131, 100, 0, 14, 110, 111, 110, 95, 101, 120, 105, 115, 116, 101, 110, 116, 95, 48, ]); } #[test] fn with_binary_encoding_list_containing_atom_that_does_not_exist_errors_badarg() { // :erlang.term_to_binary([:non_existent_1]) tried_to_convert_to_an_atom_that_doesnt_exist(vec![ 131, 108, 0, 0, 0, 1, 100, 0, 14, 110, 111, 110, 95, 101, 120, 105, 115, 116, 101, 110, 116, 95, 49, 106, ]); } #[test] fn with_binary_encoding_small_tuple_containing_atom_that_does_not_exist_errors_badarg() { // :erlang.term_to_binary({:non_existent_2}) tried_to_convert_to_an_atom_that_doesnt_exist(vec![ 131, 104, 1, 100, 0, 14, 110, 111, 110, 95, 101, 120, 105, 115, 116, 101, 110, 116, 95, 50, ]); } #[test] fn with_binary_encoding_small_atom_utf8_that_does_not_exist_errors_badarg() { // :erlang.term_to_binary(:"non_existent_3_😈") tried_to_convert_to_an_atom_that_doesnt_exist(vec![ 131, 119, 19, 110, 111, 110, 95, 101, 120, 105, 115, 116, 101, 110, 116, 95, 51, 95, 240, 159, 152, 136, ]); } fn options(process: &Process) -> Term { process.cons(Atom::str_to_term("safe"), Term::NIL) } fn tried_to_convert_to_an_atom_that_doesnt_exist(byte_vec: Vec<u8>) { run!( |arc_process| { ( Just(arc_process.clone()), strategy::term::binary::containing_bytes(byte_vec.clone(), arc_process.clone()), ) }, |(arc_process, binary)| { prop_assert_badarg!( result(&arc_process, binary, options(&arc_process)), "tried to convert to an atom that doesn't exist" ); Ok(()) }, ); }
//! Abstracts kernels so we can build generic methods to test them. //! Kernel also defines a function generate_dump that is used to dump the list of actions taken for //! a specific implementation of a kernel, which in turn allows to run tests on this specific //! implementation. generate_dump is only used in binary src/bin/kernel_dump.rs and not directly in //! tests use std::borrow::Cow; use std::sync::Arc; use crate::statistics; use itertools::Itertools; use log::*; use num_cpus; use rayon::prelude::*; use rpds::list::List; use serde::{de::DeserializeOwned, Serialize}; use std::io::{Read, Write}; use std::sync::{atomic, Mutex}; use telamon::explorer::{ self, choice::{self, ActionEx}, local_selection, Candidate, }; use telamon::helper::{MemInit, SignatureBuilder}; use telamon::model::Bound; use telamon::{codegen, device, ir}; use utils::*; /// Ignore candidates with a too big bound in tests. const CUT: f64 = 2e8f64; /// Maximal number of deadends to accept before failing. // TODO(cleanup): tune MAX_DEADEND_RATIO //const MAX_DEADEND_RATIO: usize = 20; const MAX_DEADEND_RATIO: f32 = 0.95; /// Kernel factory, which can be used in order to generate a new kernel. /// /// The two configurations available are: /// /// - [`name`]: specifies an associated name for the kernel's signature. If not specified, this is /// taken from `Kernel::name()`. /// - [`mem_init`]: specifies the memory initialization strategy for the parameters. /// /// # Examples /// /// ```ignore /// // `context` is an existing `device::Context` /// let (signature, kernel, context) = KernelBuilder::new() /// .name("My kernel") /// .build::<linalg::FusedMM<f32>, _>( /// linalg::FusedMMP::new(128, 128, 128), /// &mut context, /// ); /// /// // Now `context` is an immutable reference /// let candidates = kernel.build_body(&signature, context); /// ``` /// /// [`name`]: #method.name /// [`mem_init`]: #method.mem_init #[derive(Debug, Clone, Default)] pub struct KernelBuilder<'a> { /// The name of the kernel. If `None`, taken from the `Kernel::name`. name: Option<Cow<'a, str>>, /// Memory initialisation strategy. mem_init: MemInit, } impl<'a> KernelBuilder<'a> { /// Generates the base configuration for creating a kernel, from which configuration methods /// can be chained. pub fn new() -> Self { KernelBuilder::default() } /// Sets the name of the generated kernel. This will appear in log files. pub fn name<T: Into<Cow<'a, str>>>(mut self, name: T) -> Self { self.name = Some(name.into()); self } /// Sets the memory initialization strategy. See `MemInit` for details. pub fn mem_init(mut self, mem_init: MemInit) -> Self { self.mem_init = mem_init; self } /// Create a kernel in the given context. This returns a frozen reference to the context, the /// kernel, and its signature. pub fn build<'b, K, AM>( &self, params: K::Parameters, context: &'b mut AM, ) -> (ir::Signature, K, &'b AM) where AM: device::ArgMap<'a> + device::Context, K: Kernel<'a> + 'b, { let name = self .name .as_ref() .map(Cow::clone) .unwrap_or_else(|| K::name().into()); let (kernel, signature); { let mut builder = SignatureBuilder::new(&name, context); builder.set_mem_init(self.mem_init); kernel = K::build_signature(params, &mut builder); signature = builder.get(); } (signature, kernel, context) } } /// A kernel that can be compiled, benchmarked and used for correctness tests. pub trait Kernel<'a>: Sized + Sync { /// The input parameters of the kernel. type Parameters: Clone + DeserializeOwned + Serialize; /// The values to expect as output. type ExpectedOutput: Sync + 'static; /// The name of the function computed by the kernel. fn name() -> &'static str; /// Builds the signature of the kernel in the builder and returns an object that /// stores enough information to later build the kernel body and check its result. fn build_signature<AM>( parameters: Self::Parameters, builder: &mut SignatureBuilder<AM>, ) -> Self where AM: device::ArgMap<'a> + device::Context; /// Builder the kernel body in the given builder. This builder should be based on the /// signature created by `build_signature`. fn build_body<'b>( &self, signature: Arc<ir::Signature>, ctx: &'b dyn device::Context, ) -> Vec<Candidate>; /// Computes the expected output. fn get_expected_output(&self, _: &dyn device::Context) -> Self::ExpectedOutput; /// Ensures the generated code performs the correct operation. fn check_result( &self, expected: &Self::ExpectedOutput, context: &dyn device::Context, ) -> Result<(), String>; /// Generate a dump of a specific implementation of Self in a file, so we can rerun tests on /// the same candidate multiple times. More specifically, we dump the list of actions taken on /// the candidate rather than the candidate itself fn generate_dump<'b, AM, F: Write>( params: Self::Parameters, ctx: &'b mut AM, sink: &mut F, ) where AM: device::Context + device::ArgMap<'a>, { let (signature, kernel, ctx) = KernelBuilder::new().build::<Self, AM>(params.clone(), ctx); let mut candidate = kernel.build_body(signature.into(), ctx).remove(0); let order = explorer::config::NewNodeOrder::WeightedRandom; let ordering = explorer::config::ChoiceOrdering::default(); loop { let cand_clone = candidate.clone(); let leaf = local_selection::descend(&ordering, order, ctx, cand_clone, CUT); if let Some(leaf) = leaf { let device_fn = codegen::Function::build(&leaf.space); ctx.evaluate(&device_fn, device::EvalMode::FindBest) .unwrap(); candidate = leaf; break; } } let to_serialize = (params, candidate.actions); serde_json::to_writer(sink, &to_serialize).unwrap(); } /// Takes a path to a log and execute it. Caller is responsible for making sure that the log /// corresponds to the kernel and context being executed fn execute_dump<AM, F: Read>(ctx: &mut AM, dump: &mut F) where AM: device::Context + device::ArgMap<'a>, { // Retrieve decisions from dump let mut json = String::new(); dump.read_to_string(&mut json).unwrap(); let (params, action_list): (Self::Parameters, List<ActionEx>) = serde_json::from_str(&json).unwrap(); let (signature, kernel, ctx) = KernelBuilder::new().build::<Self, AM>(params, ctx); let expected_output = kernel.get_expected_output(ctx); let candidate = kernel.build_body(signature.into(), ctx).remove(0); let implem = action_list.iter().fold(candidate, |cand, action| { cand.apply_decision(ctx, action.clone()) .unwrap_or_else(|err| panic!("In kernel {}: {}", Self::name(), err)) }); if choice::default_list(&implem.space).next().is_some() { panic!("dump is not a fixed candidate") } let device_fn = codegen::Function::build(&implem.space); ctx.device().print( &device_fn, &mut std::fs::File::create("/tmp/code.c").unwrap(), ); ctx.evaluate(&device_fn, device::EvalMode::FindBest) .unwrap(); if let Err(err) = kernel.check_result(&expected_output, ctx) { panic!( "incorrect output for kernel {}, with actions {:?}: {}", Self::name(), implem.actions, err ) } } /// Generates, executes and tests the output of candidates for the kernel. fn test_correctness<AM>(params: Self::Parameters, num_tests: usize, context: &mut AM) where AM: device::ArgMap<'a> + device::Context, { let (signature, kernel, context) = KernelBuilder::new().build::<Self, AM>(params, context); let expected_output = kernel.get_expected_output(context); let candidates = kernel.build_body(signature.into(), context); let mut num_deadends = 0; let mut num_runs = 0; while num_runs < num_tests { let order = explorer::config::NewNodeOrder::WeightedRandom; let ordering = explorer::config::ChoiceOrdering::default(); let candidate_idx = order.pick_candidate(&candidates, CUT); let candidate = candidates[unwrap!(candidate_idx)].clone(); let leaf = local_selection::descend(&ordering, order, context, candidate, CUT); if let Some(leaf) = leaf { let device_fn = codegen::Function::build(&leaf.space); unwrap!( context.evaluate(&device_fn, device::EvalMode::FindBest), "evaluation failed for kernel {}, with actions {:?}", Self::name(), leaf.actions ); if let Err(err) = kernel.check_result(&expected_output, context) { panic!( "incorrect output for kernel {}, with actions {:?}: {}", Self::name(), leaf.actions, err ) } num_runs += 1; } else { num_deadends += 1; if num_deadends as f32 / ((1 + num_deadends + num_runs) as f32) >= MAX_DEADEND_RATIO { panic!("too many dead-ends for kernel {}, {} deadends for {} successful runs", Self::name(), num_deadends, num_runs) } } } } /// Tests the correctness of the bound of kernels and returns the list of tested leafs /// along with the actual evaluation time. #[allow(clippy::collapsible_if)] fn test_bound<AM>( params: Self::Parameters, num_tests: usize, mem_init: MemInit, context: &mut AM, ) -> Vec<BoundSample> where AM: device::ArgMap<'a> + device::Context, { let (signature, kernel, context) = KernelBuilder::new() .mem_init(mem_init) .build::<Self, AM>(params, context); let candidates = kernel.build_body(signature.into(), context); let leaves = Mutex::new(Vec::new()); let num_tested = atomic::AtomicUsize::new(0); let stabilizer = &context.stabilizer(); context.async_eval( num_cpus::get(), device::EvalMode::TestBound, &|evaluator| loop { if num_tested.fetch_add(1, atomic::Ordering::SeqCst) >= num_tests { if num_tested.fetch_sub(1, atomic::Ordering::SeqCst) > num_tests { break; } } if let Some((leaf, bounds)) = descend_check_bounds(&candidates, context) { let leaves = &leaves; evaluator.add_kernel(leaf, move |leaf, kernel| { let bound = leaf.bound.clone(); let runtime = stabilizer .wrap(kernel) .bound(Some(bound.value())) .evaluate() .unwrap(); let mut leaves = unwrap!(leaves.lock()); let mut actions = leaf.actions.iter().cloned().collect_vec(); actions.reverse(); for (idx, partial_bound) in bounds.iter().enumerate() { assert!( partial_bound.value() <= bound.value() * 1.01, "invalid inner bound: {} < {}, kernel {}, \ actions {:?} then {:?}", partial_bound, bound, Self::name(), &actions[..idx], &actions[idx..] ); } info!("new evaluation: {:.2e}ns, bound {}", runtime, bound); leaves.push(BoundSample { actions, bound, runtime, }); }); } else { num_tested.fetch_sub(1, atomic::Ordering::SeqCst); } }, ); unwrap!(leaves.into_inner()) } /// Runs the search and benchmarks the resulting candidate. fn benchmark<AM>( config: &explorer::Config, params: Self::Parameters, num_samples: usize, mem_init: MemInit, context: &mut AM, ) -> Vec<f64> where AM: device::ArgMap<'a> + device::Context, { let (signature, kernel, context) = KernelBuilder::new() .mem_init(mem_init) .build::<Self, AM>(params, context); let signature = Arc::new(signature); let search_space = kernel.build_body(Arc::clone(&signature), context); let expected = kernel.get_expected_output(context); let best = unwrap!( explorer::find_best_ex( config, context, search_space, Some(&|_, context| kernel.check_result(&expected, context)) ), "no candidates found for kernel {}", signature.name, ); let best_fn = codegen::Function::build(&best.space); context.benchmark(&best_fn, num_samples) } /// Computes the probability of encountering a dead-end when descending in the search /// tree. fn deadend_ratio<AM>( params: Self::Parameters, num_samples: usize, context: &mut AM, ) -> f64 where AM: device::ArgMap<'a> + device::Context, { let (signature, kernel, context) = KernelBuilder::new() .mem_init(MemInit::Uninit) .build::<Self, AM>(params, context); let candidates = kernel.build_body(signature.into(), context); let num_deadends = (0..num_samples) .into_par_iter() .filter(|_| { let order = explorer::config::NewNodeOrder::WeightedRandom; let ordering = explorer::config::ChoiceOrdering::default(); let inf = std::f64::INFINITY; let candidate_idx = order.pick_candidate(&candidates, inf); let candidate = candidates[unwrap!(candidate_idx)].clone(); local_selection::descend(&ordering, order, context, candidate, inf) .is_none() }) .count(); num_deadends as f64 / num_samples as f64 } } /// Descends along a path in the search tree and stores the bounds encountered on the way. fn descend_check_bounds( candidates: &[Candidate], context: &dyn device::Context, ) -> Option<(Candidate, Vec<Bound>)> { let order = explorer::config::NewNodeOrder::WeightedRandom; let mut candidates = std::borrow::Cow::Borrowed(candidates); let mut bounds = Vec::new(); loop { let idx = if let Some(idx) = order.pick_candidate(&candidates, CUT) { idx } else { return None; }; bounds.push(candidates[idx].bound.clone()); let choice_opt = explorer::choice::default_list(&candidates[idx].space).next(); if let Some(choice) = choice_opt { let new_nodes = candidates[idx] .apply_choice(context, choice) .into_iter() .filter(|x| x.bound.value() < CUT) .collect_vec(); candidates = std::borrow::Cow::Owned(new_nodes); } else { return Some((candidates[idx].clone(), bounds)); } } } /// A sample of the accuracy of bounds. pub struct BoundSample { actions: Vec<explorer::choice::ActionEx>, bound: Bound, runtime: f64, } impl BoundSample { /// Returns the ratio between the bound and the actual evaluation. fn ratio(&self) -> f64 { self.runtime / self.bound.value() } } impl std::fmt::Display for BoundSample { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "{:.2}x, {:.2e}ns vs {}, for actions {:?}", self.ratio(), self.runtime, self.bound, self.actions ) } } /// Prints an analysis of the bounds computed by the lower bound model. pub fn analyze_bounds(mut bounds: Vec<BoundSample>) { const NUM_QUANTILES: usize = 5; bounds.sort_by(|x, y| cmp_f64(x.ratio(), y.ratio())); let num_errors = bounds.iter().take_while(|b| b.ratio() < 1.).count(); if num_errors > 0 { let error_ratio = num_errors as f64 / bounds.len() as f64; let error_ratio = statistics::estimate_ratio(error_ratio, bounds.len()); println!("ratio of errors {}, for example: ", error_ratio); let num_printed = std::cmp::min(NUM_QUANTILES, num_errors); for i in 0..num_printed { let index = i * num_errors / num_printed; println!("{}% worst error: {}", i * 100 / num_printed, bounds[index]); } } if num_errors < bounds.len() { let num_bounds = bounds.len() - num_errors; let num_quantiles = std::cmp::min(NUM_QUANTILES, num_bounds); for i in 0..num_quantiles { let index = (i + 1) * (num_bounds / num_quantiles) - 1; println!( "{}% worst: {}", (i + 1) * 100 / num_quantiles, bounds[num_errors + index] ); } } }
use crate::instruction::Instruction; use std::collections::VecDeque; pub fn parse(bytes: &[u8]) -> VecDeque<Instruction> { let mut instructions = VecDeque::with_capacity(bytes.len()); for b in bytes { if let Some(i) = parse_byte(*b) { instructions.push_back(i); } } instructions } fn parse_byte(b: u8) -> Option<Instruction> { match b as char { '+' => Some(Instruction::Add(1)), '-' => Some(Instruction::Sub(1)), '>' => Some(Instruction::Right(1)), '<' => Some(Instruction::Left(1)), '.' => Some(Instruction::Out), ',' => Some(Instruction::In), '[' => Some(Instruction::Open), ']' => Some(Instruction::Close), _ => None, } }
#[doc = "Reader of register MPCBB1_VCTR52"] pub type R = crate::R<u32, super::MPCBB1_VCTR52>; #[doc = "Writer for register MPCBB1_VCTR52"] pub type W = crate::W<u32, super::MPCBB1_VCTR52>; #[doc = "Register MPCBB1_VCTR52 `reset()`'s with value 0xffff_ffff"] impl crate::ResetValue for super::MPCBB1_VCTR52 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0xffff_ffff } } #[doc = "Reader of field `B1664`"] pub type B1664_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1664`"] pub struct B1664_W<'a> { w: &'a mut W, } impl<'a> B1664_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `B1665`"] pub type B1665_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1665`"] pub struct B1665_W<'a> { w: &'a mut W, } impl<'a> B1665_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `B1666`"] pub type B1666_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1666`"] pub struct B1666_W<'a> { w: &'a mut W, } impl<'a> B1666_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `B1667`"] pub type B1667_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1667`"] pub struct B1667_W<'a> { w: &'a mut W, } impl<'a> B1667_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `B1668`"] pub type B1668_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1668`"] pub struct B1668_W<'a> { w: &'a mut W, } impl<'a> B1668_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `B1669`"] pub type B1669_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1669`"] pub struct B1669_W<'a> { w: &'a mut W, } impl<'a> B1669_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `B1670`"] pub type B1670_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1670`"] pub struct B1670_W<'a> { w: &'a mut W, } impl<'a> B1670_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `B1671`"] pub type B1671_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1671`"] pub struct B1671_W<'a> { w: &'a mut W, } impl<'a> B1671_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `B1672`"] pub type B1672_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1672`"] pub struct B1672_W<'a> { w: &'a mut W, } impl<'a> B1672_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `B1673`"] pub type B1673_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1673`"] pub struct B1673_W<'a> { w: &'a mut W, } impl<'a> B1673_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `B1674`"] pub type B1674_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1674`"] pub struct B1674_W<'a> { w: &'a mut W, } impl<'a> B1674_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `B1675`"] pub type B1675_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1675`"] pub struct B1675_W<'a> { w: &'a mut W, } impl<'a> B1675_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `B1676`"] pub type B1676_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1676`"] pub struct B1676_W<'a> { w: &'a mut W, } impl<'a> B1676_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `B1677`"] pub type B1677_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1677`"] pub struct B1677_W<'a> { w: &'a mut W, } impl<'a> B1677_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `B1678`"] pub type B1678_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1678`"] pub struct B1678_W<'a> { w: &'a mut W, } impl<'a> B1678_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `B1679`"] pub type B1679_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1679`"] pub struct B1679_W<'a> { w: &'a mut W, } impl<'a> B1679_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `B1680`"] pub type B1680_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1680`"] pub struct B1680_W<'a> { w: &'a mut W, } impl<'a> B1680_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `B1681`"] pub type B1681_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1681`"] pub struct B1681_W<'a> { w: &'a mut W, } impl<'a> B1681_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `B1682`"] pub type B1682_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1682`"] pub struct B1682_W<'a> { w: &'a mut W, } impl<'a> B1682_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `B1683`"] pub type B1683_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1683`"] pub struct B1683_W<'a> { w: &'a mut W, } impl<'a> B1683_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `B1684`"] pub type B1684_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1684`"] pub struct B1684_W<'a> { w: &'a mut W, } impl<'a> B1684_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `B1685`"] pub type B1685_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1685`"] pub struct B1685_W<'a> { w: &'a mut W, } impl<'a> B1685_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `B1686`"] pub type B1686_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1686`"] pub struct B1686_W<'a> { w: &'a mut W, } impl<'a> B1686_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `B1687`"] pub type B1687_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1687`"] pub struct B1687_W<'a> { w: &'a mut W, } impl<'a> B1687_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `B1688`"] pub type B1688_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1688`"] pub struct B1688_W<'a> { w: &'a mut W, } impl<'a> B1688_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `B1689`"] pub type B1689_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1689`"] pub struct B1689_W<'a> { w: &'a mut W, } impl<'a> B1689_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `B1690`"] pub type B1690_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1690`"] pub struct B1690_W<'a> { w: &'a mut W, } impl<'a> B1690_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `B1691`"] pub type B1691_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1691`"] pub struct B1691_W<'a> { w: &'a mut W, } impl<'a> B1691_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `B1692`"] pub type B1692_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1692`"] pub struct B1692_W<'a> { w: &'a mut W, } impl<'a> B1692_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `B1693`"] pub type B1693_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1693`"] pub struct B1693_W<'a> { w: &'a mut W, } impl<'a> B1693_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `B1694`"] pub type B1694_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1694`"] pub struct B1694_W<'a> { w: &'a mut W, } impl<'a> B1694_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `B1695`"] pub type B1695_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1695`"] pub struct B1695_W<'a> { w: &'a mut W, } impl<'a> B1695_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - B1664"] #[inline(always)] pub fn b1664(&self) -> B1664_R { B1664_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - B1665"] #[inline(always)] pub fn b1665(&self) -> B1665_R { B1665_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - B1666"] #[inline(always)] pub fn b1666(&self) -> B1666_R { B1666_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - B1667"] #[inline(always)] pub fn b1667(&self) -> B1667_R { B1667_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - B1668"] #[inline(always)] pub fn b1668(&self) -> B1668_R { B1668_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - B1669"] #[inline(always)] pub fn b1669(&self) -> B1669_R { B1669_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - B1670"] #[inline(always)] pub fn b1670(&self) -> B1670_R { B1670_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - B1671"] #[inline(always)] pub fn b1671(&self) -> B1671_R { B1671_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - B1672"] #[inline(always)] pub fn b1672(&self) -> B1672_R { B1672_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - B1673"] #[inline(always)] pub fn b1673(&self) -> B1673_R { B1673_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - B1674"] #[inline(always)] pub fn b1674(&self) -> B1674_R { B1674_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - B1675"] #[inline(always)] pub fn b1675(&self) -> B1675_R { B1675_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - B1676"] #[inline(always)] pub fn b1676(&self) -> B1676_R { B1676_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - B1677"] #[inline(always)] pub fn b1677(&self) -> B1677_R { B1677_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - B1678"] #[inline(always)] pub fn b1678(&self) -> B1678_R { B1678_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - B1679"] #[inline(always)] pub fn b1679(&self) -> B1679_R { B1679_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - B1680"] #[inline(always)] pub fn b1680(&self) -> B1680_R { B1680_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - B1681"] #[inline(always)] pub fn b1681(&self) -> B1681_R { B1681_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - B1682"] #[inline(always)] pub fn b1682(&self) -> B1682_R { B1682_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - B1683"] #[inline(always)] pub fn b1683(&self) -> B1683_R { B1683_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - B1684"] #[inline(always)] pub fn b1684(&self) -> B1684_R { B1684_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - B1685"] #[inline(always)] pub fn b1685(&self) -> B1685_R { B1685_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - B1686"] #[inline(always)] pub fn b1686(&self) -> B1686_R { B1686_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - B1687"] #[inline(always)] pub fn b1687(&self) -> B1687_R { B1687_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - B1688"] #[inline(always)] pub fn b1688(&self) -> B1688_R { B1688_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - B1689"] #[inline(always)] pub fn b1689(&self) -> B1689_R { B1689_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - B1690"] #[inline(always)] pub fn b1690(&self) -> B1690_R { B1690_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - B1691"] #[inline(always)] pub fn b1691(&self) -> B1691_R { B1691_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - B1692"] #[inline(always)] pub fn b1692(&self) -> B1692_R { B1692_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - B1693"] #[inline(always)] pub fn b1693(&self) -> B1693_R { B1693_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - B1694"] #[inline(always)] pub fn b1694(&self) -> B1694_R { B1694_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - B1695"] #[inline(always)] pub fn b1695(&self) -> B1695_R { B1695_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - B1664"] #[inline(always)] pub fn b1664(&mut self) -> B1664_W { B1664_W { w: self } } #[doc = "Bit 1 - B1665"] #[inline(always)] pub fn b1665(&mut self) -> B1665_W { B1665_W { w: self } } #[doc = "Bit 2 - B1666"] #[inline(always)] pub fn b1666(&mut self) -> B1666_W { B1666_W { w: self } } #[doc = "Bit 3 - B1667"] #[inline(always)] pub fn b1667(&mut self) -> B1667_W { B1667_W { w: self } } #[doc = "Bit 4 - B1668"] #[inline(always)] pub fn b1668(&mut self) -> B1668_W { B1668_W { w: self } } #[doc = "Bit 5 - B1669"] #[inline(always)] pub fn b1669(&mut self) -> B1669_W { B1669_W { w: self } } #[doc = "Bit 6 - B1670"] #[inline(always)] pub fn b1670(&mut self) -> B1670_W { B1670_W { w: self } } #[doc = "Bit 7 - B1671"] #[inline(always)] pub fn b1671(&mut self) -> B1671_W { B1671_W { w: self } } #[doc = "Bit 8 - B1672"] #[inline(always)] pub fn b1672(&mut self) -> B1672_W { B1672_W { w: self } } #[doc = "Bit 9 - B1673"] #[inline(always)] pub fn b1673(&mut self) -> B1673_W { B1673_W { w: self } } #[doc = "Bit 10 - B1674"] #[inline(always)] pub fn b1674(&mut self) -> B1674_W { B1674_W { w: self } } #[doc = "Bit 11 - B1675"] #[inline(always)] pub fn b1675(&mut self) -> B1675_W { B1675_W { w: self } } #[doc = "Bit 12 - B1676"] #[inline(always)] pub fn b1676(&mut self) -> B1676_W { B1676_W { w: self } } #[doc = "Bit 13 - B1677"] #[inline(always)] pub fn b1677(&mut self) -> B1677_W { B1677_W { w: self } } #[doc = "Bit 14 - B1678"] #[inline(always)] pub fn b1678(&mut self) -> B1678_W { B1678_W { w: self } } #[doc = "Bit 15 - B1679"] #[inline(always)] pub fn b1679(&mut self) -> B1679_W { B1679_W { w: self } } #[doc = "Bit 16 - B1680"] #[inline(always)] pub fn b1680(&mut self) -> B1680_W { B1680_W { w: self } } #[doc = "Bit 17 - B1681"] #[inline(always)] pub fn b1681(&mut self) -> B1681_W { B1681_W { w: self } } #[doc = "Bit 18 - B1682"] #[inline(always)] pub fn b1682(&mut self) -> B1682_W { B1682_W { w: self } } #[doc = "Bit 19 - B1683"] #[inline(always)] pub fn b1683(&mut self) -> B1683_W { B1683_W { w: self } } #[doc = "Bit 20 - B1684"] #[inline(always)] pub fn b1684(&mut self) -> B1684_W { B1684_W { w: self } } #[doc = "Bit 21 - B1685"] #[inline(always)] pub fn b1685(&mut self) -> B1685_W { B1685_W { w: self } } #[doc = "Bit 22 - B1686"] #[inline(always)] pub fn b1686(&mut self) -> B1686_W { B1686_W { w: self } } #[doc = "Bit 23 - B1687"] #[inline(always)] pub fn b1687(&mut self) -> B1687_W { B1687_W { w: self } } #[doc = "Bit 24 - B1688"] #[inline(always)] pub fn b1688(&mut self) -> B1688_W { B1688_W { w: self } } #[doc = "Bit 25 - B1689"] #[inline(always)] pub fn b1689(&mut self) -> B1689_W { B1689_W { w: self } } #[doc = "Bit 26 - B1690"] #[inline(always)] pub fn b1690(&mut self) -> B1690_W { B1690_W { w: self } } #[doc = "Bit 27 - B1691"] #[inline(always)] pub fn b1691(&mut self) -> B1691_W { B1691_W { w: self } } #[doc = "Bit 28 - B1692"] #[inline(always)] pub fn b1692(&mut self) -> B1692_W { B1692_W { w: self } } #[doc = "Bit 29 - B1693"] #[inline(always)] pub fn b1693(&mut self) -> B1693_W { B1693_W { w: self } } #[doc = "Bit 30 - B1694"] #[inline(always)] pub fn b1694(&mut self) -> B1694_W { B1694_W { w: self } } #[doc = "Bit 31 - B1695"] #[inline(always)] pub fn b1695(&mut self) -> B1695_W { B1695_W { w: self } } }
use super::RectTransform; use crate::codec::{Decode, Encode}; use crate::{remote_type, RemoteEnum, RemoteObject, Vector3}; remote_type!( /// A text label. object UI.Text { properties: { { RectTransform { /// Returns the rect transform for the text. /// /// **Game Scenes**: All get: rect_transform -> RectTransform } } { Visible { /// Returns whether the UI object is visible. /// /// **Game Scenes**: All get: is_visible -> bool, /// Sets whether the UI object is visible. /// /// **Game Scenes**: All set: set_visible(bool) } } { Content { /// Returns the text string. /// /// **Game Scenes**: All get: content -> String, /// Sets the text string. /// /// **Game Scenes**: All set: set_content(&str) } } { Font { /// Returns the name of the font. /// /// **Game Scenes**: All get: font -> String, /// Sets the name of the font. /// /// **Game Scenes**: All set: set_font(&str) } } { AvailableFonts { /// Returns a list of all available fonts. /// /// **Game Scenes**: All get: available_fonts -> Vec<String> } } { Size { /// Returns the font size. /// /// **Game Scenes**: All get: size -> i32, /// Sets the font size. /// /// **Game Scenes**: All set: set_size(i32) } } { FontStyle { /// Returns the font style. /// /// **Game Scenes**: All get: font_style -> FontStyle, /// Sets the font style. /// /// **Game Scenes**: All set: set_font_style(FontStyle) } } { Color { /// Returns the color. /// /// **Game Scenes**: All get: color -> Vector3, /// Sets the color. /// /// **Game Scenes**: All set: set_color(Vector3) } } { Alignment { /// Returns the text alignment. /// /// **Game Scenes**: All get: alignment -> TextAnchor, /// Sets the text alignment. /// /// **Game Scenes**: All set: set_alignment(TextAnchor) } } { LineSpacing { /// Returns the line spacing. /// /// **Game Scenes**: All get: line_spacing -> f32, /// Sets the line spacing. /// /// **Game Scenes**: All set: set_line_spacing(f32) } } } methods: { { /// Remove the UI object. /// /// **Game Scenes**: All fn remove() { Remove() } } } }); remote_type!( /// Font Style. enum FontStyle { /// Normal. Normal = 0, /// Bold. Bold = 1, /// Italic. Italic = 2, /// Bold and Italic. BoldAndItalic = 3, } ); remote_type!( /// Text alignment. enum TextAlignment { /// Left aligned. Left = 0, /// Right aligned. Right = 1, /// Center aligned. Center = 2, } ); remote_type!( /// Text anchor. enum TextAnchor { /// Lower center. LowerCenter = 0, /// Lower left. LowerLeft = 1, /// Lower right. LowerRight = 2, /// Middle center. MiddleCenter = 3, /// Middle left. MiddleLeft = 4, /// Middle right. MiddleRight = 5, /// Upper center. UpperCenter = 6, /// Upper left. UpperLeft = 7, /// Upper right. UpperRight = 8, } );
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_catalog::table_context::TableContext; use common_exception::Result; use common_expression::DataBlock; use common_expression::TableSchemaRef; use common_meta_store::MetaStore; use common_meta_types::MatchSeq; use common_meta_types::SeqV; use common_pipeline_core::processors::port::InputPort; use common_pipeline_core::processors::processor::ProcessorPtr; use common_pipeline_sinks::AsyncMpscSink; use common_pipeline_sinks::AsyncMpscSinker; use common_storage::DataOperator; use super::writer::ResultCacheWriter; use crate::common::gen_result_cache_dir; use crate::common::gen_result_cache_meta_key; use crate::common::ResultCacheValue; use crate::meta_manager::ResultCacheMetaManager; pub struct WriteResultCacheSink { ctx: Arc<dyn TableContext>, sql: String, partitions_shas: Vec<String>, meta_mgr: ResultCacheMetaManager, meta_key: String, cache_writer: ResultCacheWriter, } #[async_trait::async_trait] impl AsyncMpscSink for WriteResultCacheSink { const NAME: &'static str = "WriteResultCacheSink"; #[async_trait::unboxed_simple] async fn consume(&mut self, block: DataBlock) -> Result<bool> { if !self.cache_writer.over_limit() { self.cache_writer.append_block(block); Ok(false) } else { // Finish the cache writing pipeline. Ok(true) } } async fn on_finish(&mut self) -> Result<()> { if self.cache_writer.over_limit() { return Ok(()); } // 1. Write the result cache to the storage. let location = self.cache_writer.write_to_storage().await?; // 2. Set result cache key-value pair to meta. let now = SeqV::<()>::now_ms() / 1000; let ttl = self.meta_mgr.get_ttl(); let expire_at = now + ttl; let value = ResultCacheValue { sql: self.sql.clone(), query_id: self.ctx.get_id(), query_time: now, ttl, partitions_shas: self.partitions_shas.clone(), result_size: self.cache_writer.current_bytes(), num_rows: self.cache_writer.num_rows(), location, }; self.meta_mgr .set(self.meta_key.clone(), value, MatchSeq::GE(0), expire_at) .await?; self.ctx .set_query_id_result_cache(self.ctx.get_id(), self.meta_key.clone()); Ok(()) } } impl WriteResultCacheSink { pub fn try_create( ctx: Arc<dyn TableContext>, key: &str, schema: TableSchemaRef, inputs: Vec<Arc<InputPort>>, kv_store: Arc<MetaStore>, ) -> Result<ProcessorPtr> { let settings = ctx.get_settings(); let max_bytes = settings.get_query_result_cache_max_bytes()?; let ttl = settings.get_query_result_cache_ttl_secs()?; let tenant = ctx.get_tenant(); let sql = ctx.get_query_str(); let partitions_shas = ctx.get_partitions_shas(); let meta_key = gen_result_cache_meta_key(&tenant, key); let location = gen_result_cache_dir(key); let operator = DataOperator::instance().operator(); let cache_writer = ResultCacheWriter::create(schema, location, operator, max_bytes); Ok(ProcessorPtr::create(Box::new(AsyncMpscSinker::create( inputs, WriteResultCacheSink { ctx, sql, partitions_shas, meta_mgr: ResultCacheMetaManager::create(kv_store, ttl), meta_key, cache_writer, }, )))) } }
//Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } } struct Solution {} use std::cell::Cell; use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn longest_univalue_path(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { if let Some(node) = root { let val = node.borrow().val; let mut max_l = Cell::new(0); let r = Option::Some(node); Self::get_max_l(&r, val, &mut max_l); return max_l.get(); }; return 0; } fn get_max_l(r: &Option<Rc<RefCell<TreeNode>>>, val: i32, max_l: &mut Cell<i32>) -> i32 { return match r { None => 0, Some(r) => { let node = r.borrow(); let val2 = node.val; let left = Solution::get_max_l(&node.left, val2, max_l); let right = Solution::get_max_l(&node.right, val2, max_l); // 路径长度为节点数减1所以此处不加1 max_l.set(max_l.get().max(left + right)); // 和父节点值相同才返回以当前节点所能构成的最长通知路径长度, 否则返回0 if val2 == val { return left.max(right) + 1; } else { return 0; } } }; } } fn main() { let n = TreeNode::new(5); let node = Option::Some(Rc::new(RefCell::new(n))); let result = Solution::longest_univalue_path(node); println!("{:?}", result); }
use ::{ grammar, translate, PegCompiler }; fn compile(src: &str) -> PegCompiler { let mut compiler = PegCompiler::new(); let file = compiler.codemap.add_file("input.test".into(), src.into()); let ast_items = grammar::items(&file.source(), file.span).unwrap(); translate::Grammar::from_ast(&mut compiler, ast_items).unwrap(); compiler } #[test] fn test_finds_left_recursion() { let compiler = compile(r#" foo = "foo" foo / bar bar = "bar" bar / foo "#); assert_eq!(compiler.diagnostics[0].message, "Found illegal left recursion for rule foo: foo -> bar -> foo"); assert_eq!(compiler.diagnostics[1].message, "Found illegal left recursion for rule bar: bar -> foo -> bar"); assert_eq!(compiler.diagnostics.len(), 2); } #[test] fn test_finds_direct_left_recursion() { let compiler = compile(r#" foo = foo "#); assert_eq!(compiler.diagnostics[0].message, "Found illegal left recursion for rule foo: foo -> foo"); assert_eq!(compiler.diagnostics.len(), 1); }
use std::time::Duration; use alacritty_config_derive::ConfigDeserialize; use alacritty_terminal::config::Program; use alacritty_terminal::term::color::Rgb; #[derive(ConfigDeserialize, Clone, Debug, PartialEq, Eq)] pub struct BellConfig { /// Visual bell animation function. pub animation: BellAnimation, /// Command to run on bell. pub command: Option<Program>, /// Visual bell flash color. pub color: Rgb, /// Visual bell duration in milliseconds. duration: u16, } impl Default for BellConfig { fn default() -> Self { Self { color: Rgb::new(255, 255, 255), animation: Default::default(), command: Default::default(), duration: Default::default(), } } } impl BellConfig { pub fn duration(&self) -> Duration { Duration::from_millis(self.duration as u64) } } /// `VisualBellAnimations` are modeled after a subset of CSS transitions and Robert /// Penner's Easing Functions. #[derive(ConfigDeserialize, Default, Clone, Copy, Debug, PartialEq, Eq)] pub enum BellAnimation { // CSS animation. Ease, // CSS animation. EaseOut, // Penner animation. EaseOutSine, // Penner animation. EaseOutQuad, // Penner animation. EaseOutCubic, // Penner animation. EaseOutQuart, // Penner animation. EaseOutQuint, // Penner animation. #[default] EaseOutExpo, // Penner animation. EaseOutCirc, // Penner animation. Linear, }
// Copyright 2018 Steve Smith (tarkasteve@gmail.com). See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use cfg_if::cfg_if; cfg_if! { if #[cfg(any(target_os = "linux", target_os = "android"))] { mod sparse; pub use self::sparse::copy; } else { pub use std::fs::copy; } } pub mod util;
use xshell::{Shell, cmd}; fn main() { let sh = Shell::new().unwrap(); let stdout = cmd!(sh, "echo hello world").read().unwrap(); print!("{}\n", stdout) }
use super::Intersects; use super::aabb::{Aabb2, Aabb3}; use cgmath::{Point, Point2, Point3}; use cgmath::{Vector3, Vector2}; #[test] fn test_aabb2_collide() { let a = Aabb2::new(Point2::new(0f32, 0.), Point2::new(1f32, 1.)); let table = [(Point2::new(0.9f32, 0.9f32), true), (Point2::new(0.9f32, 1.1f32), false), (Point2::new(1.1f32, 0.9f32), false), (Point2::new(1.1f32, 1.1f32), false), (Point2::new(-1.1f32, -1.1f32), false), (Point2::new(-0.9f32, -1.1f32), false), (Point2::new(-1.1f32, -0.9f32), false), (Point2::new(-0.9f32, -0.9f32), true)]; for &(point, should_intersect) in table.iter() { let b = Aabb2::new(point, point.add_v(&Vector2::new(1f32, 1f32))); assert!(a.intersect(&b) == should_intersect); } } #[test] fn test_aabb3_collide() { let a = Aabb3::new(Point3::new(0f32, 0., 0.), Point3::new(1f32, 1., 1.)); let table = [(Point3::new(0.9f32, 0.9f32, 0.9f32), true), (Point3::new(0.9f32, 1.1f32, 0.9f32), false), (Point3::new(1.1f32, 0.9f32, 0.9f32), false), (Point3::new(1.1f32, 1.1f32, 0.9f32), false), (Point3::new(0.9f32, 0.9f32, 1.1f32), false), (Point3::new(0.9f32, 1.1f32, 1.1f32), false), (Point3::new(1.1f32, 0.9f32, 1.1f32), false), (Point3::new(1.1f32, 1.1f32, 1.1f32), false), (Point3::new(-1.1f32, -1.1f32, -1.1f32), false), (Point3::new(-0.9f32, -1.1f32, -1.1f32), false), (Point3::new(-1.1f32, -0.9f32, -1.1f32), false), (Point3::new(-0.9f32, -0.9f32, -1.1f32), false), (Point3::new(-1.1f32, -1.1f32, -0.9f32), false), (Point3::new(-0.9f32, -1.1f32, -0.9f32), false), (Point3::new(-1.1f32, -0.9f32, -0.9f32), false), (Point3::new(-0.9f32, -0.9f32, -0.9f32), true)]; for &(point, should_intersect) in table.iter() { let b = Aabb3::new(point, point.add_v(&Vector3::new(1f32, 1f32, 1f32))); assert!(a.intersect(&b) == should_intersect); } } #[test] fn test_point2_collide() { let a = Point2::new(1f32, 1f32); let table = [(Point2::new(1f32, 1f32), true), (Point2::new(0f32, 1f32), false), (Point2::new(1f32, 0f32), false), (Point2::new(0f32, 0f32), false)]; for &(point, should_intersect) in table.iter() { assert!(a.intersect(&point) == should_intersect); } } #[test] fn test_point3_collide() { let a = Point3::new(1f32, 1f32, 1f32); let table = [(Point3::new(1f32, 1f32, 1f32), true), (Point3::new(0f32, 1f32, 1f32), false), (Point3::new(1f32, 0f32, 1f32), false), (Point3::new(0f32, 0f32, 1f32), false), (Point3::new(1f32, 1f32, 0f32), false), (Point3::new(0f32, 1f32, 0f32), false), (Point3::new(1f32, 0f32, 0f32), false), (Point3::new(0f32, 0f32, 0f32), false)]; for &(point, should_intersect) in table.iter() { assert!(a.intersect(&point) == should_intersect); } } mod sparse { use super::super::aabb::Aabb3; use super::super::octtree::Sparse; use cgmath::Point3; static size: int = 5; #[test] fn test_insert_points() { let mut oct: Sparse<f32, Point3<f32>, (int, int, int)> = Sparse::new(size as f32, 8); for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Point3::new(x as f32, y as f32, z as f32); oct.insert(point, (x, y, z)); } } } for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Point3::new(x as f32, y as f32, z as f32); oct.quary(&point, |_, value| { assert!(*value == (x, y, z)); }); } } } } #[test] fn test_remove_points() { let mut oct: Sparse<f32, Point3<f32>, (int, int, int)> = Sparse::new(size as f32, 8); for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Point3::new(x as f32, y as f32, z as f32); oct.insert(point, (x, y, z)); } } } for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Point3::new(x as f32, y as f32, z as f32); oct.quary(&point, |_, value| { assert!(*value == (x, y, z)); }); } } } for x in range(0, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Point3::new(x as f32, y as f32, z as f32); oct.remove(point); } } } for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Point3::new(x as f32, y as f32, z as f32); oct.quary(&point, |_, value| { let (x, _, _) = *value; assert!(x < 0); }); } } } } #[test] fn test_insert_aabb() { let mut oct: Sparse<f32, Aabb3<f32>, (int, int, int)> = Sparse::new((8*size) as f32, 8); for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Aabb3::new(Point3::new((5*x-1) as f32, (5*y-1) as f32, (5*z-1) as f32), Point3::new((5*x+1) as f32, (5*y+1) as f32, (5*z+1) as f32)); oct.insert(point, (x, y, z)); } } } for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Aabb3::new(Point3::new((5*x-1) as f32, (5*y-1) as f32, (5*z-1) as f32), Point3::new((5*x+1) as f32, (5*y+1) as f32, (5*z+1) as f32)); oct.quary(&point, |_, value| { assert!(*value == (x, y, z)); }); } } } } #[test] fn test_remove_aabb() { let mut oct: Sparse<f32, Aabb3<f32>, (int, int, int)> = Sparse::new((8*size) as f32, 8); for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Aabb3::new(Point3::new((5*x-1) as f32, (5*y-1) as f32, (5*z-1) as f32), Point3::new((5*x+1) as f32, (5*y+1) as f32, (5*z+1) as f32)); oct.insert(point, (x, y, z)); } } } for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Aabb3::new(Point3::new((5*x-1) as f32, (5*y-1) as f32, (5*z-1) as f32), Point3::new((5*x+1) as f32, (5*y+1) as f32, (5*z+1) as f32)); oct.quary(&point, |_, value| { assert!(*value == (x, y, z)); }); } } } for x in range(0, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Aabb3::new(Point3::new((5*x-1) as f32, (5*y-1) as f32, (5*z-1) as f32), Point3::new((5*x+1) as f32, (5*y+1) as f32, (5*z+1) as f32)); oct.remove(point); } } } for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Aabb3::new(Point3::new(x as f32, y as f32, z as f32), Point3::new(x as f32 + 0.1, y as f32 + 0.1, z as f32 + 0.1)); oct.quary(&point, |_, value| { let (x, _, _) = *value; assert!(x < 0); }); } } } } } mod linear { use super::super::aabb::Aabb3; use super::super::octtree::Linear; use cgmath::Point3; static size: int = 3; #[test] fn test_insert_points() { let mut oct: Linear<f32, Point3<f32>, (int, int, int)> = Linear::new(size as f32, 3); for x in range(-size, size) { for y in range(-size, size) { for z in range(-size, size) { let point = Point3::new((x+1) as f32 , (y+1) as f32 , (z+1) as f32 ); oct.insert(point, (x, y, z)); } } } for x in range(-size, size) { for y in range(-size, size) { for z in range(-size, size) { let point = Point3::new((x+1) as f32 , (y+1) as f32 , (z+1) as f32 ); oct.quary(&point, |_, value| { assert!((x, y, z) == *value); }); } } } } #[test] fn test_insert_aabb() { let mut oct: Linear<f32, Aabb3<f32>, (int, int, int)> = Linear::new((5*size) as f32, 3); for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Aabb3::new(Point3::new((5*x) as f32, (5*y) as f32, (5*z) as f32), Point3::new((5*x+1) as f32, (5*y+1) as f32, (5*z+1) as f32)); oct.insert(point, (x, y, z)); } } } for x in range(-size, size+1) { for y in range(-size, size+1) { for z in range(-size, size+1) { let point = Aabb3::new(Point3::new((5*x) as f32, (5*y) as f32, (5*z) as f32), Point3::new((5*x+1) as f32, (5*y+1) as f32, (5*z+1) as f32)); oct.quary(&point, |_, value| { assert!(*value == (x, y, z)); }); } } } } } mod bvh { use std::collections::HashSet; use std::iter::range_inclusive; use cgmath::Point3; use cgmath::Vector3; use super::super::sphere::Sphere; use super::super::aabb::Aabb3; use super::super::bvh::{BvhBuilder, ToMorton}; use super::super::Intersects; use test::Bencher; static size: int = 10; #[test] fn test_to_morton3() { let base = Point3::new(0f32, 0., 0.); let scale = Vector3::new(1023f32, 1023., 1023.); let full = Point3::new(1f32, 1f32, 1f32); let zero = Point3::new(0f32, 0f32, 0f32); let half = Point3::new(0.5f32, 0.5f32, 0.5f32); let x_full = Point3::new(1f32, 0f32, 0f32); let y_full = Point3::new(0f32, 1f32, 0f32); let z_full = Point3::new(0f32, 0f32, 1f32); assert!(0b111_111_111_111_111_111_111_111_111_111 == full.to_morton(&base, &scale)); assert!(0b000_000_000_000_000_000_000_000_000_000 == zero.to_morton(&base, &scale)); assert!(0b000_111_111_111_111_111_111_111_111_111 == half.to_morton(&base, &scale)); assert!(0b001_001_001_001_001_001_001_001_001_001 == z_full.to_morton(&base, &scale)); assert!(0b010_010_010_010_010_010_010_010_010_010 == y_full.to_morton(&base, &scale)); assert!(0b100_100_100_100_100_100_100_100_100_100 == x_full.to_morton(&base, &scale)); } #[test] fn test_aabb_bvh_build() { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let aabb = Aabb3::new(Point3::new(xf-0.25, yf-0.25, zf-0.25), Point3::new(zf+0.25, yf+0.25, zf+0.25)); builder.add(aabb, (x, y, x)); } } } let _ = builder.build(); } #[test] fn test_aabb_bvh_collide_all() { let mut set = HashSet::new(); let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let aabb = Aabb3::new(Point3::new(xf-0.25, yf-0.25, zf-0.25), Point3::new(zf+0.25, yf+0.25, zf+0.25)); builder.add(aabb, (x, y, z)); set.insert((x, y, z)); } } } let aabb = Aabb3::new(Point3::new(-size as f32, -size as f32, -size as f32), Point3::new(size as f32, size as f32, size as f32)); let bvh = builder.build(); for (_, dat) in bvh.collision_iter(&aabb) { assert!(set.remove(dat)); } assert!(set.len() == 0); } #[test] fn test_aabb_bvh_collide_half() { let mut set = HashSet::new(); let mut builder = BvhBuilder::new(); let check = Aabb3::new(Point3::new(0. as f32, 0. as f32, 0. as f32), Point3::new(size as f32, size as f32, size as f32)); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let aabb = Aabb3::new(Point3::new(xf-0.25, yf-0.25, zf-0.25), Point3::new(zf+0.25, yf+0.25, zf+0.25)); builder.add(aabb, (x, y, z)); if aabb.intersect(&check) { set.insert((x, y, z)); } } } } let bvh = builder.build(); for (_, dat) in bvh.collision_iter(&check) { assert!(set.remove(dat)); } assert!(set.len() == 0); } #[test] fn test_sphere_bvh_build() { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let sphere = Sphere::new(Point3::new(xf, yf, zf), 0.25); builder.add(sphere, (x, y, x)); } } } let _ = builder.build(); } #[test] fn test_sphere_bvh_collide_all() { let mut set = HashSet::new(); let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let sphere = Sphere::new(Point3::new(xf, yf, zf), 0.25); builder.add(sphere, (x, y, z)); set.insert((x, y, z)); } } } let sphere = Sphere::new(Point3::new(0f32, 0f32, 0f32), ((size*size + size*size + size*size) as f32).sqrt()); let bvh = builder.build(); for (_, dat) in bvh.collision_iter(&sphere) { assert!(set.remove(dat)); } assert!(set.len() == 0); } #[test] fn test_sphere_bvh_collide_half() { let mut set = HashSet::new(); let mut builder = BvhBuilder::new(); let check = Sphere::new(Point3::new(0f32, 0f32, 0f32), 0.5 * ((size*size + size*size + size*size) as f32).sqrt()); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let sphere = Sphere::new(Point3::new(xf, yf, zf), 0.25); builder.add(sphere, (x, y, z)); if sphere.intersect(&check) { set.insert((x, y, z)); } } } } let bvh = builder.build(); for (_, dat) in bvh.collision_iter(&check) { assert!(set.remove(dat)); } assert!(set.len() == 0); } #[bench] fn bench_aabb_build(bench: &mut Bencher) { bench.iter(|| { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let aabb = Aabb3::new(Point3::new(xf-0.25, yf-0.25, zf-0.25), Point3::new(zf+0.25, yf+0.25, zf+0.25)); builder.add(aabb, (x, y, z)); } } } builder.build() }); } #[bench] fn bench_aabb_build_add_only(bench: &mut Bencher) { bench.iter(|| { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let aabb = Aabb3::new(Point3::new(xf-0.25, yf-0.25, zf-0.25), Point3::new(zf+0.25, yf+0.25, zf+0.25)); builder.add(aabb, (x, y, z)); } } } builder }); } #[bench] fn bench_aabb_iter_half(bench: &mut Bencher) { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let aabb = Aabb3::new(Point3::new(xf-0.25, yf-0.25, zf-0.25), Point3::new(zf+0.25, yf+0.25, zf+0.25)); builder.add(aabb, (x, y, z)); } } } let bvh = builder.build(); let check = Aabb3::new(Point3::new(0. as f32, 0. as f32, 0. as f32), Point3::new(size as f32, size as f32, size as f32)); bench.iter(|| { let mut sum = 0i; for (_, _) in bvh.collision_iter(&check) { sum += 1; } sum }); } #[bench] fn bench_aabb_iter_one(bench: &mut Bencher) { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let aabb = Aabb3::new(Point3::new(xf-0.25, yf-0.25, zf-0.25), Point3::new(zf+0.25, yf+0.25, zf+0.25)); builder.add(aabb, (x, y, z)); } } } let bvh = builder.build(); let check = Aabb3::new(Point3::new(0. as f32, 0. as f32, 0. as f32), Point3::new(1. as f32, 1. as f32, 1. as f32)); bench.iter(|| { let mut sum = 0i; for (_, _) in bvh.collision_iter(&check) { sum += 1; } sum }); } #[bench] fn bench_sphere_build(bench: &mut Bencher) { bench.iter(|| { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let sphere = Sphere::new(Point3::new(xf, yf, zf), 0.25); builder.add(sphere, (x, y, z)); } } } builder.build() }); } #[bench] fn bench_sphere_build_add_only(bench: &mut Bencher) { bench.iter(|| { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let sphere = Sphere::new(Point3::new(xf, yf, zf), 0.25); builder.add(sphere, (x, y, z)); } } } builder }); } #[bench] fn bench_sphere_iter_half(bench: &mut Bencher) { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let sphere = Sphere::new(Point3::new(xf, yf, zf), 0.25); builder.add(sphere, (x, y, z)); } } } let bvh = builder.build(); let check = Sphere::new(Point3::new(0. as f32, 0. as f32, 0. as f32), size as f32); bench.iter(|| { let mut sum = 0i; for (_, _) in bvh.collision_iter(&check) { sum += 1; } sum }); } #[bench] fn bench_sphere_iter_one(bench: &mut Bencher) { let mut builder = BvhBuilder::new(); for x in range_inclusive(-size, size) { for y in range_inclusive(-size, size) { for z in range_inclusive(-size, size) { let xf = x as f32; let yf = y as f32; let zf = z as f32; let sphere = Sphere::new(Point3::new(xf, yf, zf), 0.25); builder.add(sphere, (x, y, z)); } } } let bvh = builder.build(); let check = Sphere::new(Point3::new(0f32, 0f32, 0f32), 0.25); bench.iter(|| { let mut sum = 0i; for (_, _) in bvh.collision_iter(&check) { sum += 1; } sum }); } }
//! A library for generating prime numbers using a segmented sieve. mod iterator; mod segsieve; mod segment; mod sieve; mod wheel; pub use sieve::{Sieve, SieveIterator};
use std::fmt; use base32; pub struct Sequence { // TODO: make private pub fields: Vec<Vec<Field>>, } #[derive(Clone)] pub struct Field { pub note: Note, pub cmd: Command, } #[derive(Clone)] pub enum Note { On(u8), Off, Hold, } #[derive(Clone)] pub struct Command { pub id: u8, pub data: u8, } impl Sequence { pub fn new(fields: Vec<Vec<Field>>) -> Self { Sequence { fields: fields } } pub fn get_field(&self, row: usize, col: usize) -> &Field { &self.fields[row][col] } pub fn width(&self) -> usize { self.fields[0].len() } pub fn len(&self) -> usize { self.fields.len() } } impl fmt::Display for Field { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}{}{:02X}", self.note, self.cmd.id as char, self.cmd.data) } } impl ::std::ops::Add<u8> for Note { type Output = Note; fn add(self, with: u8) -> Note { match self { Note::On(v) => Note::On(v + with), _ => self } } } impl fmt::Display for Note { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Note::On(ref note) => { const NOTE_NAME: &'static str = "C-C#D-D#E-F-F#G-G#A-A#B-"; let name = *note as usize % 12; let octave = note / 12; write!(f, "{}{}", &NOTE_NAME[name*2..name*2+2], octave) } Note::Off => write!(f, "---"), Note::Hold => write!(f, " "), } } } impl Command { pub fn zero() -> Command { Command { id: '0' as u8, data: 0 } } pub fn from_str(raw: &str) -> Command { let mut chars = raw.chars(); Command { id: base32::from_char(chars.next().unwrap()).unwrap(), data: u8::from_str_radix(chars.as_str(), 16).unwrap(), } } pub fn hi(&self) -> u8 { self.data >> 4 } pub fn lo(&self) -> u8 { self.data & 0xf } pub fn set_hi(&mut self, v: u8) { self.data = self.lo() + (v << 4) } pub fn set_lo(&mut self, v: u8) { self.data = (self.data & 0xf0) + (v & 0xf) } }
pub mod model; pub use model::*; pub mod spotify;
use std::env; use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } fn main() { let args: Vec<String> = env::args().collect(); let mut records = Vec::new(); if let Ok(lines) = read_lines("./input.txt") { for line in lines { if let Ok(ip) = line { records.push(ip.parse::<i32>().unwrap()); } } } if args[1] == "1" { for (i, x) in records.iter().enumerate() { for j in (i + 1)..(records.len()) { if x + records[j] == 2020 { println!("{}", x * records[j]) } } } } else if args[1] == "2" { for (i, _) in records.iter().enumerate() { for j in (i + 1)..(records.len()) { for k in (j + 1)..(records.len()) { if records[i] + records[j] + records[k] == 2020 { println!("{}", records[i] * records[j] * records[k]) } } } } } }
use crate::cli; use crate::fs; pub fn run() { let masses: Vec<usize> = fs::read_lines(cli::aoc_filename("aoc_2019_01.txt"), |l| { l.parse::<usize>().unwrap() }) .unwrap(); let fuel: usize = masses.iter().map(needed_fuel).sum(); println!("Fuel needed: {}", fuel); let fuel: usize = masses.iter().map(actually_needed_fuel).sum(); println!("Fuel ACTUALLY needed: {}", fuel); } fn needed_fuel(mass: &usize) -> usize { mass / 3 - 2 } fn actually_needed_fuel(mass: &usize) -> usize { let mut curr = needed_fuel(mass); let mut total = curr; while curr > 8 { curr = needed_fuel(&curr); total += curr; } total } #[cfg(test)] mod tests { use super::*; #[test] fn part_one_mass_cases() { assert_eq!(needed_fuel(&12), 2); assert_eq!(needed_fuel(&14), 2); assert_eq!(needed_fuel(&1969), 654); assert_eq!(needed_fuel(&100756), 33583); } #[test] fn part_two_mass_cases() { assert_eq!(actually_needed_fuel(&14), 2); assert_eq!(actually_needed_fuel(&1969), 966); assert_eq!(actually_needed_fuel(&100756), 50346); } }
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use std::convert::TryInto; use anyhow::*; use liblumen_alloc::atom; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::{Monitor, Process}; use liblumen_alloc::erts::term::prelude::*; use crate::erlang::node_0; use crate::runtime::context::*; use crate::runtime::scheduler::SchedulerDependentAlloc; use crate::runtime::{process, registry}; const TYPE_CONTEXT: &str = "supported types are :port, :process, or :time_offset"; #[native_implemented::function(erlang:monitor/2)] pub fn result(process: &Process, r#type: Term, item: Term) -> exception::Result<Term> { let type_atom: Atom = r#type.try_into().context(TYPE_CONTEXT)?; match type_atom.name() { "port" => unimplemented!(), "process" => monitor_process_identifier(process, item), "time_offset" => unimplemented!(), name => Err(TryAtomFromTermError(name)) .context(TYPE_CONTEXT) .map_err(From::from), } } // Private fn monitor_process_identifier( process: &Process, process_identifier: Term, ) -> exception::Result<Term> { match process_identifier.decode()? { TypedTerm::Atom(atom) => Ok(monitor_process_registered_name( process, process_identifier, atom, )), TypedTerm::Pid(pid) => Ok(monitor_process_pid(process, process_identifier, pid)), TypedTerm::ExternalPid(_) => unimplemented!(), TypedTerm::Tuple(tuple) => monitor_process_tuple(process, process_identifier, &tuple), _ => Err(TypeError) .context(PROCESS_IDENTIFIER_CONTEXT) .map_err(From::from), } } fn monitor_process_identifier_noproc(process: &Process, identifier: Term) -> Term { let monitor_reference = process.next_reference(); let noproc_message = noproc_message(process, monitor_reference, identifier); process.send_from_self(noproc_message); monitor_reference } fn monitor_process_pid(process: &Process, process_identifier: Term, pid: Pid) -> Term { match registry::pid_to_process(&pid) { Some(monitored_arc_process) => process::monitor(process, &monitored_arc_process), None => monitor_process_identifier_noproc(process, process_identifier), } } fn monitor_process_registered_name( process: &Process, process_identifier: Term, atom: Atom, ) -> Term { match registry::atom_to_process(&atom) { Some(monitored_arc_process) => { let reference = process.next_reference(); let reference_reference: Boxed<Reference> = reference.try_into().unwrap(); let monitor = Monitor::Name { monitoring_pid: process.pid(), monitored_name: atom, }; process.monitor( reference_reference.as_ref().clone(), monitored_arc_process.pid(), ); monitored_arc_process.monitored(reference_reference.as_ref().clone(), monitor); reference } None => { let identifier = process.tuple_from_slice(&[process_identifier, node_0::result()]); monitor_process_identifier_noproc(process, identifier) } } } const PROCESS_IDENTIFIER_CONTEXT: &str = "process identifier must be `pid | registered_name() | {registered_name(), node()}`"; fn monitor_process_tuple( process: &Process, _process_identifier: Term, tuple: &Tuple, ) -> exception::Result<Term> { if tuple.len() == 2 { let registered_name = tuple[0]; let registered_name_atom = term_try_into_atom("registered name", registered_name)?; let node = tuple[1]; if node == node_0::result() { Ok(monitor_process_registered_name( process, registered_name, registered_name_atom, )) } else { let _: Atom = term_try_into_atom!(node)?; unimplemented!( "node ({:?}) is not the local node ({:?})", node, node_0::result() ); } } else { Err(anyhow!(PROCESS_IDENTIFIER_CONTEXT).into()) } } fn noproc_message(process: &Process, reference: Term, identifier: Term) -> Term { let noproc = atom!("noproc"); down_message(process, reference, identifier, noproc) } fn down_message(process: &Process, reference: Term, identifier: Term, info: Term) -> Term { let down = atom!("DOWN"); let r#type = atom!("process"); process.tuple_from_slice(&[down, reference, r#type, identifier, info]) }
//! A self balancing binary tree use std::cmp::{Ord, Ordering, max}; use std::mem::replace; use std::collections::VecDeque; struct AvlNode<K: Ord, V> { key: K, val: V, height: i32, left: AvlTree<K,V>, right: AvlTree<K,V> } /// A map based on a binary tree that self balances using the AVL algorithm pub struct AvlTree<K: Ord, V> (Option<Box<AvlNode<K,V>>>); /// A struct used to iterate over values of the AvlTree pub struct Iter<'a, K: 'a, V: 'a> { queue: VecDeque<(&'a K,&'a V)>, forwards: bool } impl<'a, K: 'a + Ord, V: 'a> Iter<'a,K, V> { ///creates an iterator containing all elements between start and end, inclusive, ///Unbounded if the None fn new(tree: &'a AvlTree<K,V>, start: Option<&K>, end: Option<&K>, forwards: bool) -> Self { let mut iter = Iter { queue: VecDeque::new(), forwards: forwards }; iter.init(tree, start, end); iter } fn init(&mut self, tree: &'a AvlTree<K,V>, start: Option<&K>, end: Option<&K>) { tree.0.as_ref().map(|node| { self.init(&node.left, start, end); if (start.is_none() || *start.unwrap() <= node.key) && (end.is_none() || *end.unwrap() >= node.key) { self.queue.push_back((&node.key,&node.val)); }; self.init(&node.right, start, end); 0 }); } } impl<'a, K: 'a + Ord , V: 'a> Iterator for Iter<'a,K, V> { type Item = (&'a K, &'a V); fn next(&mut self) -> Option<(&'a K, &'a V)> { if self.forwards { self.queue.pop_front() } else { self.queue.pop_back() } } } impl<K: Ord, V> AvlTree<K,V> { /// Returns the height of the tree. /// The height is defined as The number of Nodes /// on the longest path from the root to any leaf. /// Since the tree is self balancing, the height should /// be about log2(n) plus or minus 1 /// /// #Examples /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// /// assert_eq!(tree.height(),0); /// tree.insert(1,"a"); /// assert_eq!(tree.height(),1); /// tree.insert(2,"b"); /// assert_eq!(tree.height(),2); /// tree.insert(3,"c"); /// assert_eq!(tree.height(),2); /// tree.insert(4,"d"); /// assert_eq!(tree.height(),3); /// ``` pub fn height(&self) -> i32 { match self.0 { None => 0, Some(ref node) => node.height } } ///checks the balance of the tree from this node. ///the magnitude of the result idicates how unbalanced the tree is, ///with 0 being balanced, 1 being unbalance of 1, and so on. ///the sign indicates which direction the balance leans. ///Negative isa left leaning tree, positive is right leaning. fn check_balance(&self) -> i32 { match self.0 { None => 0, Some(ref node) => node.right.height() - node.left.height() } } ///updates this subtree's heights. returns the height of the tree after updating fn update_height(&mut self) -> i32{ match self.0 { None => 0, Some(ref mut node) => { node.height = max(node.left.update_height(),node.right.update_height()) + 1; node.height } } } ///updates this node's height. fn update_one_height(&mut self) { match self.0 { None => (), Some(ref mut node) => { node.height = max(node.left.height(),node.right.height()) + 1; } } } fn right_rot(&mut self) { //move gradparent out of self let mut grandparent_node = self.0.take(); //move left child out of grandparent let mut parent_node = grandparent_node.as_mut().unwrap().left.0.take(); //move parent's right to grandparent's left grandparent_node.as_mut().unwrap().left.0 = parent_node.as_mut().unwrap().right.0.take(); //move grandparent to parent's right parent_node.as_mut().unwrap().right.0 = grandparent_node; //move parent into self self.0 = parent_node; //update heights based on new positions self.update_height(); } fn left_rot(&mut self) { let mut grandparent_node = self.0.take(); let mut parent_node = grandparent_node.as_mut().unwrap().right.0.take(); grandparent_node.as_mut().unwrap().right.0 = parent_node.as_mut().unwrap().left.0.take(); parent_node.as_mut().unwrap().left.0 = grandparent_node; self.0 = parent_node; self.update_height(); } fn right_left_rot(&mut self) { self.0.as_mut().unwrap().right.right_rot(); self.left_rot(); } fn left_right_rot(&mut self) { self.0.as_mut().unwrap().left.left_rot(); self.right_rot(); } fn rebalance(&mut self) { //check balance let balance = self.check_balance(); //too left leaning if balance == -2 { //if left subtree is left leaning or balanced, then right rotate, else //left-right rotate if self.0.as_mut().unwrap().left.check_balance() <= 0 { self.right_rot(); } else { self.left_right_rot(); } } //too right leaning else if balance == 2 { if self.0.as_mut().unwrap().right.check_balance() >= 0 { self.left_rot(); } else { self.right_left_rot(); } }; //else balanced, nothing to do //update heights, not using update_height method to not do unneccesary recursions self.update_one_height(); } /// Creates a new empty AvlTree /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// /// tree.insert(1,"a"); /// ``` pub fn new() -> Self { AvlTree(None as Option<Box<AvlNode<K,V>>>) } /// Inserts a key,value pair into the tree. Returns None if the key was /// not present in the tree already. If the key was present, then the key is updated /// with the new value and the old value is returned. /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// /// assert_eq!(tree.insert(37, "a"), None); /// assert_eq!(tree.is_empty(), false); /// /// tree.insert(37, "b"); /// assert_eq!(tree.insert(37, "c"), Some("b")); /// assert_eq!(tree.get(&37), Some(&"c")); pub fn insert(&mut self, key: K, val: V) -> Option<V> { let result = match self.0 { //if there is no data here, insert the key-value pair here and return None None => { self.0 = Some(Box::new(AvlNode { key: key, val: val, height: 1, left: AvlTree::new(), right: AvlTree::new() })); None } Some(ref mut root) => { //if key exists, swap out values, return old value if key == root.key { Some(replace(&mut root.val,val)) } //go left else if key < root.key { root.left.insert(key,val) } //go right else { root.right.insert(key,val) } } }; self.rebalance(); result } /// checks if the tree is empty. /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// /// assert!(tree.is_empty()); /// /// tree.insert("hello","world"); /// /// assert!(!tree.is_empty()); pub fn is_empty(&self) -> bool { self.0.is_none() } /// Takes a reference to something of type Key and /// returns None if the key is not present, or a reference to the /// value if the key is present /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// tree.insert(37, "b"); /// tree.insert(1,"a"); /// /// assert_eq!(tree.get(&1), Some(&"a")); /// assert_eq!(tree.get(&2), None); /// /// ``` pub fn get(&self, key: &K) -> Option<&V> { match self.0 { None => None, Some(ref node) => { if *key == node.key { Some(&node.val) } else if *key < node.key { node.left.get(key) } else { node.right.get(key) } } } } /// Takes a referenece to something of type Key and /// attempts to delete the key and its associated value /// from the tree. Returns None if the key was not present, /// and returns the value if the key was present. /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// tree.insert(37, "b"); /// tree.insert(1,"a"); /// /// assert_eq!(tree.remove(&1), Some("a")); /// assert!(!tree.contains_key(&1)); /// assert_eq!(tree.remove(&2), None); /// /// ``` pub fn remove(&mut self, key: &K) -> Option<V> { let (result, replacement) = match self.0.take() { None => (None, AvlTree(None) as AvlTree<K,V>), Some(mut node) => { match key.cmp(&node.key) { Ordering::Less => (node.left.remove(key), AvlTree(Some(node))), Ordering::Greater => (node.right.remove(key), AvlTree(Some(node))), Ordering::Equal => { let node = *node; let replacement = match (node.left.0, node.right.0) { //no subtrees, replacement is nothing (None,None) => AvlTree(None) as AvlTree<K,V>, //one subtree, replacement is the one subtree (Some(left),None) => AvlTree(Some(left)), (None,Some(right)) => AvlTree(Some(right)), //two subtrees, must move some thigns around to find a suitable //replacement (Some(left),Some(right)) => { let mut newright = AvlTree(Some(right)); let mut min = newright.take_min(); min.right = newright; min.left = AvlTree(Some(left)); AvlTree(Some(min)) } }; self.update_height(); (Some(node.val),replacement) } } } }; *self = replacement; self.rebalance(); result } fn take_min(&mut self) -> Box<AvlNode<K,V>> { let result = if self.0.as_ref().unwrap().left.is_empty() { let mut res = self.0.take().unwrap(); self.0 = res.right.0.take(); res } else { self.0.as_mut().unwrap().left.take_min() }; self.update_one_height(); result } /// Takes a referenece to something of type Key and /// checks if the key is present. /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// tree.insert(37, "b"); /// tree.insert(1,"a"); /// /// assert!(tree.contains_key(&1)); /// assert!(!tree.contains_key(&2)); /// pub fn contains_key(&self, key: &K) -> bool { match self.0 { None => false, Some(ref node) => { if *key == node.key { true } else if *key < node.key { node.left.contains_key(key) } else { node.right.contains_key(key) } } } } /// Gives an iterator over the key-value pairs in the tree, sorted by key. /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// tree.insert(37, "b"); /// tree.insert(1,"a"); /// /// assert_eq!(tree.iter().next().unwrap(), (&1, &"a")); /// pub fn iter(&self) -> Iter<K,V> { Iter::new(self, None, None, true) } /// Gives an iterator over the key-value pairs in the tree, sorted by key, in reverse order. /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// tree.insert(37, "b"); /// tree.insert(1,"a"); /// /// assert_eq!(tree.reverse_iter().next().unwrap(), (&37, &"b")); /// pub fn reverse_iter(&self) -> Iter<K,V> { Iter::new(self, None, None, false) } /// Gives an iterator over the key-value pairs in the tree that fall within the given start and /// end points (inclusive) in sorted order. If None is given, then that side is unbounded. /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// tree.insert(1,"a"); /// tree.insert(2,"a"); /// tree.insert(3,"a"); /// tree.insert(4,"a"); /// tree.insert(5,"a"); /// /// assert_eq!(tree.range_iter(Some(&2), None).next().unwrap(), (&2, &"a")); /// pub fn range_iter(&self, start: Option<&K>, end: Option<&K> ) -> Iter<K,V> { Iter::new(self, start, end, true) } /// Gives an iterator over the key-value pairs in the tree that fall within the given start and /// end points (inclusive) in reverse sorted order. If None is given, then that side is unbounded. /// /// #Examples /// /// ``` /// use avltree_map::AvlTree; /// /// let mut tree = AvlTree::new(); /// tree.insert(1,"a"); /// tree.insert(2,"a"); /// tree.insert(3,"a"); /// tree.insert(4,"a"); /// tree.insert(5,"a"); /// /// assert_eq!(tree.reverse_range_iter(None, Some(&3)).next().unwrap(), (&3, &"a")); /// pub fn reverse_range_iter(&self, start: Option<&K>, end: Option<&K> ) -> Iter<K,V> { Iter::new(self, start, end, false) } } #[cfg(test)] mod test { use AvlTree; #[test] fn test_insert() { let mut tree = AvlTree::new(); for num in 1..100 { assert_eq!(tree.insert(num, num),None); } //ensure self balancing is working. //ceil log2(100) == 7, so height must be <= 7 assert!(tree.height() <= 7); //check reinserting returns right thing assert_eq!(tree.insert(5,30), Some(5)); assert_eq!(tree.insert(5,35), Some(30)); assert_eq!(tree.insert(99,35), Some(99)); assert_eq!(tree.insert(101,35), None); } #[test] fn test_remove() { let mut tree = AvlTree::new(); for num in 1..1000 { assert_eq!(tree.insert(num, num),None); } assert!(tree.height() <= 10); for num in 100..900 { assert_eq!(tree.remove(&num), Some(num)); } println!("{}",tree.height()); assert!(tree.height() <= 8); assert_eq!(tree.remove(&50), Some(50)); assert_eq!(tree.remove(&500), None); assert!(!tree.contains_key(&400)); } #[test] fn test_iter() { let mut tree = AvlTree::new(); for num in 1..1000 { assert_eq!(tree.insert(num, num),None); }; let mut c = 1; //ensures the keys come back in order for (key,val) in tree.iter() { assert!(key == val); assert!(*key == c); c += 1; }; c = 999; for (key, _) in tree.reverse_iter() { assert!(*key == c); c -= 1; }; c = 100; for (key, _) in tree.range_iter(Some(&100), Some(&900)) { assert!(*key == c); c += 1; } assert!(c == 901); c = 100; for (key, _) in tree.range_iter(Some(&100), None) { assert!(*key == c); c += 1; } assert!(c == 1000); c = 900; for (key, _) in tree.reverse_range_iter(Some(&100), Some(&900)) { assert!(*key == c); c -= 1; } assert!(c == 99); c = 900; for (key, _) in tree.reverse_range_iter(None, Some(&900)) { assert!(*key == c); c -= 1; } assert!(c == 0); } }
use crate::{ objects::{Cube, Object}, Result, }; use std::path::Path; use winit::{dpi::PhysicalSize, window::Window}; pub mod pipeline; pub mod texture; pub use texture::Texture; pub struct Renderer { surface: wgpu::Surface, _adapter: wgpu::Adapter, pub device: wgpu::Device, pub queue: wgpu::Queue, sc_desc: wgpu::SwapChainDescriptor, swap_chain: wgpu::SwapChain, size: PhysicalSize<u32>, bg_color: wgpu::Color, } impl Renderer { pub async fn new(window: &Window, bg_color: [f32; 4]) -> Self { let size = window.inner_size(); let surface = wgpu::Surface::create(window); let adapter = wgpu::Adapter::request(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, compatible_surface: Some(&surface), }, wgpu::BackendBit::VULKAN) .await.unwrap(); let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor { extensions: wgpu::Extensions { anisotropic_filtering: false, }, limits: Default::default(), }).await; let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: wgpu::TextureFormat::Bgra8UnormSrgb, width: size.width, height: size.height, present_mode: wgpu::PresentMode::Immediate, }; let swap_chain = device.create_swap_chain(&surface, &sc_desc); let bg_color = wgpu::Color { r: bg_color[0] as f64, g: bg_color[1] as f64, b: bg_color[2] as f64, a: bg_color[3] as f64, }; Self { surface, _adapter: adapter, device, queue, sc_desc, swap_chain, size, bg_color, } } pub fn create_pipeline( &self, vert_file: &Path, frag_file: &Path, vertex_buffer_descriptor: wgpu::VertexBufferDescriptor, ) -> Result<wgpu::RenderPipeline> { pipeline::create_pipeline( vert_file, frag_file, vertex_buffer_descriptor, self.sc_desc.format, &self.device, ) } pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { self.size = new_size; self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); } pub fn init_clear_screen(&mut self) { // TODO: fix unwrap let frame = self.swap_chain.get_next_texture().unwrap(); let mut encoder = get_command_encoder(&self.device); { let _render_pass = begin_render_pass(&mut encoder, &frame, self.bg_color); } submit_frame(&mut self.queue, encoder); } pub fn render(&mut self, cube: &Cube) { // TODO: fix unwrap let frame = self.swap_chain.get_next_texture().unwrap(); let mut encoder = get_command_encoder(&self.device); { let mut render_pass = begin_render_pass(&mut encoder, &frame, self.bg_color); // cube.render(&mut render_pass); render_pass.set_pipeline(&cube.pipeline); render_pass.set_vertex_buffer(0, &cube.vertex_buffer, 0, 0); render_pass.set_index_buffer(&cube.index_buffer, 0, 0); render_pass.draw_indexed(0..cube.num_indices, 0, 0..1); } submit_frame(&mut self.queue, encoder); } // pub fn get_command_encoder(&self) -> wgpu::CommandEncoder { // // render_pass.set_pipeline(&model.pipeline.render_pipeline); // // render_pass.set_bind_group(0, &model.texture.diffuse_bind_group, &[]); // // render_pass.set_vertex_buffers(0, &[(&model.vertex_buffer, 0)]); // // render_pass.set_index_buffer(&model.index_buffer, 0); // // render_pass.draw_indexed(0..model.num_indices, 0, 0..1); // } // pub fn begin_render_pass<'a>( // &self, // encoder: &'a mut wgpu::CommandEncoder, // frame: &wgpu::SwapChainOutput, // ) -> wgpu::RenderPass<'a> { // let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { // color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { // attachment: &frame.view, // resolve_target: None, // load_op: wgpu::LoadOp::Clear, // store_op: wgpu::StoreOp::Store, // clear_color: wgpu::Color { // r: 0.1, // g: 0.2, // b: 0.3, // a: 1.0, // }, // }], // depth_stencil_attachment: None, // }); // render_pass // } // pub fn submit_frame(&mut self, encoder: wgpu::CommandEncoder) { // self.queue.submit(&[encoder.finish()]); // } } fn get_command_encoder(device: &wgpu::Device) -> wgpu::CommandEncoder { device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("comand_encoder")}) } fn begin_render_pass<'a>( encoder: &'a mut wgpu::CommandEncoder, frame: &'a wgpu::SwapChainOutput, bg_color: wgpu::Color, ) -> wgpu::RenderPass<'a> { encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { attachment: &frame.view, resolve_target: None, load_op: wgpu::LoadOp::Clear, store_op: wgpu::StoreOp::Store, clear_color: bg_color, }], depth_stencil_attachment: None, }) } fn submit_frame(queue: &mut wgpu::Queue, encoder: wgpu::CommandEncoder) { queue.submit(&[encoder.finish()]); }
//! A channel for sending a single message between asynchronous tasks. use loom::{ futures::task::{self, Task}, sync::atomic::AtomicUsize, sync::CausalCell, }; use futures::{Async, Future, Poll}; use std::fmt; use std::mem::{self, ManuallyDrop}; use std::sync::atomic::Ordering::{self, AcqRel, Acquire}; use std::sync::Arc; /// Sends a value to the associated `Receiver`. /// /// Instances are created by the [`channel`](fn.channel.html) function. #[derive(Debug)] pub struct Sender<T> { inner: Option<Arc<Inner<T>>>, } /// Receive a value from the associated `Sender`. /// /// Instances are created by the [`channel`](fn.channel.html) function. #[derive(Debug)] pub struct Receiver<T> { inner: Option<Arc<Inner<T>>>, } pub mod error { //! Oneshot error types use std::fmt; /// Error returned by the `Future` implementation for `Receiver`. #[derive(Debug)] pub struct RecvError(pub(super) ()); /// Error returned by the `try_recv` function on `Receiver`. #[derive(Debug)] pub struct TryRecvError(pub(super) ()); // ===== impl RecvError ===== impl fmt::Display for RecvError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } } impl ::std::error::Error for RecvError { fn description(&self) -> &str { "channel closed" } } // ===== impl TryRecvError ===== impl fmt::Display for TryRecvError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } } impl ::std::error::Error for TryRecvError { fn description(&self) -> &str { "channel closed" } } } use self::error::*; struct Inner<T> { /// Manages the state of the inner cell state: AtomicUsize, /// The value. This is set by `Sender` and read by `Receiver`. The state of /// the cell is tracked by `state`. value: CausalCell<Option<T>>, /// The task to notify when the receiver drops without consuming the value. tx_task: CausalCell<ManuallyDrop<Task>>, /// The task to notify when the value is sent. rx_task: CausalCell<ManuallyDrop<Task>>, } #[derive(Clone, Copy)] struct State(usize); /// Create a new one-shot channel for sending single values across asynchronous /// tasks. /// /// The function returns separate "send" and "receive" handles. The `Sender` /// handle is used by the producer to send the value. The `Receiver` handle is /// used by the consumer to receive the value. /// /// Each handle can be used on separate tasks. /// /// # Examples /// /// ``` /// extern crate futures; /// extern crate tokio; /// /// use tokio::sync::oneshot; /// use futures::Future; /// use std::thread; /// /// let (sender, receiver) = oneshot::channel::<i32>(); /// /// # let t = /// thread::spawn(|| { /// let future = receiver.map(|i| { /// println!("got: {:?}", i); /// }); /// // ... /// # return future; /// }); /// /// sender.send(3).unwrap(); /// # t.join().unwrap().wait().unwrap(); /// ``` pub fn channel<T>() -> (Sender<T>, Receiver<T>) { let inner = Arc::new(Inner { state: AtomicUsize::new(State::new().as_usize()), value: CausalCell::new(None), tx_task: CausalCell::new(ManuallyDrop::new(unsafe { mem::uninitialized() })), rx_task: CausalCell::new(ManuallyDrop::new(unsafe { mem::uninitialized() })), }); let tx = Sender { inner: Some(inner.clone()), }; let rx = Receiver { inner: Some(inner) }; (tx, rx) } impl<T> Sender<T> { /// Completes this oneshot with a successful result. /// /// The function consumes `self` and notifies the `Receiver` handle that a /// value is ready to be received. /// /// If the value is successfully enqueued for the remote end to receive, /// then `Ok(())` is returned. If the receiving end was dropped before this /// function was called, however, then `Err` is returned with the value /// provided. pub fn send(mut self, t: T) -> Result<(), T> { let inner = self.inner.take().unwrap(); inner.value.with_mut(|ptr| unsafe { *ptr = Some(t); }); if !inner.complete() { return Err(inner .value .with_mut(|ptr| unsafe { (*ptr).take() }.unwrap())); } Ok(()) } /// Check if the associated [`Receiver`] handle has been dropped. /// /// # Return values /// /// If `Ok(Ready)` is returned then the associated `Receiver` has been /// dropped, which means any work required for sending should be canceled. /// /// If `Ok(NotReady)` is returned then the associated `Receiver` is still /// alive and may be able to receive a message if sent. The current task is /// registered to receive a notification if the `Receiver` handle goes away. /// /// [`Receiver`]: struct.Receiver.html pub fn poll_close(&mut self) -> Poll<(), ()> { let inner = self.inner.as_ref().unwrap(); let mut state = State::load(&inner.state, Acquire); if state.is_closed() { return Ok(Async::Ready(())); } if state.is_tx_task_set() { let will_notify = inner .tx_task .with(|ptr| unsafe { (&*ptr).will_notify_current() }); if !will_notify { state = State::unset_tx_task(&inner.state); if state.is_closed() { return Ok(Async::Ready(())); } else { unsafe { inner.drop_tx_task() }; } } } if !state.is_tx_task_set() { // Attempt to set the task unsafe { inner.set_tx_task(); } // Update the state state = State::set_tx_task(&inner.state); if state.is_closed() { return Ok(Async::Ready(())); } } Ok(Async::NotReady) } /// Check if the associated [`Receiver`] handle has been dropped. /// /// Unlike [`poll_close`], this function does not register a task for /// wakeup upon close. /// /// [`Receiver`]: struct.Receiver.html /// [`poll_close`]: struct.Sender.html#method.poll_close pub fn is_closed(&self) -> bool { let inner = self.inner.as_ref().unwrap(); let state = State::load(&inner.state, Acquire); state.is_closed() } } impl<T> Drop for Sender<T> { fn drop(&mut self) { if let Some(inner) = self.inner.as_ref() { inner.complete(); } } } impl<T> Receiver<T> { /// Prevent the associated [`Sender`] handle from sending a value. /// /// Any `send` operation which happens after calling `close` is guaranteed /// to fail. After calling `close`, `Receiver::poll`] should be called to /// receive a value if one was sent **before** the call to `close` /// completed. /// /// [`Sender`]: struct.Sender.html pub fn close(&mut self) { let inner = self.inner.as_ref().unwrap(); inner.close(); } /// Attempts to receive a value outside of the context of a task. /// /// Does not register a task if no value has been sent. /// /// A return value of `None` must be considered immediately stale (out of /// date) unless [`close`] has been called first. /// /// Returns an error if the sender was dropped. /// /// [`close`]: #method.close pub fn try_recv(&mut self) -> Result<T, TryRecvError> { let result = if let Some(inner) = self.inner.as_ref() { let state = State::load(&inner.state, Acquire); if state.is_complete() { match unsafe { inner.consume_value() } { Some(value) => Ok(value), None => Err(TryRecvError(())), } } else if state.is_closed() { Err(TryRecvError(())) } else { // Not ready, this does not clear `inner` return Err(TryRecvError(())); } } else { panic!("called after complete"); }; self.inner = None; result } } impl<T> Drop for Receiver<T> { fn drop(&mut self) { if let Some(inner) = self.inner.as_ref() { inner.close(); } } } impl<T> Future for Receiver<T> { type Item = T; type Error = RecvError; fn poll(&mut self) -> Poll<T, RecvError> { use futures::Async::{NotReady, Ready}; // If `inner` is `None`, then `poll()` has already completed. let ret = if let Some(inner) = self.inner.as_ref() { match inner.poll_recv() { Ok(Ready(v)) => Ok(Ready(v)), Ok(NotReady) => return Ok(NotReady), Err(e) => Err(e), } } else { panic!("called after complete"); }; self.inner = None; ret } } impl<T> Inner<T> { fn complete(&self) -> bool { let prev = State::set_complete(&self.state); if prev.is_closed() { return false; } if prev.is_rx_task_set() { self.rx_task.with(|ptr| unsafe { (&*ptr).notify() }); } true } fn poll_recv(&self) -> Poll<T, RecvError> { use futures::Async::{NotReady, Ready}; // Load the state let mut state = State::load(&self.state, Acquire); if state.is_complete() { match unsafe { self.consume_value() } { Some(value) => Ok(Ready(value)), None => Err(RecvError(())), } } else if state.is_closed() { Err(RecvError(())) } else { if state.is_rx_task_set() { let will_notify = self .rx_task .with(|ptr| unsafe { (&*ptr).will_notify_current() }); // Check if the task is still the same if !will_notify { // Unset the task state = State::unset_rx_task(&self.state); if state.is_complete() { return match unsafe { self.consume_value() } { Some(value) => Ok(Ready(value)), None => Err(RecvError(())), }; } else { unsafe { self.drop_rx_task() }; } } } if !state.is_rx_task_set() { // Attempt to set the task unsafe { self.set_rx_task(); } // Update the state state = State::set_rx_task(&self.state); if state.is_complete() { match unsafe { self.consume_value() } { Some(value) => Ok(Ready(value)), None => Err(RecvError(())), } } else { return Ok(NotReady); } } else { return Ok(NotReady); } } } /// Called by `Receiver` to indicate that the value will never be received. fn close(&self) { let prev = State::set_closed(&self.state); if prev.is_tx_task_set() && !prev.is_complete() { self.tx_task.with(|ptr| unsafe { (&*ptr).notify() }); } } /// Consume the value. This function does not check `state`. unsafe fn consume_value(&self) -> Option<T> { self.value.with_mut(|ptr| (*ptr).take()) } unsafe fn drop_rx_task(&self) { self.rx_task.with_mut(|ptr| ManuallyDrop::drop(&mut *ptr)) } unsafe fn drop_tx_task(&self) { self.tx_task.with_mut(|ptr| ManuallyDrop::drop(&mut *ptr)) } unsafe fn set_rx_task(&self) { self.rx_task .with_mut(|ptr| *ptr = ManuallyDrop::new(task::current())); } unsafe fn set_tx_task(&self) { self.tx_task .with_mut(|ptr| *ptr = ManuallyDrop::new(task::current())); } } unsafe impl<T: Send> Send for Inner<T> {} unsafe impl<T: Send> Sync for Inner<T> {} impl<T> Drop for Inner<T> { fn drop(&mut self) { let state = State(*self.state.get_mut()); if state.is_rx_task_set() { self.rx_task.with_mut(|ptr| unsafe { ManuallyDrop::drop(&mut *ptr); }); } if state.is_tx_task_set() { self.tx_task.with_mut(|ptr| unsafe { ManuallyDrop::drop(&mut *ptr); }); } } } impl<T: fmt::Debug> fmt::Debug for Inner<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::sync::atomic::Ordering::Relaxed; fmt.debug_struct("Inner") .field("state", &State::load(&self.state, Relaxed)) .finish() } } const RX_TASK_SET: usize = 0b00001; const VALUE_SENT: usize = 0b00010; const CLOSED: usize = 0b00100; const TX_TASK_SET: usize = 0b01000; impl State { fn new() -> State { State(0) } fn is_complete(&self) -> bool { self.0 & VALUE_SENT == VALUE_SENT } fn set_complete(cell: &AtomicUsize) -> State { // TODO: This could be `Release`, followed by an `Acquire` fence *if* // the `RX_TASK_SET` flag is set. However, `loom` does not support // fences yet. let val = cell.fetch_or(VALUE_SENT, AcqRel); State(val) } fn is_rx_task_set(&self) -> bool { self.0 & RX_TASK_SET == RX_TASK_SET } fn set_rx_task(cell: &AtomicUsize) -> State { let val = cell.fetch_or(RX_TASK_SET, AcqRel); State(val | RX_TASK_SET) } fn unset_rx_task(cell: &AtomicUsize) -> State { let val = cell.fetch_and(!RX_TASK_SET, AcqRel); State(val & !RX_TASK_SET) } fn is_closed(&self) -> bool { self.0 & CLOSED == CLOSED } fn set_closed(cell: &AtomicUsize) -> State { // Acquire because we want all later writes (attempting to poll) to be // ordered after this. let val = cell.fetch_or(CLOSED, Acquire); State(val) } fn set_tx_task(cell: &AtomicUsize) -> State { let val = cell.fetch_or(TX_TASK_SET, AcqRel); State(val | TX_TASK_SET) } fn unset_tx_task(cell: &AtomicUsize) -> State { let val = cell.fetch_and(!TX_TASK_SET, AcqRel); State(val & !TX_TASK_SET) } fn is_tx_task_set(&self) -> bool { self.0 & TX_TASK_SET == TX_TASK_SET } fn as_usize(self) -> usize { self.0 } fn load(cell: &AtomicUsize, order: Ordering) -> State { let val = cell.load(order); State(val) } } impl fmt::Debug for State { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("State") .field("is_complete", &self.is_complete()) .field("is_closed", &self.is_closed()) .field("is_rx_task_set", &self.is_rx_task_set()) .field("is_tx_task_set", &self.is_tx_task_set()) .finish() } }
//! Load MP3 files use crate::audio::GenericMusicStream; use std::{io, iter::Peekable}; use simplemad::{self, Decoder, MadFixed32, SimplemadError}; /// Lazy iterator over audio samples from an MP3 struct MP3Samples<R: io::Read + Send> { decoder: Peekable<simplemad::Decoder<R>>, current_samples: Option<Vec<Vec<MadFixed32>>>, current_samples_index: usize, /// What channel the next sample should come from current_channel: usize, /// Whether the end of the file has been reached yet. eof: bool, } impl<R: io::Read + Send> MP3Samples<R> { fn new(decoder: Peekable<Decoder<R>>) -> MP3Samples<R> { MP3Samples { decoder, current_samples: None, current_samples_index: 0, current_channel: 0, eof: false, } } } impl<R: io::Read + Send> Iterator for MP3Samples<R> { type Item = f32; fn next(&mut self) -> Option<f32> { if self.eof { return None; // If we need the next mp3 frame, get it } else if self.current_samples.is_none() || self.current_samples_index == self.current_samples.as_ref().unwrap()[0].len() { loop { match self.decoder.next() { Some(r) => match r { Ok(f) => { self.current_samples = Some(f.samples); self.current_samples_index = 0; self.current_channel = 0; break; } Err(SimplemadError::Mad(e)) => remani_warn!("libmad err: {:?}", e), Err(SimplemadError::Read(e)) => remani_warn!("mp3 read err: {}", e), Err(SimplemadError::EOF) => { self.eof = true; return None; } }, None => { self.eof = true; return None; } } } } // This shouldn't ever error let current_samples = self .current_samples .as_ref() .expect("Something went terribly wrong in the mp3 module"); let sample = current_samples[self.current_channel][self.current_samples_index].to_f32(); self.current_channel = (self.current_channel + 1) % current_samples.len(); if self.current_channel == 0 { self.current_samples_index += 1; } Some(sample) } } // Hope nothing bad happens unsafe impl<R: io::Read + Send> Send for MP3Samples<R> {} /// Create a stream that reads from an mp3 pub(super) fn decode<R: io::Read + Send + 'static>(reader: R) -> Result<GenericMusicStream<impl Iterator<Item = f32> + Send, f32>, String> { let mut decoder = match Decoder::decode(reader) { Ok(d) => d.peekable(), Err(e) => return Err(format!("{:?}", e)), }; let sample_rate; let channel_count; { // Get the sample rate and channel count. while let &Err(_) = decoder.peek().ok_or("Error finding audio metadata")? { decoder.next(); } // This line should never panic let frame = decoder.peek().unwrap().as_ref().unwrap(); sample_rate = frame.sample_rate; channel_count = frame.samples.len(); } Ok(GenericMusicStream { samples: MP3Samples::new(decoder), channel_count: channel_count as u8, sample_rate, }) }
pub const EXPECTED_TOTAL_WORDS: usize = 6; pub const EXPECTED_TOTAL_LINES: usize = 3; pub const EXPECTED_UNIQUE_WORDS: usize = 3; pub const EXPECTED_ERROR: &str = "test error"; pub fn new_wordcount() -> wordcount_core::WordCount { wordcount_core::WordCount { total: EXPECTED_TOTAL_WORDS, lines: EXPECTED_TOTAL_LINES, unique_words: vec![ (String::from("test3"), 3), (String::from("test2"), 2), (String::from("test1"), 1), ], } }
pub mod dom; pub mod drag; pub mod focus; pub mod gamepad; pub mod history; pub mod keyboard; pub mod mouse; pub mod pointer; pub mod progress; pub mod socket; pub mod slot; pub mod touch;
#[repr(C)] #[derive(Copy, Clone, Debug, Default)] pub struct VkExtent2D { pub width: u32, pub height: u32, }
use std::time::{Instant}; #[derive(Debug)] struct Node { value: u32, next: Option<Box<Node>> } fn main() { let INPUT = "469217538"; let len = INPUT.len(); let mut next_cup_vec = Vec::new(); next_cup_vec.resize((len+1) as usize, 0); let input_vec: Vec<_> = INPUT.chars().map(|x| x.to_string().parse::<u32>().unwrap()).collect(); for i in 0..len { if i == len - 1 { next_cup_vec[input_vec[i] as usize] = input_vec[0]; } else { next_cup_vec[input_vec[i] as usize] = input_vec[i + 1]; } } play(&mut next_cup_vec, 100, input_vec[0], 9); let mut final_arrangement = Vec::new(); let mut current_cup = 1; loop { current_cup = next_cup_vec[current_cup as usize]; if current_cup == 1 {break;} final_arrangement.push(current_cup.to_string()); }; println!("Part one: {}", final_arrangement.join("")); let now = Instant::now(); let mut next_cup_vec = Vec::new(); next_cup_vec.resize((1000001) as usize, 0); for i in 0..(len-1) { next_cup_vec[input_vec[i] as usize] = input_vec[i+1]; }; next_cup_vec[input_vec[len-1] as usize] = (len+1) as u32; next_cup_vec[1000000] = input_vec[0]; for i in len+1..1000000 { next_cup_vec[i as usize] = (i+1) as u32; } play(&mut next_cup_vec, 10000000, input_vec[0], 1000000); let one_next = next_cup_vec[1]; println!("{:?}", now.elapsed()); println!("Part two: {}", (one_next as u64) * (next_cup_vec[one_next as usize]) as u64); } fn play(next_cup_vec: &mut Vec<u32>, iterations: u32, mut current_cup: u32, max_value: u32) { for _ in 0..iterations { current_cup = step(next_cup_vec, current_cup, max_value); } } fn step(next_cup_vec: &mut Vec<u32>, current_cup: u32, max_value: u32) -> u32 { let move_beginning = next_cup_vec[current_cup as usize]; let move_middle = next_cup_vec[move_beginning as usize]; let move_end = next_cup_vec[move_middle as usize]; let mut destination_cup = current_cup - 1; loop { if [move_beginning, move_middle, move_end].contains(&destination_cup) { destination_cup = destination_cup - 1; } else if destination_cup == 0 { destination_cup = max_value; } else { break; } } let destination_cup_next = next_cup_vec[destination_cup as usize]; next_cup_vec[destination_cup as usize] = move_beginning; let new_next = next_cup_vec[move_end as usize]; next_cup_vec[move_end as usize] = destination_cup_next; next_cup_vec[current_cup as usize] = new_next; new_next }
// Copyright (c) 2017 Martijn Rijkeboer <mrr@sru-systems.com> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use crate::common; use std::fmt; use std::fmt::Debug; use std::ops::{BitXorAssign, Index, IndexMut}; /// Structure for the (1KB) memory block implemented as 128 64-bit words. pub struct Block([u64; common::QWORDS_IN_BLOCK]); impl Block { /// Gets the byte slice representation of the block. pub fn as_u8(&self) -> &[u8] { let bytes: &[u8; common::BLOCK_SIZE] = unsafe { &*(&self.0 as *const [u64; common::QWORDS_IN_BLOCK] as *const [u8; common::BLOCK_SIZE]) }; bytes } /// Gets the mutable byte slice representation of the block. pub fn as_u8_mut(&mut self) -> &mut [u8] { let bytes: &mut [u8; common::BLOCK_SIZE] = unsafe { &mut *(&mut self.0 as *mut [u64; common::QWORDS_IN_BLOCK] as *mut [u8; common::BLOCK_SIZE]) }; bytes } /// Copies self to destination. pub fn copy_to(&self, dst: &mut Block) { for (d, s) in dst.0.iter_mut().zip(self.0.iter()) { *d = *s } } /// Creates a new block filled with zeros. pub fn zero() -> Block { Block([0u64; common::QWORDS_IN_BLOCK]) } } impl<'a> BitXorAssign<&'a Block> for Block { fn bitxor_assign(&mut self, rhs: &Block) { for (s, r) in self.0.iter_mut().zip(rhs.0.iter()) { *s ^= *r } } } impl Clone for Block { fn clone(&self) -> Block { Block(self.0) } } impl Debug for Block { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_list().entries(self.0.iter()).finish() } } impl Eq for Block {} impl Index<usize> for Block { type Output = u64; fn index(&self, index: usize) -> &u64 { &self.0[index] } } impl IndexMut<usize> for Block { fn index_mut(&mut self, index: usize) -> &mut u64 { &mut self.0[index] } } impl PartialEq for Block { fn eq(&self, other: &Block) -> bool { let mut equal = true; for (s, o) in self.0.iter().zip(other.0.iter()) { if s != o { equal = false; } } equal } } #[cfg(test)] mod tests { use crate::block::Block; use crate::common; #[test] fn as_u8_returns_correct_slice() { let block = Block::zero(); let expected = vec![0u8; 1024]; let actual = block.as_u8(); assert_eq!(actual, expected.as_slice()); } #[test] fn as_u8_mut_returns_correct_slice() { let mut block = Block::zero(); let mut expected = vec![0u8; 1024]; let actual = block.as_u8_mut(); assert_eq!(actual, expected.as_mut_slice()); } #[test] fn bitxor_assign_updates_lhs() { let mut lhs = Block([0u64; common::QWORDS_IN_BLOCK]); let rhs = Block([1u64; common::QWORDS_IN_BLOCK]); lhs ^= &rhs; assert_eq!(lhs, rhs); } #[test] fn copy_to_copies_block() { let src = Block([1u64; common::QWORDS_IN_BLOCK]); let mut dst = Block([0u64; common::QWORDS_IN_BLOCK]); src.copy_to(&mut dst); assert_eq!(dst, src); } #[test] fn clone_clones_block() { let orig = Block([1u64; common::QWORDS_IN_BLOCK]); let copy = orig.clone(); assert_eq!(copy, orig); } #[test] fn zero_creates_block_will_all_zeros() { let expected = Block([0u64; common::QWORDS_IN_BLOCK]); let actual = Block::zero(); assert_eq!(actual, expected); } }
use serde::Deserialize; use serde_json as json; use std::fs::{self, File}; use std::io::Read; use std::path::Path; use alacritty_terminal::ansi; use alacritty_terminal::config::Config; use alacritty_terminal::event::{Event, EventListener}; use alacritty_terminal::grid::{Dimensions, Grid}; use alacritty_terminal::index::{Column, Line}; use alacritty_terminal::term::cell::Cell; use alacritty_terminal::term::test::TermSize; use alacritty_terminal::term::Term; macro_rules! ref_tests { ($($name:ident)*) => { $( #[test] fn $name() { let test_dir = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/ref")); let test_path = test_dir.join(stringify!($name)); ref_test(&test_path); } )* } } ref_tests! { alt_reset clear_underline colored_reset colored_underline csi_rep decaln_reset deccolm_reset delete_chars_reset delete_lines erase_chars_reset fish_cc grid_reset history hyperlinks indexed_256_colors insert_blank_reset issue_855 ll newline_with_cursor_beyond_scroll_region region_scroll_down row_reset saved_cursor saved_cursor_alt scroll_up_reset selective_erasure sgr tab_rendering tmux_git_log tmux_htop underline vim_24bitcolors_bce vim_large_window_scroll vim_simple_edit vttest_cursor_movement_1 vttest_insert vttest_origin_mode_1 vttest_origin_mode_2 vttest_scroll vttest_tab_clear_set wrapline_alt_toggle zerowidth zsh_tab_completion erase_in_line } fn read_u8<P>(path: P) -> Vec<u8> where P: AsRef<Path>, { let mut res = Vec::new(); File::open(path.as_ref()).unwrap().read_to_end(&mut res).unwrap(); res } #[derive(Deserialize, Default)] struct RefConfig { history_size: u32, } #[derive(Copy, Clone)] struct Mock; impl EventListener for Mock { fn send_event(&self, _event: Event) {} } fn ref_test(dir: &Path) { let recording = read_u8(dir.join("alacritty.recording")); let serialized_size = fs::read_to_string(dir.join("size.json")).unwrap(); let serialized_grid = fs::read_to_string(dir.join("grid.json")).unwrap(); let serialized_cfg = fs::read_to_string(dir.join("config.json")).unwrap(); let size: TermSize = json::from_str(&serialized_size).unwrap(); let grid: Grid<Cell> = json::from_str(&serialized_grid).unwrap(); let ref_config: RefConfig = json::from_str(&serialized_cfg).unwrap(); let mut config = Config::default(); config.scrolling.set_history(ref_config.history_size); let mut terminal = Term::new(&config, &size, Mock); let mut parser: ansi::Processor = ansi::Processor::new(); for byte in recording { parser.advance(&mut terminal, byte); } // Truncate invisible lines from the grid. let mut term_grid = terminal.grid().clone(); term_grid.initialize_all(); term_grid.truncate(); if grid != term_grid { for i in 0..grid.total_lines() { for j in 0..grid.columns() { let cell = &term_grid[Line(i as i32)][Column(j)]; let original_cell = &grid[Line(i as i32)][Column(j)]; if original_cell != cell { println!("[{i}][{j}] {original_cell:?} => {cell:?}",); } } } panic!("Ref test failed; grid doesn't match"); } assert_eq!(grid, term_grid); }
//! Provides the `Installer` type, which represents a provisioned Node installer. use std::fs::{rename, File}; use std::path::PathBuf; use std::string::ToString; use super::{Distro, Fetched}; use catalog::NodeCollection; use distro::error::DownloadError; use fs::ensure_containing_dir_exists; use node_archive::{self, Archive}; use path; use style::{progress_bar, Action}; use notion_fail::{Fallible, ResultExt}; use semver::Version; #[cfg(feature = "mock-network")] use mockito; cfg_if! { if #[cfg(feature = "mock-network")] { fn public_node_server_root() -> String { mockito::SERVER_URL.to_string() } } else { fn public_node_server_root() -> String { "https://nodejs.org/dist".to_string() } } } /// A provisioned Node distribution. pub struct NodeDistro { archive: Box<Archive>, version: Version, } /// Check if the cached file is valid. It may have been corrupted or interrupted in the middle of /// downloading. // ISSUE(#134) - verify checksum fn cache_is_valid(cache_file: &PathBuf) -> bool { if cache_file.is_file() { if let Ok(file) = File::open(cache_file) { match node_archive::load(file) { Ok(_) => return true, Err(_) => return false, } } } false } impl Distro for NodeDistro { /// Provision a Node distribution from the public Node distributor (`https://nodejs.org`). fn public(version: Version) -> Fallible<Self> { let archive_file = path::node_archive_file(&version.to_string()); let url = format!( "{}/v{}/{}", public_node_server_root(), version, &archive_file ); NodeDistro::remote(version, &url) } /// Provision a Node distribution from a remote distributor. fn remote(version: Version, url: &str) -> Fallible<Self> { let archive_file = path::node_archive_file(&version.to_string()); let cache_file = path::node_cache_dir()?.join(&archive_file); if cache_is_valid(&cache_file) { return NodeDistro::cached(version, File::open(cache_file).unknown()?); } ensure_containing_dir_exists(&cache_file)?; Ok(NodeDistro { archive: node_archive::fetch(url, &cache_file) .with_context(DownloadError::for_version(version.to_string()))?, version: version, }) } /// Provision a Node distribution from the filesystem. fn cached(version: Version, file: File) -> Fallible<Self> { Ok(NodeDistro { archive: node_archive::load(file).unknown()?, version: version, }) } /// Produces a reference to this distribution's Node version. fn version(&self) -> &Version { &self.version } /// Fetches this version of Node. (It is left to the responsibility of the `NodeCollection` /// to update its state after fetching succeeds.) fn fetch(self, collection: &NodeCollection) -> Fallible<Fetched> { if collection.contains(&self.version) { return Ok(Fetched::Already(self.version)); } let dest = path::node_versions_dir()?; let bar = progress_bar( Action::Fetching, &format!("v{}", self.version), self.archive .uncompressed_size() .unwrap_or(self.archive.compressed_size()), ); self.archive .unpack(&dest, &mut |_, read| { bar.inc(read as u64); }) .unknown()?; let version_string = self.version.to_string(); rename( dest.join(path::node_archive_root_dir(&version_string)), path::node_version_dir(&version_string)?, ).unknown()?; bar.finish_and_clear(); Ok(Fetched::Now(self.version)) } }
//! Wrapper of [`tokio::process::Command`]. use crate::process::process_output; use std::path::Path; use tokio::process::Command; /// Executes the command and redirects the output to a file. pub async fn write_stdout_to_file<P: AsRef<Path>>( cmd: &mut Command, output_file: P, ) -> std::io::Result<()> { let file = std::fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .open(output_file)?; let exit_status = cmd.stdout(file).spawn()?.wait().await?; if exit_status.success() { Ok(()) } else { Err(std::io::Error::new( std::io::ErrorKind::Other, format!( "Failed to execute the command: {cmd:?}, exit code: {:?}", exit_status.code() ), )) } } /// Builds `Command` from a cmd string which can use pipe. /// /// This can work with the piped command, e.g., `git ls-files | uniq`. pub fn shell_command(shell_cmd: impl AsRef<str>) -> Command { if cfg!(target_os = "windows") { let mut cmd = Command::new("cmd"); cmd.args(["/C", shell_cmd.as_ref()]); cmd } else { let mut cmd = Command::new("bash"); cmd.arg("-c").arg(shell_cmd.as_ref()); cmd } } /// Unit type wrapper for [`tokio::process::Command`]. #[derive(Debug)] pub struct TokioCommand(Command); impl From<std::process::Command> for TokioCommand { fn from(std_cmd: std::process::Command) -> Self { Self(std_cmd.into()) } } impl TokioCommand { /// Constructs a new instance of [`TokioCommand`]. pub fn new(shell_cmd: impl AsRef<str>) -> Self { Self(shell_command(shell_cmd)) } pub async fn lines(&mut self) -> std::io::Result<Vec<String>> { // Calling `output()` or `spawn().wait_with_output()` directly does not // work for Vim. // let output = self.0.spawn()?.wait_with_output().await?; // // TokioCommand works great for Neovim, but it seemingly has some issues with Vim due to // the stdout pipe stuffs, not sure the reason under the hood clearly, but StdCommand works // both for Neovim and Vim. let output = self.0.output().await?; process_output(output) } pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self { self.0.current_dir(dir); self } } #[cfg(test)] mod tests { use super::*; use std::collections::HashSet; #[tokio::test] async fn test_tokio_command() { let shell_cmd = format!( "ls {}", std::env::current_dir() .unwrap() .into_os_string() .into_string() .unwrap() ); let mut tokio_cmd = TokioCommand::new(shell_cmd); assert_eq!( vec!["Cargo.toml", "src"] .into_iter() .map(Into::into) .collect::<HashSet<String>>(), HashSet::from_iter(tokio_cmd.lines().await.unwrap().into_iter()) ); } }
extern crate bigint; extern crate block; extern crate evm; extern crate evm_network_classic; extern crate evm_stateful; extern crate hexutil; extern crate trie; #[macro_use] extern crate lazy_static; use bigint::{Address, Gas, U256}; use block::TransactionAction; use evm::{AccountChange, HeaderParams, SeqTransactionVM, Storage, ValidTransaction, VM}; use evm_network_classic::MainnetEIP160Patch; use evm_stateful::{LiteralAccount, MemoryStateful}; use hexutil::*; use std::collections::{HashMap, HashSet}; use std::ops::Deref; use std::rc::Rc; use std::str::FromStr; use std::sync::Arc; use std::thread; use trie::MemoryDatabase; #[derive(Debug, Clone)] /// Represents an account. This is usually returned by the EVM. pub enum SendableAccountChange { /// A full account. The client is expected to replace its own account state with this. Full { /// Account nonce. nonce: U256, /// Account address. address: Address, /// Account balance. balance: U256, /// Change storage with given indexes and values. changing_storage: Storage, /// Code associated with this account. code: Vec<u8>, }, /// Only balance is changed, and it is increasing for this address. IncreaseBalance(Address, U256), /// Create or delete a (new) account. Create { /// Account nonce. nonce: U256, /// Account address. address: Address, /// Account balance. balance: U256, /// All storage values of this account, with given indexes and values. storage: Storage, /// Code associated with this account. code: Vec<u8>, }, Nonexist(Address), } impl SendableAccountChange { /// Address of this account. pub fn address(&self) -> Address { match self { &SendableAccountChange::Full { address, .. } => address, &SendableAccountChange::IncreaseBalance(address, _) => address, &SendableAccountChange::Create { address, .. } => address, &SendableAccountChange::Nonexist(address) => address, } } } impl From<AccountChange> for SendableAccountChange { fn from(change: AccountChange) -> Self { match change { AccountChange::Full { nonce, address, balance, changing_storage, code, } => SendableAccountChange::Full { nonce, address, balance, changing_storage, code: code.deref().clone(), }, AccountChange::IncreaseBalance(address, balance) => { SendableAccountChange::IncreaseBalance(address, balance) } AccountChange::Create { nonce, address, balance, storage, code, } => SendableAccountChange::Create { nonce, address, balance, storage, code: code.deref().clone(), }, AccountChange::Nonexist(address) => SendableAccountChange::Nonexist(address), } } } impl Into<AccountChange> for SendableAccountChange { fn into(self) -> AccountChange { match self { SendableAccountChange::Full { nonce, address, balance, changing_storage, code, } => AccountChange::Full { nonce, address, balance, changing_storage, code: Rc::new(code), }, SendableAccountChange::IncreaseBalance(address, balance) => { AccountChange::IncreaseBalance(address, balance) } SendableAccountChange::Create { nonce, address, balance, storage, code, } => AccountChange::Create { nonce, address, balance, storage, code: Rc::new(code), }, SendableAccountChange::Nonexist(address) => AccountChange::Nonexist(address), } } } pub struct SendableValidTransaction { pub caller: Option<Address>, pub gas_price: Gas, pub gas_limit: Gas, pub action: TransactionAction, pub value: U256, pub input: Vec<u8>, pub nonce: U256, } impl From<ValidTransaction> for SendableValidTransaction { fn from(transaction: ValidTransaction) -> SendableValidTransaction { match transaction { ValidTransaction { caller, gas_price, gas_limit, action, value, input, nonce, } => SendableValidTransaction { caller, gas_price, gas_limit, action, value, nonce, input: input.deref().clone(), }, } } } impl Into<ValidTransaction> for SendableValidTransaction { fn into(self) -> ValidTransaction { match self { SendableValidTransaction { caller, gas_price, gas_limit, action, value, input, nonce, } => ValidTransaction { caller, gas_price, gas_limit, action, value, nonce, input: Rc::new(input), }, } } } fn is_modified(modified_addresses: &HashSet<Address>, accounts: &[SendableAccountChange]) -> bool { for account in accounts { if modified_addresses.contains(&account.address()) { return true; } } return false; } pub fn parallel_execute( stateful: MemoryStateful<'static>, transactions: &[ValidTransaction], ) -> MemoryStateful<'static> { let header = HeaderParams { beneficiary: Address::zero(), timestamp: 0, number: U256::zero(), difficulty: U256::zero(), gas_limit: Gas::max_value(), }; let stateful = Arc::new(stateful); let mut threads = Vec::new(); // Execute all transactions in parallel. for transaction in transactions { let transaction: SendableValidTransaction = transaction.clone().into(); let header = header.clone(); let stateful = stateful.clone(); threads.push(thread::spawn(move || { let patch = MainnetEIP160Patch::default(); let vm: SeqTransactionVM<_> = stateful.call(&patch, transaction.into(), &header, &[]); let accounts: Vec<SendableAccountChange> = vm.accounts().map(|v| SendableAccountChange::from(v.clone())).collect(); (accounts, vm.used_addresses()) })); } // Join all results together. let mut thread_accounts = Vec::new(); for thread in threads { let accounts = thread.join().unwrap(); thread_accounts.push(accounts); } // Now we only have a single reference to stateful, unwrap it and // start the state transition. let mut stateful = match Arc::try_unwrap(stateful) { Ok(val) => val, Err(_) => panic!(), }; let mut modified_addresses = HashSet::new(); for (index, (accounts, used_addresses)) in thread_accounts.into_iter().enumerate() { let (accounts, used_addresses) = if is_modified(&modified_addresses, &accounts) { // Re-execute the transaction if conflict is detected. println!("Transaction index {}: conflict detected, re-execute.", index); let patch = MainnetEIP160Patch::default(); let vm: SeqTransactionVM<_> = stateful.call(&patch, transactions[index].clone(), &header, &[]); let accounts: Vec<AccountChange> = vm.accounts().map(|v| v.clone()).collect(); (accounts, vm.used_addresses()) } else { println!("Transaction index {}: parallel execution successful.", index); let accounts: Vec<AccountChange> = accounts.iter().map(|v| v.clone().into()).collect(); (accounts, used_addresses) }; stateful.transit(&accounts); modified_addresses.extend(used_addresses.into_iter()); } stateful } lazy_static! { static ref DATABASE: MemoryDatabase = MemoryDatabase::default(); } fn main() { let mut stateful = MemoryStateful::empty(&DATABASE); let addr1 = Address::from_str("0x0000000000000000000000000000000000001000").unwrap(); let addr2 = Address::from_str("0x0000000000000000000000000000000000001001").unwrap(); let addr3 = Address::from_str("0x0000000000000000000000000000000000001002").unwrap(); // Input some initial accounts. stateful.sets(&[ (addr1, LiteralAccount { nonce: U256::zero(), balance: U256::from_str("0x1000000000000000000").unwrap(), storage: HashMap::new(), code: read_hex("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055").unwrap(), }), (addr2, LiteralAccount { nonce: U256::zero(), balance: U256::from_str("0x1000000000000000000").unwrap(), storage: HashMap::new(), code: read_hex("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055").unwrap(), }), (addr3, LiteralAccount { nonce: U256::zero(), balance: U256::from_str("0x1000000000000000000").unwrap(), storage: HashMap::new(), code: read_hex("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055").unwrap(), }), ]); // Execute several crafted transactions. let stateful = parallel_execute( stateful, &[ ValidTransaction { caller: Some(addr1), action: TransactionAction::Call(addr1), gas_price: Gas::zero(), gas_limit: Gas::max_value(), value: U256::from_str("0x1000").unwrap(), input: Rc::new(Vec::new()), nonce: U256::zero(), }, ValidTransaction { caller: Some(addr2), action: TransactionAction::Call(addr3), gas_price: Gas::zero(), gas_limit: Gas::max_value(), value: U256::from_str("0x1000").unwrap(), input: Rc::new(Vec::new()), nonce: U256::zero(), }, ValidTransaction { caller: Some(addr3), action: TransactionAction::Call(addr2), gas_price: Gas::zero(), gas_limit: Gas::max_value(), value: U256::from_str("0x1000").unwrap(), input: Rc::new(Vec::new()), nonce: U256::zero(), }, ], ); println!("New state root: 0x{:x}", stateful.root()); }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Read kernel logs, convert them to LogMessages and serve them. use crate::logs::logger; use byteorder::{ByteOrder, LittleEndian}; use fidl_fuchsia_logger::{self, LogMessage}; use fuchsia_async as fasync; use fuchsia_zircon as zx; use futures::stream; use futures::stream::Stream; pub struct KernelLogger { debuglogger: zx::DebugLog, buf: Vec<u8>, } pub struct KernelLogsIterator<'a> { klogger: &'a mut KernelLogger, } impl KernelLogger { pub fn create() -> Result<KernelLogger, zx::Status> { Ok(KernelLogger { debuglogger: zx::DebugLog::create(zx::DebugLogOpts::READABLE)?, buf: Vec::with_capacity(zx::sys::ZX_LOG_RECORD_MAX), }) } fn read_log(&mut self) -> Result<(LogMessage, usize), zx::Status> { loop { match self.debuglogger.read(&mut self.buf) { Err(status) => { return Err(status); } Ok(()) => { let mut l = LogMessage { time: LittleEndian::read_i64(&self.buf[8..16]), pid: LittleEndian::read_u64(&self.buf[16..24]), tid: LittleEndian::read_u64(&self.buf[24..32]), severity: fidl_fuchsia_logger::LogLevelFilter::Info as i32, dropped_logs: 0, tags: vec!["klog".to_string()], msg: String::new(), }; let data_len = LittleEndian::read_u16(&self.buf[4..6]) as usize; l.msg = match String::from_utf8(self.buf[32..(32 + data_len)].to_vec()) { Err(e) => { eprintln!("logger: invalid log record: {:?}", e); continue; } Ok(s) => s, }; if let Some(b'\n') = l.msg.bytes().last() { l.msg.pop(); } let size = logger::METADATA_SIZE + 5/*tag*/ + l.msg.len() + 1; return Ok((l, size)); } } } } pub fn log_stream<'a>(&'a mut self) -> KernelLogsIterator<'a> { KernelLogsIterator { klogger: self } } } impl<'a> Iterator for KernelLogsIterator<'a> { type Item = Result<(LogMessage, usize), zx::Status>; fn next(&mut self) -> Option<Self::Item> { match self.klogger.read_log() { Err(zx::Status::SHOULD_WAIT) => { return None; } Err(status) => { return Some(Err(status)); } Ok(n) => { return Some(Ok(n)); } } } } pub fn listen( klogger: KernelLogger, ) -> impl Stream<Item = Result<(LogMessage, usize), zx::Status>> { stream::unfold((true, klogger), move |(mut is_readable, mut klogger)| { async move { loop { if !is_readable { if let Err(e) = fasync::OnSignals::new(&klogger.debuglogger, zx::Signals::LOG_READABLE) .await { break Some((Err(e), (is_readable, klogger))); } } is_readable = true; match klogger.read_log() { Err(zx::Status::SHOULD_WAIT) => { is_readable = false; continue; } x => break Some((x, (is_readable, klogger))), } } } }) }
use std::env; use n3_machine_ffi::{MachineId, MachineIdSet, WorkId}; pub fn parse_ids() -> Option<MachineIdSet> { let mut args = env::args().skip(1); let work: WorkId = args.next()?.parse().unwrap(); let primary: MachineId = args.next()?.parse().unwrap(); Some(MachineIdSet { work, primary, ..Default::default() }) } pub fn parse_python_path() -> String { // TODO: better ideas? which::which("python").unwrap().display().to_string() }
use serde::Deserialize; use serde_json::Value; use crate::apis::flight_provider::raw_models::airline_code_raw::AirlineCodeRaw; use crate::apis::flight_provider::raw_models::airport_instance_info_raw::AirportInstanceInfoRaw; use crate::apis::flight_provider::raw_models::airport_instance_position_raw::AirportInstancePositionRaw; use crate::apis::flight_provider::raw_models::airport_instance_timezone_raw::AirportInstanceTimezoneRaw; #[derive(Deserialize, Debug)] pub struct AirportInstanceRaw { pub name: Option<String>, pub code: Option<AirlineCodeRaw>, pub position: Option<AirportInstancePositionRaw>, pub timezone: Option<AirportInstanceTimezoneRaw>, pub visible: Option<bool>, pub website: Option<Value>, pub info: Option<AirportInstanceInfoRaw>, }
pub mod rpc; #[macro_use] extern crate log; extern crate morgan_interface; #[cfg(test)] #[macro_use] extern crate serde_json;
use std::io::{self, BufRead}; use std::process; mod game; fn ask() -> String { println!("Your guess (one letter please)?"); let stdin = io::stdin(); let result = stdin.lock().lines().next().unwrap().unwrap().trim_end().to_string(); result } fn main() { let thumbs_up = "\u{1F44D}"; let red_x = "\u{274C}"; let secret = "HELLO WORLD"; let mut game = game::Game::build(secret); // head, 2 arms, 2 legs, body = 6 bad guesses allowed, and 7th ends the game while game.num_bad_guesses < 7 { game.display_status(); game.display_phrase(); let guess = ask(); match game.guess(&guess) { game::GuessResult::CorrectGuess => { println!("{} Correct guess", thumbs_up); if game.is_won() { println!("You win!"); process::exit(0); } }, game::GuessResult::WrongGuess => { // There's an extra space after the emoji because my terminal (Alacritty) doesn't // display any space between the emoji and text if there's only one. println!("{} Nope, try again", red_x); } } } println!("You lose :("); } #[cfg(test)] mod test { use super::*; #[test] fn test_bad_guess() { let mut game = game::Game::build("hello"); let result = game.guess("F"); assert_eq!(game::GuessResult::WrongGuess, result); assert_eq!(1, game.num_guesses); assert_eq!(1, game.num_bad_guesses); } #[test] fn test_repeated_bad_guess() { let mut game = game::Game::build("hello"); game.guess("F"); let result = game.guess("F"); assert_eq!(game::GuessResult::WrongGuess, result); assert_eq!(1, game.num_guesses); assert_eq!(1, game.num_bad_guesses); } #[test] fn test_good_guess() { let mut game = game::Game::build("hello"); let result = game.guess("h"); assert_eq!(game::GuessResult::CorrectGuess, result); assert_eq!(1, game.num_guesses); assert_eq!(0, game.num_bad_guesses); } #[test] fn test_repeated_good_guess() { let mut game = game::Game::build("hello"); game.guess("h"); let result = game.guess("h"); assert_eq!(game::GuessResult::CorrectGuess, result); assert_eq!(1, game.num_guesses); assert_eq!(0, game.num_bad_guesses); } #[test] fn test_winning() { let mut game = game::Game::build("hi"); game.guess("h"); game.guess("i"); assert_eq!(true, game.is_won()); } #[test] fn test_winning_with_whitespace() { let mut game = game::Game::build("h i"); game.guess("h"); game.guess("i"); assert_eq!(true, game.is_won()); } }
use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ braced, parse::{Lookahead1, Parse, ParseStream}, token::Brace, Expr, Ident, Path, Token, Type, }; #[derive(Debug)] pub struct Element { open_tag: OpenTag, children: Vec<Node>, close_tag: Option<CloseTag>, } impl Parse for Element { fn parse(input: ParseStream) -> syn::Result<Self> { let open_tag = input.parse::<OpenTag>()?; let (children, close_tag) = if open_tag.is_self_closing() { (Vec::new(), None) } else { let children = Node::parse_list(input)?; let close_tag = input.parse::<CloseTag>()?; if open_tag.name != close_tag.name { return Err(syn::Error::new_spanned( &close_tag.name, format!( "Tag <{}/> does not match tag <{}>", close_tag.name.to_token_stream(), open_tag.name.to_token_stream(), ), )); } (children, Some(close_tag)) }; Ok(Element { open_tag, children, close_tag, }) } } impl Element { pub fn generate( &self, prefix: Option<&String>, element_trait: Option<&Path>, ) -> syn::Result<TokenStream> { let mut tokens = TokenStream::new(); let element_name = &self.open_tag.name; let builder = if let Some(prefix) = prefix { format_ident!("{}_builder", prefix) } else { format_ident!("builder") }; let build = if let Some(prefix) = prefix { format_ident!("{}_build", prefix) } else { format_ident!("build") }; let add_child = if let Some(prefix) = prefix { format_ident!("{}_child", prefix) } else { format_ident!("child") }; if let Some(element_trait) = &element_trait { tokens.extend(quote! { <#element_name as #element_trait>::#builder() }); } else { tokens.extend(quote! { <#element_name>::#builder() }); } for attr in &self.open_tag.attributes { let set_attr = if let Some(prefix) = prefix { format_ident!("{}_attr_{}", prefix, attr.name) } else { format_ident!("attr_{}", attr.name) }; let value = &attr.value; tokens.extend(quote! { .#set_attr(#value) }) } for child in &self.children { let child_tokens = child.generate(prefix, element_trait)?; tokens.extend(quote! { .#add_child(#child_tokens) }) } tokens.extend(quote! { .#build() }); Ok(tokens) } } #[derive(Debug)] pub enum Node { Element(Element), Expr(Brace, Expr), } impl Node { fn parse_opt(input: ParseStream) -> syn::Result<Option<Node>> { let lookahead = input.lookahead1(); if lookahead.peek(Token![<]) { if input.peek2(Token![/]) { Ok(None) } else { input.parse().map(Node::Element).map(Some) } } else if lookahead.peek(Brace) { let content; let brace = braced!(content in input); let expr = content.parse()?; Ok(Some(Node::Expr(brace, expr))) } else { Err(lookahead.error()) } } pub fn parse_list(input: ParseStream) -> syn::Result<Vec<Node>> { let mut nodes = Vec::new(); while let Some(node) = Node::parse_opt(input)? { nodes.push(node) } Ok(nodes) } pub fn generate( &self, prefix: Option<&String>, element_trait: Option<&Path>, ) -> syn::Result<TokenStream> { match self { Node::Element(element) => element.generate(prefix, element_trait), Node::Expr(_, expr) => Ok(expr.to_token_stream()), } } } #[derive(Debug)] pub struct OpenTag { lt_token: Token![<], name: Type, attributes: Vec<TagAttribute>, close_token: Option<Token![/]>, gt_token: Token![>], } impl OpenTag { pub fn is_self_closing(&self) -> bool { self.close_token.is_some() } } impl Parse for OpenTag { fn parse(input: ParseStream) -> syn::Result<Self> { let lt_token = input.parse()?; let name = input.parse()?; let mut attributes = Vec::new(); let close_token; loop { let lookahead = input.lookahead1(); if lookahead.peek(Token![/]) { close_token = Some(input.parse()?); break; } else if lookahead.peek(Token![>]) { close_token = None; break; } else if TagAttribute::peek(&lookahead) { attributes.push(input.parse()?); } else { return Err(lookahead.error()); } } let gt_token = input.parse()?; Ok(OpenTag { lt_token, name, attributes, close_token, gt_token, }) } } #[derive(Debug)] pub struct TagAttribute { name: Ident, eq_token: Token![=], brace: Brace, value: Expr, } impl Parse for TagAttribute { fn parse(input: ParseStream) -> syn::Result<Self> { let content; Ok(TagAttribute { name: input.parse()?, eq_token: input.parse()?, brace: braced!(content in input), value: content.parse()?, }) } } impl TagAttribute { pub fn peek(input: &Lookahead1<'_>) -> bool { input.peek(Ident) } } #[derive(Debug)] pub struct CloseTag { lt_token: Token![<], close_token: Token![/], name: Type, gt_token: Token![>], } impl Parse for CloseTag { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(CloseTag { lt_token: input.parse()?, close_token: input.parse()?, name: input.parse()?, gt_token: input.parse()?, }) } }
#[macro_use] extern crate log; use futures::sync::mpsc; use futures::{future, Future, Sink, Stream}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use tokio::executor::DefaultExecutor; use tokio::net::TcpListener; use tokio_rustls::{ rustls::{AllowAnyAuthenticatedClient, RootCertStore, ServerConfig}, TlsAcceptor, }; use tower_grpc::{Code, Request, Response, Status}; pub mod spike_proto { include!(concat!(env!("OUT_DIR"), "/spike.rs")); } #[derive(Clone, Debug)] struct Spike { state: Arc<State>, } #[derive(Debug)] struct State { rooms: Mutex<HashMap<String, Vec<String>>>, } impl spike_proto::server::Spike for Spike { type SendFuture = future::FutureResult<Response<spike_proto::SendResponse>, tower_grpc::Status>; fn send(&mut self, request: Request<spike_proto::SendRequest>) -> Self::SendFuture { let send_request: spike_proto::SendRequest = request.into_inner(); let mut rooms = self.state.rooms.lock().unwrap(); let room = rooms .entry(send_request.room) .or_insert_with(|| Vec::with_capacity(16)); room.push(send_request.msg); let response = Response::new(spike_proto::SendResponse {}); future::ok(response) } type WatchStream = Box<Stream<Item = spike_proto::WatchResponse, Error = tower_grpc::Status> + Send>; type WatchFuture = future::FutureResult<Response<Self::WatchStream>, tower_grpc::Status>; fn watch(&mut self, request: Request<spike_proto::WatchRequest>) -> Self::WatchFuture { use std::thread; let (tx, rx) = mpsc::channel(4); let watch_request: spike_proto::WatchRequest = request.into_inner(); let rooms = self.state.rooms.lock().unwrap(); let room: Option<&Vec<String>> = rooms.get(&watch_request.room); if room.is_none() { return future::err(Status::new(Code::NotFound, "room unknown")); } // We clone only the messages for the room. It'd be better if we didn't // have to clone at all. let mut room: Vec<String> = room.unwrap().clone(); drop(rooms); // It's a little unfortunate that we spawn a thread for this. I wonder, // can we avoid this thread? thread::spawn(move || { let mut tx = tx.wait(); // TODO don't unwrap, signal error back up for msg in room.drain(..) { tx.send(spike_proto::WatchResponse { msg }).unwrap(); } }); let rx = rx.map_err(|_| unimplemented!()); future::ok(Response::new(Box::new(rx))) } } pub fn main() { ::env_logger::init(); let threads = num_cpus::get(); let spike = Spike { state: Arc::new(State { rooms: Mutex::new(HashMap::new()), }), }; let service = spike_proto::server::SpikeServer::new(spike); let h2_settings = Default::default(); let h2 = Arc::new(Mutex::new(tower_h2::Server::new( service, h2_settings, DefaultExecutor::current(), ))); let mut root_cert_store = RootCertStore::empty(); root_cert_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS); let config = ServerConfig::new(AllowAnyAuthenticatedClient::new(root_cert_store)); let tls_acceptor = TlsAcceptor::from(Arc::new(config)); let addr = "0.0.0.0:10011".parse().unwrap(); let bind = TcpListener::bind(&addr).expect("bind"); let serve = bind .incoming() .for_each(move |tls_sock| { let addr = tls_sock.peer_addr().ok(); if let Err(e) = tls_sock.set_nodelay(true) { return Err(e); } info!("New connection from addr={:?}", addr); let h2_inner = h2.clone(); let done = tls_acceptor .accept(tls_sock) .and_then(move |sock| { let serve = h2_inner.lock().unwrap().serve(sock); tokio::spawn(serve.map_err(|e| error!("h2 error: {:?}", e))); Ok(()) }) .map_err(move |err| error!("TLS error: {:?} - {:?}", err, addr)); tokio::spawn(done); Ok(()) }) .map_err(|e| error!("accept error: {}", e)); let mut rt = tokio::runtime::Builder::new() .core_threads(threads) .build() .unwrap(); rt.spawn(serve); info!( "Started server with {} threads, listening on {}", threads, addr ); rt.shutdown_on_idle().wait().unwrap(); }
use alloc::vec::Vec; pub unsafe fn deallocate<T>(ptr: *mut T, capacity: usize) { let _vec: Vec<T> = Vec::from_raw_parts(ptr, 0, capacity); // Let it drop. }
use cql_ffi::statement::CassStatement; use cql_bindgen::CassPrepared as _CassPrepared; use cql_bindgen::cass_prepared_free; use cql_bindgen::cass_prepared_bind; //use cql_bindgen::cass_prepared_parameter_name; //use cql_bindgen::cass_prepared_parameter_data_type; //use cql_bindgen::cass_prepared_parameter_data_type_by_name; //use cql_bindgen::cass_prepared_parameter_data_type_by_name_n; pub struct CassPrepared(pub *const _CassPrepared); unsafe impl Sync for CassPrepared{} unsafe impl Send for CassPrepared{} impl Drop for CassPrepared { fn drop(&mut self) { unsafe { cass_prepared_free(self.0) } } } impl CassPrepared { pub fn bind(&self) -> CassStatement { unsafe { CassStatement(cass_prepared_bind(self.0)) } } }
use input_i_scanner::InputIScanner; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),+); $n: expr) => { std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>() }; ($t: ty; $n: expr) => { std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>() }; } let (n, x) = scan!((usize, usize)); let a = scan!(usize; n); let mut seen = vec![false; n]; let mut cur = x - 1; seen[cur] = true; loop { cur = a[cur] - 1; if seen[cur] { break; } seen[cur] = true; } let mut ans = 0; for i in 0..n { if seen[i] { ans += 1; } } println!("{}", ans); }
use std::{collections::HashMap, sync::Arc}; use tokio::{ fs::File, io::{AsyncRead, AsyncWrite}, sync::mpsc::Sender, }; use crate::{ config::Config, fs, fs::FileInfo, sync::file_events_buffer::FileEventsBuffer, sync::SyncEvent, IronCarrierError, }; use crate::network::streaming::{FileReceiver, FileSender, FrameMessage, FrameReader, FrameWriter}; type RpcResult<T> = Result<T, IronCarrierError>; pub(crate) struct ServerPeerHandler<'a, TReader, TWriter> where TReader: AsyncRead + Unpin, TWriter: AsyncWrite + Unpin, { config: &'a Config, frame_writer: FrameWriter<TWriter>, frame_reader: FrameReader<TReader>, file_sender: FileSender<TWriter>, file_receiver: FileReceiver<'a, TReader>, socket_addr: String, sync_notifier: Option<Arc<tokio::sync::Notify>>, bounce_invalid_messages: bool, } impl<'a, TReader, TWriter> ServerPeerHandler<'a, TReader, TWriter> where TReader: AsyncRead + Unpin, TWriter: AsyncWrite + Unpin, { pub fn new( config: &'a Config, frame_reader: FrameReader<TReader>, frame_writer: FrameWriter<TWriter>, file_receiver: FileReceiver<'a, TReader>, file_sender: FileSender<TWriter>, socket_addr: String, ) -> Self { Self { config, frame_reader, frame_writer, file_sender, file_receiver, socket_addr, sync_notifier: None, bounce_invalid_messages: false, } } fn should_sync_file(&self, remote_file: &FileInfo) -> bool { !remote_file.is_local_file_newer(&self.config) } async fn get_file_list(&self, alias: &str) -> RpcResult<Vec<FileInfo>> { let path = self .config .paths .get(alias) .ok_or_else(|| IronCarrierError::AliasNotAvailable(alias.to_owned()))?; crate::fs::walk_path(path, &self.config.ignore, alias) .await .map_err(|_| IronCarrierError::IOReadingError) } async fn server_sync_hash(&self) -> RpcResult<HashMap<String, u64>> { crate::fs::get_hash_for_alias(&self.config.paths, &self.config.ignore) .await .map_err(|_| IronCarrierError::IOReadingError) } pub async fn close(&mut self) { if self.sync_notifier.is_some() { self.sync_notifier.as_ref().unwrap().notify_one(); self.sync_notifier = None; } } pub async fn handle_events<'b>( &mut self, sync_events: Sender<SyncEvent>, file_events_buffer: &'b FileEventsBuffer, ) -> crate::Result<()> { loop { match self.frame_reader.next_frame().await? { Some(mut message) => match message.frame_ident() { "set_peer_port" => { let port = message.next_arg::<u32>()?; log::debug!("peer requested to change port to {}", port); self.socket_addr = format!("{}:{}", self.socket_addr, port); self.frame_writer .write_frame("set_peer_port".into()) .await?; } "server_sync_hash" => { log::debug!("peer requested sync hash"); let response = FrameMessage::new("server_sync_hash") .with_arg(&self.server_sync_hash().await)?; self.frame_writer.write_frame(response).await?; } "query_file_list" => { let alias = message.next_arg::<String>()?; log::debug!("peer requested file list for alias {}", alias); let response = FrameMessage::new("query_file_list") .with_arg(&self.get_file_list(&alias).await)?; self.frame_writer.write_frame(response).await?; } "create_or_update_file" => { let remote_file = message.next_arg::<FileInfo>()?; log::debug!("peer request to send file {:?}", remote_file.path); if self.should_sync_file(&remote_file) { let file_handle = self.file_receiver.prepare_file_transfer(remote_file); let response = FrameMessage::new("create_or_update_file") .with_arg(&file_handle)?; self.frame_writer.write_frame(response).await?; self.file_receiver.wait_files(&file_events_buffer).await?; } else { let response = FrameMessage::new("create_or_update_file").with_arg(&0u64)?; self.frame_writer.write_frame(response).await?; } } "request_file" => { let remote_file = message.next_arg::<FileInfo>()?; let file_handle = message.next_arg::<u64>()?; log::debug!("peer request file {:?}", remote_file.path); let file_path = remote_file.get_absolute_path(&self.config)?; log::debug!("sending file to peer: {}", remote_file.size.unwrap()); let mut file = File::open(file_path).await?; self.frame_writer.write_frame("request_file".into()).await?; self.file_sender.send_file(file_handle, &mut file).await?; log::debug!("file sent {:?}", remote_file.path); } "delete_file" => { let remote_file = message.next_arg::<FileInfo>()?; log::debug!("peer requested to delete file {:?}", remote_file.path); file_events_buffer.add_event(&remote_file, &self.socket_addr); fs::delete_file(&remote_file, &self.config).await?; self.frame_writer.write_frame("delete_file".into()).await?; } "move_file" => { let src_file = message.next_arg::<FileInfo>()?; let dest_file = message.next_arg::<FileInfo>()?; log::debug!( "peer requested to move file {:?} to {:?}", src_file.path, dest_file.path ); file_events_buffer.add_event(&src_file, &self.socket_addr); file_events_buffer.add_event(&dest_file, &self.socket_addr); fs::move_file(&src_file, &dest_file, &self.config).await?; self.frame_writer.write_frame("move_file".into()).await?; } "init_sync" => { log::debug!("peer requested to start sync"); let sync_starter = Arc::new(tokio::sync::Notify::new()); let sync_ended = Arc::new(tokio::sync::Notify::new()); sync_events .send(SyncEvent::PeerRequestedSync( self.socket_addr.clone(), sync_starter.clone(), sync_ended.clone(), )) .await?; log::debug!("waiting for sync schedule"); sync_starter.notified().await; log::info!("init sync with peer"); self.frame_writer.write_frame("init_sync".into()).await?; self.sync_notifier = Some(sync_ended); } "finish_sync" => { let two_way_sync = message.next_arg::<bool>()?; log::debug!("peer is finishing sync"); self.sync_notifier.as_ref().unwrap().notify_one(); self.sync_notifier = None; if two_way_sync { log::debug!("schedulling sync back with peer"); sync_events .send(SyncEvent::EnqueueSyncToPeer( self.socket_addr.clone(), false, )) .await?; } self.frame_writer.write_frame("finish_sync".into()).await?; } message_name => { if self.bounce_invalid_messages { self.frame_writer.write_frame(message_name.into()).await?; } else { return Err(IronCarrierError::ParseCommandError.into()); } } }, None => { if self.sync_notifier.is_some() { self.sync_notifier.as_ref().unwrap().notify_one(); self.sync_notifier = None; } return Ok(()); } } } } } #[cfg(test)] mod tests { use std::{ path::{Path, PathBuf}, time::Duration, }; use tokio::io::DuplexStream; use crate::network::streaming::{file_streamers, frame_stream}; use super::*; fn sample_config(test_folder: &str) -> Arc<Config> { Arc::new( Config::parse_content(format!( "port = 8090 [paths] a = \"./tmp/{}\"", test_folder )) .unwrap(), ) } fn create_tmp_file(path: &Path, contents: &str) { if !path.parent().unwrap().exists() { std::fs::create_dir_all(path.parent().unwrap()).unwrap(); } std::fs::write(path, contents).unwrap(); } async fn create_peer_handler( test_folder: &str, command_stream: DuplexStream, file_stream: DuplexStream, ) { let config = sample_config(test_folder); let (events_tx, _) = tokio::sync::mpsc::channel(10); let files_event_buffer = Arc::new(FileEventsBuffer::new(config.clone())); let (frame_reader, frame_writer) = frame_stream(command_stream); let (file_receiver, file_sender) = file_streamers(file_stream, &config, "".into()); let mut server_peer_handler = ServerPeerHandler::new( &config, frame_reader, frame_writer, file_receiver, file_sender, "".to_owned(), ); server_peer_handler.bounce_invalid_messages = true; server_peer_handler .handle_events(events_tx, &files_event_buffer) .await .unwrap(); } #[tokio::test()] async fn server_handler_can_reply_messages() { let (client_stream, server_stream) = tokio::io::duplex(10); let (_, server_file_stream) = tokio::io::duplex(10); tokio::spawn(async move { create_peer_handler( "server_handler_can_reply_messages", server_stream, server_file_stream, ) .await; }); let (mut reader, mut writer) = frame_stream(client_stream); writer.write_frame("ping".into()).await.unwrap(); assert_eq!( reader.next_frame().await.unwrap().unwrap().frame_ident(), "ping" ); } #[tokio::test] async fn server_reply_query_file_list() -> crate::Result<()> { create_tmp_file( Path::new("./tmp/server_reply_query_file_list/file_1"), "some content", ); let (client_stream, server_stream) = tokio::io::duplex(10); let (_, server_file_stream) = tokio::io::duplex(10); tokio::spawn(async move { create_peer_handler( "server_reply_query_file_list", server_stream, server_file_stream, ) .await; }); let (mut reader, mut writer) = frame_stream(client_stream); let message = FrameMessage::new("query_file_list").with_arg(&"a")?; writer.write_frame(message).await?; let mut response = reader.next_frame().await?.unwrap(); assert_eq!(response.frame_ident(), "query_file_list"); let files = response.next_arg::<RpcResult<Vec<FileInfo>>>()??; assert_eq!(files.len(), 1); assert_eq!(files[0].path, Path::new("file_1")); let message = FrameMessage::new("query_file_list").with_arg(&"b")?; writer.write_frame(message).await?; let mut response = reader.next_frame().await?.unwrap(); let files = response.next_arg::<RpcResult<Vec<FileInfo>>>()?; assert!(files.is_err()); std::fs::remove_dir_all("./tmp/server_reply_query_file_list")?; Ok(()) } #[tokio::test] async fn server_can_receive_files() -> crate::Result<()> { let (client_stream, server_stream) = tokio::io::duplex(10); let (client_file_stream, server_file_stream) = tokio::io::duplex(10); let (mut reader, mut writer) = frame_stream(client_stream); let mut file_sender = FileSender::new(client_file_stream); tokio::spawn(async move { create_peer_handler( "server_can_receive_files", server_stream, server_file_stream, ) .await; }); let mut file_content: &[u8] = b"Some file content"; let file_size = file_content.len() as u64; let modified_at = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH)? .as_secs(); let file_info = FileInfo { alias: "a".to_owned(), path: PathBuf::from("subpath/new_file.txt"), size: Some(file_size), created_at: Some(0), modified_at: Some(modified_at), deleted_at: None, }; let message = FrameMessage::new("create_or_update_file").with_arg(&file_info)?; writer.write_frame(message).await?; let mut response = reader.next_frame().await?.unwrap(); assert_eq!(response.frame_ident(), "create_or_update_file"); let file_handle: u64 = response.next_arg()?; file_sender .send_file(file_handle, &mut file_content) .await?; tokio::time::sleep(Duration::from_secs(1)).await; let file_meta = std::fs::metadata("./tmp/server_can_receive_files/subpath/new_file.txt")?; assert_eq!(file_meta.len(), file_size); std::fs::remove_dir_all("./tmp/server_can_receive_files")?; Ok(()) } #[tokio::test] async fn server_can_delete_files() -> crate::Result<()> { create_tmp_file(Path::new("./tmp/server_can_delete_files/file_1"), ""); let (client_stream, server_stream) = tokio::io::duplex(10); let (_, server_file_stream) = tokio::io::duplex(10); let (mut reader, mut writer) = frame_stream(client_stream); tokio::spawn(async move { create_peer_handler("server_can_delete_files", server_stream, server_file_stream).await; }); { let file_info = FileInfo { alias: "a".to_owned(), path: PathBuf::from("file_1"), size: None, created_at: None, modified_at: None, deleted_at: None, }; let message = FrameMessage::new("delete_file").with_arg(&file_info)?; writer.write_frame(message).await?; let response = reader.next_frame().await?.unwrap(); assert_eq!(response.frame_ident(), "delete_file"); assert!(!Path::new("./tmp/server_can_delete_files/file_1").exists()); std::fs::remove_dir_all("./tmp/server_can_delete_files")?; } Ok(()) } #[tokio::test] async fn server_can_move_files() -> crate::Result<()> { create_tmp_file(Path::new("./tmp/server_can_move_files/file_1"), ""); let (client_stream, server_stream) = tokio::io::duplex(10); let (_, server_file_stream) = tokio::io::duplex(10); let (mut reader, mut writer) = frame_stream(client_stream); tokio::spawn(async move { create_peer_handler("server_can_move_files", server_stream, server_file_stream).await; }); { let src = FileInfo { alias: "a".to_owned(), path: PathBuf::from("file_1"), size: None, created_at: None, modified_at: None, deleted_at: None, }; let dst = FileInfo { alias: "a".to_owned(), path: PathBuf::from("file_2"), size: None, created_at: None, modified_at: None, deleted_at: None, }; let message = FrameMessage::new("move_file") .with_arg(&src)? .with_arg(&dst)?; writer.write_frame(message).await?; let response = reader.next_frame().await?.unwrap(); assert_eq!(response.frame_ident(), "move_file"); assert!(!Path::new("./tmp/server_can_move_files/file_1").exists()); assert!(Path::new("./tmp/server_can_move_files/file_2").exists()); std::fs::remove_dir_all("./tmp/server_can_move_files")?; } Ok(()) } #[tokio::test] async fn server_can_send_files() -> crate::Result<()> { let file_size = b"Some file content".len() as u64; create_tmp_file( Path::new("./tmp/server_can_send_files/file_1"), "Some file content", ); let (client_stream, server_stream) = tokio::io::duplex(10); let (client_file_stream, server_file_stream) = tokio::io::duplex(10); let (mut reader, mut writer) = frame_stream(client_stream); tokio::spawn(async move { create_peer_handler("server_can_send_files", server_stream, server_file_stream).await; }); { let modified_at = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH)? .as_secs(); let file_info = FileInfo { alias: "a".to_owned(), path: PathBuf::from("file_1"), size: Some(file_size), created_at: None, modified_at: Some(modified_at), deleted_at: None, }; let config = sample_config("server_can_send_files_2"); let mut receiver = FileReceiver::new(client_file_stream, &config, "a".into()); let message = FrameMessage::new("request_file") .with_arg(&file_info)? .with_arg(&receiver.prepare_file_transfer(file_info))?; writer.write_frame(message).await?; let response = reader.next_frame().await?.unwrap(); assert_eq!(response.frame_ident(), "request_file"); let events_buffer = FileEventsBuffer::new(config.clone()); receiver.wait_files(&events_buffer).await?; assert!(Path::new("./tmp/server_can_send_files_2/file_1").exists()); std::fs::remove_dir_all("./tmp/server_can_send_files")?; std::fs::remove_dir_all("./tmp/server_can_send_files_2")?; } Ok(()) } }
// `without_binary_errors_badarg` in unit tests // `with_utf8_binary_without_base_errors_badarg` in unit tests test_stdout!(with_binary_with_integer_in_base_returns_integer, "2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n"); // `with_binary_without_integer_in_base_errors_badarg` in unit tests
//!Game rounds logic mod operating_round; mod priv_auction; mod stock_round; pub use operating_round::OperatingRound; pub use priv_auction::PrivAuction; pub use stock_round::StockRound;
#[doc = "Reader of register APB1RSTR"] pub type R = crate::R<u32, super::APB1RSTR>; #[doc = "Writer for register APB1RSTR"] pub type W = crate::W<u32, super::APB1RSTR>; #[doc = "Register APB1RSTR `reset()`'s with value 0"] impl crate::ResetValue for super::APB1RSTR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `COMPRST`"] pub type COMPRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMPRST`"] pub struct COMPRST_W<'a> { w: &'a mut W, } impl<'a> COMPRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } #[doc = "Reader of field `DACRST`"] pub type DACRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DACRST`"] pub struct DACRST_W<'a> { w: &'a mut W, } impl<'a> DACRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `PWRRST`"] pub type PWRRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PWRRST`"] pub struct PWRRST_W<'a> { w: &'a mut W, } impl<'a> PWRRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `USBRST`"] pub type USBRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USBRST`"] pub struct USBRST_W<'a> { w: &'a mut W, } impl<'a> USBRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `I2C2RST`"] pub type I2C2RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `I2C2RST`"] pub struct I2C2RST_W<'a> { w: &'a mut W, } impl<'a> I2C2RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `I2C1RST`"] pub type I2C1RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `I2C1RST`"] pub struct I2C1RST_W<'a> { w: &'a mut W, } impl<'a> I2C1RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `UART5RST`"] pub type UART5RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UART5RST`"] pub struct UART5RST_W<'a> { w: &'a mut W, } impl<'a> UART5RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `UART4RST`"] pub type UART4RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UART4RST`"] pub struct UART4RST_W<'a> { w: &'a mut W, } impl<'a> UART4RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `USART3RST`"] pub type USART3RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USART3RST`"] pub struct USART3RST_W<'a> { w: &'a mut W, } impl<'a> USART3RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `USART2RST`"] pub type USART2RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USART2RST`"] pub struct USART2RST_W<'a> { w: &'a mut W, } impl<'a> USART2RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `SPI3RST`"] pub type SPI3RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SPI3RST`"] pub struct SPI3RST_W<'a> { w: &'a mut W, } impl<'a> SPI3RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `SPI2RST`"] pub type SPI2RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SPI2RST`"] pub struct SPI2RST_W<'a> { w: &'a mut W, } impl<'a> SPI2RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `WWDRST`"] pub type WWDRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WWDRST`"] pub struct WWDRST_W<'a> { w: &'a mut W, } impl<'a> WWDRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `LCDRST`"] pub type LCDRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LCDRST`"] pub struct LCDRST_W<'a> { w: &'a mut W, } impl<'a> LCDRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `TIM7RST`"] pub type TIM7RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM7RST`"] pub struct TIM7RST_W<'a> { w: &'a mut W, } impl<'a> TIM7RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `TIM6RST`"] pub type TIM6RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM6RST`"] pub struct TIM6RST_W<'a> { w: &'a mut W, } impl<'a> TIM6RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `TIM5RST`"] pub type TIM5RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM5RST`"] pub struct TIM5RST_W<'a> { w: &'a mut W, } impl<'a> TIM5RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `TIM4RST`"] pub type TIM4RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM4RST`"] pub struct TIM4RST_W<'a> { w: &'a mut W, } impl<'a> TIM4RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `TIM3RST`"] pub type TIM3RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM3RST`"] pub struct TIM3RST_W<'a> { w: &'a mut W, } impl<'a> TIM3RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `TIM2RST`"] pub type TIM2RST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIM2RST`"] pub struct TIM2RST_W<'a> { w: &'a mut W, } impl<'a> TIM2RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 31 - COMP interface reset"] #[inline(always)] pub fn comprst(&self) -> COMPRST_R { COMPRST_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 29 - DAC interface reset"] #[inline(always)] pub fn dacrst(&self) -> DACRST_R { DACRST_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 28 - Power interface reset"] #[inline(always)] pub fn pwrrst(&self) -> PWRRST_R { PWRRST_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 23 - USB reset"] #[inline(always)] pub fn usbrst(&self) -> USBRST_R { USBRST_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 22 - I2C 2 reset"] #[inline(always)] pub fn i2c2rst(&self) -> I2C2RST_R { I2C2RST_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 21 - I2C 1 reset"] #[inline(always)] pub fn i2c1rst(&self) -> I2C1RST_R { I2C1RST_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - UART 5 reset"] #[inline(always)] pub fn uart5rst(&self) -> UART5RST_R { UART5RST_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 19 - UART 4 reset"] #[inline(always)] pub fn uart4rst(&self) -> UART4RST_R { UART4RST_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - USART 3 reset"] #[inline(always)] pub fn usart3rst(&self) -> USART3RST_R { USART3RST_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - USART 2 reset"] #[inline(always)] pub fn usart2rst(&self) -> USART2RST_R { USART2RST_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 15 - SPI 3 reset"] #[inline(always)] pub fn spi3rst(&self) -> SPI3RST_R { SPI3RST_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 14 - SPI 2 reset"] #[inline(always)] pub fn spi2rst(&self) -> SPI2RST_R { SPI2RST_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 11 - Window watchdog reset"] #[inline(always)] pub fn wwdrst(&self) -> WWDRST_R { WWDRST_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 9 - LCD reset"] #[inline(always)] pub fn lcdrst(&self) -> LCDRST_R { LCDRST_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 5 - Timer 7 reset"] #[inline(always)] pub fn tim7rst(&self) -> TIM7RST_R { TIM7RST_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - Timer 6reset"] #[inline(always)] pub fn tim6rst(&self) -> TIM6RST_R { TIM6RST_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - Timer 5 reset"] #[inline(always)] pub fn tim5rst(&self) -> TIM5RST_R { TIM5RST_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - Timer 4 reset"] #[inline(always)] pub fn tim4rst(&self) -> TIM4RST_R { TIM4RST_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Timer 3 reset"] #[inline(always)] pub fn tim3rst(&self) -> TIM3RST_R { TIM3RST_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Timer 2 reset"] #[inline(always)] pub fn tim2rst(&self) -> TIM2RST_R { TIM2RST_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 31 - COMP interface reset"] #[inline(always)] pub fn comprst(&mut self) -> COMPRST_W { COMPRST_W { w: self } } #[doc = "Bit 29 - DAC interface reset"] #[inline(always)] pub fn dacrst(&mut self) -> DACRST_W { DACRST_W { w: self } } #[doc = "Bit 28 - Power interface reset"] #[inline(always)] pub fn pwrrst(&mut self) -> PWRRST_W { PWRRST_W { w: self } } #[doc = "Bit 23 - USB reset"] #[inline(always)] pub fn usbrst(&mut self) -> USBRST_W { USBRST_W { w: self } } #[doc = "Bit 22 - I2C 2 reset"] #[inline(always)] pub fn i2c2rst(&mut self) -> I2C2RST_W { I2C2RST_W { w: self } } #[doc = "Bit 21 - I2C 1 reset"] #[inline(always)] pub fn i2c1rst(&mut self) -> I2C1RST_W { I2C1RST_W { w: self } } #[doc = "Bit 20 - UART 5 reset"] #[inline(always)] pub fn uart5rst(&mut self) -> UART5RST_W { UART5RST_W { w: self } } #[doc = "Bit 19 - UART 4 reset"] #[inline(always)] pub fn uart4rst(&mut self) -> UART4RST_W { UART4RST_W { w: self } } #[doc = "Bit 18 - USART 3 reset"] #[inline(always)] pub fn usart3rst(&mut self) -> USART3RST_W { USART3RST_W { w: self } } #[doc = "Bit 17 - USART 2 reset"] #[inline(always)] pub fn usart2rst(&mut self) -> USART2RST_W { USART2RST_W { w: self } } #[doc = "Bit 15 - SPI 3 reset"] #[inline(always)] pub fn spi3rst(&mut self) -> SPI3RST_W { SPI3RST_W { w: self } } #[doc = "Bit 14 - SPI 2 reset"] #[inline(always)] pub fn spi2rst(&mut self) -> SPI2RST_W { SPI2RST_W { w: self } } #[doc = "Bit 11 - Window watchdog reset"] #[inline(always)] pub fn wwdrst(&mut self) -> WWDRST_W { WWDRST_W { w: self } } #[doc = "Bit 9 - LCD reset"] #[inline(always)] pub fn lcdrst(&mut self) -> LCDRST_W { LCDRST_W { w: self } } #[doc = "Bit 5 - Timer 7 reset"] #[inline(always)] pub fn tim7rst(&mut self) -> TIM7RST_W { TIM7RST_W { w: self } } #[doc = "Bit 4 - Timer 6reset"] #[inline(always)] pub fn tim6rst(&mut self) -> TIM6RST_W { TIM6RST_W { w: self } } #[doc = "Bit 3 - Timer 5 reset"] #[inline(always)] pub fn tim5rst(&mut self) -> TIM5RST_W { TIM5RST_W { w: self } } #[doc = "Bit 2 - Timer 4 reset"] #[inline(always)] pub fn tim4rst(&mut self) -> TIM4RST_W { TIM4RST_W { w: self } } #[doc = "Bit 1 - Timer 3 reset"] #[inline(always)] pub fn tim3rst(&mut self) -> TIM3RST_W { TIM3RST_W { w: self } } #[doc = "Bit 0 - Timer 2 reset"] #[inline(always)] pub fn tim2rst(&mut self) -> TIM2RST_W { TIM2RST_W { w: self } } }
use crate::round; pub struct Game { pub controller: round::Controller, } impl Game { pub fn welcome(&self) { println!("1 2 3 "); println!("4 5 6 "); println!("7 8 9 "); } pub fn playing(&self) -> bool { self.controller.has_next_round() } pub fn play(&mut self) { self.controller.run(); } pub fn gameover(&self) { println!("---------"); println!("Game Over"); } }
#[doc = "Reader of register CR"] pub type R = crate::R<u32, super::CR>; #[doc = "Writer for register CR"] pub type W = crate::W<u32, super::CR>; #[doc = "Register CR `reset()`'s with value 0x83"] impl crate::ResetValue for super::CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x83 } } #[doc = "Internal high-speed clock enable\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum HSION_A { #[doc = "0: Clock Off"] OFF = 0, #[doc = "1: Clock On"] ON = 1, } impl From<HSION_A> for bool { #[inline(always)] fn from(variant: HSION_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `HSION`"] pub type HSION_R = crate::R<bool, HSION_A>; impl HSION_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSION_A { match self.bits { false => HSION_A::OFF, true => HSION_A::ON, } } #[doc = "Checks if the value of the field is `OFF`"] #[inline(always)] pub fn is_off(&self) -> bool { *self == HSION_A::OFF } #[doc = "Checks if the value of the field is `ON`"] #[inline(always)] pub fn is_on(&self) -> bool { *self == HSION_A::ON } } #[doc = "Write proxy for field `HSION`"] pub struct HSION_W<'a> { w: &'a mut W, } impl<'a> HSION_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSION_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "High Speed Internal clock enable in Stop mode"] pub type HSIKERON_A = HSION_A; #[doc = "Reader of field `HSIKERON`"] pub type HSIKERON_R = crate::R<bool, HSION_A>; #[doc = "Write proxy for field `HSIKERON`"] pub struct HSIKERON_W<'a> { w: &'a mut W, } impl<'a> HSIKERON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSIKERON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "HSI clock ready flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum HSIRDY_A { #[doc = "0: Clock not ready"] NOTREADY = 0, #[doc = "1: Clock ready"] READY = 1, } impl From<HSIRDY_A> for bool { #[inline(always)] fn from(variant: HSIRDY_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `HSIRDY`"] pub type HSIRDY_R = crate::R<bool, HSIRDY_A>; impl HSIRDY_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSIRDY_A { match self.bits { false => HSIRDY_A::NOTREADY, true => HSIRDY_A::READY, } } #[doc = "Checks if the value of the field is `NOTREADY`"] #[inline(always)] pub fn is_not_ready(&self) -> bool { *self == HSIRDY_A::NOTREADY } #[doc = "Checks if the value of the field is `READY`"] #[inline(always)] pub fn is_ready(&self) -> bool { *self == HSIRDY_A::READY } } #[doc = "Write proxy for field `HSIRDY`"] pub struct HSIRDY_W<'a> { w: &'a mut W, } impl<'a> HSIRDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSIRDY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut W { self.variant(HSIRDY_A::NOTREADY) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(HSIRDY_A::READY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "HSI clock divider\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum HSIDIV_A { #[doc = "0: No division"] DIV1 = 0, #[doc = "1: Division by 2"] DIV2 = 1, #[doc = "2: Division by 4"] DIV4 = 2, #[doc = "3: Division by 8"] DIV8 = 3, } impl From<HSIDIV_A> for u8 { #[inline(always)] fn from(variant: HSIDIV_A) -> Self { variant as _ } } #[doc = "Reader of field `HSIDIV`"] pub type HSIDIV_R = crate::R<u8, HSIDIV_A>; impl HSIDIV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSIDIV_A { match self.bits { 0 => HSIDIV_A::DIV1, 1 => HSIDIV_A::DIV2, 2 => HSIDIV_A::DIV4, 3 => HSIDIV_A::DIV8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIV1`"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == HSIDIV_A::DIV1 } #[doc = "Checks if the value of the field is `DIV2`"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == HSIDIV_A::DIV2 } #[doc = "Checks if the value of the field is `DIV4`"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == HSIDIV_A::DIV4 } #[doc = "Checks if the value of the field is `DIV8`"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == HSIDIV_A::DIV8 } } #[doc = "Write proxy for field `HSIDIV`"] pub struct HSIDIV_W<'a> { w: &'a mut W, } impl<'a> HSIDIV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSIDIV_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "No division"] #[inline(always)] pub fn div1(self) -> &'a mut W { self.variant(HSIDIV_A::DIV1) } #[doc = "Division by 2"] #[inline(always)] pub fn div2(self) -> &'a mut W { self.variant(HSIDIV_A::DIV2) } #[doc = "Division by 4"] #[inline(always)] pub fn div4(self) -> &'a mut W { self.variant(HSIDIV_A::DIV4) } #[doc = "Division by 8"] #[inline(always)] pub fn div8(self) -> &'a mut W { self.variant(HSIDIV_A::DIV8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 3)) | (((value as u32) & 0x03) << 3); self.w } } #[doc = "HSI divider flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum HSIDIVF_A { #[doc = "0: New HSIDIV ratio has not yet propagated to hsi_ck"] NOTPROPAGATED = 0, #[doc = "1: HSIDIV ratio has propagated to hsi_ck"] PROPAGATED = 1, } impl From<HSIDIVF_A> for bool { #[inline(always)] fn from(variant: HSIDIVF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `HSIDIVF`"] pub type HSIDIVF_R = crate::R<bool, HSIDIVF_A>; impl HSIDIVF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSIDIVF_A { match self.bits { false => HSIDIVF_A::NOTPROPAGATED, true => HSIDIVF_A::PROPAGATED, } } #[doc = "Checks if the value of the field is `NOTPROPAGATED`"] #[inline(always)] pub fn is_not_propagated(&self) -> bool { *self == HSIDIVF_A::NOTPROPAGATED } #[doc = "Checks if the value of the field is `PROPAGATED`"] #[inline(always)] pub fn is_propagated(&self) -> bool { *self == HSIDIVF_A::PROPAGATED } } #[doc = "Write proxy for field `HSIDIVF`"] pub struct HSIDIVF_W<'a> { w: &'a mut W, } impl<'a> HSIDIVF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSIDIVF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "New HSIDIV ratio has not yet propagated to hsi_ck"] #[inline(always)] pub fn not_propagated(self) -> &'a mut W { self.variant(HSIDIVF_A::NOTPROPAGATED) } #[doc = "HSIDIV ratio has propagated to hsi_ck"] #[inline(always)] pub fn propagated(self) -> &'a mut W { self.variant(HSIDIVF_A::PROPAGATED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "CSI clock enable"] pub type CSION_A = HSION_A; #[doc = "Reader of field `CSION`"] pub type CSION_R = crate::R<bool, HSION_A>; #[doc = "Write proxy for field `CSION`"] pub struct CSION_W<'a> { w: &'a mut W, } impl<'a> CSION_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CSION_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "CSI clock ready flag"] pub type CSIRDY_A = HSIRDY_A; #[doc = "Reader of field `CSIRDY`"] pub type CSIRDY_R = crate::R<bool, HSIRDY_A>; #[doc = "Write proxy for field `CSIRDY`"] pub struct CSIRDY_W<'a> { w: &'a mut W, } impl<'a> CSIRDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CSIRDY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut W { self.variant(HSIRDY_A::NOTREADY) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(HSIRDY_A::READY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "CSI clock enable in Stop mode"] pub type CSIKERON_A = HSION_A; #[doc = "Reader of field `CSIKERON`"] pub type CSIKERON_R = crate::R<bool, HSION_A>; #[doc = "Write proxy for field `CSIKERON`"] pub struct CSIKERON_W<'a> { w: &'a mut W, } impl<'a> CSIKERON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CSIKERON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "RC48 clock enable"] pub type HSI48ON_A = HSION_A; #[doc = "Reader of field `HSI48ON`"] pub type HSI48ON_R = crate::R<bool, HSION_A>; #[doc = "Write proxy for field `HSI48ON`"] pub struct HSI48ON_W<'a> { w: &'a mut W, } impl<'a> HSI48ON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSI48ON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "RC48 clock ready flag"] pub type HSI48RDY_A = HSIRDY_A; #[doc = "Reader of field `HSI48RDY`"] pub type HSI48RDY_R = crate::R<bool, HSIRDY_A>; #[doc = "Write proxy for field `HSI48RDY`"] pub struct HSI48RDY_W<'a> { w: &'a mut W, } impl<'a> HSI48RDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSI48RDY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut W { self.variant(HSIRDY_A::NOTREADY) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(HSIRDY_A::READY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "D1 domain clocks ready flag"] pub type D1CKRDY_A = HSIRDY_A; #[doc = "Reader of field `D1CKRDY`"] pub type D1CKRDY_R = crate::R<bool, HSIRDY_A>; #[doc = "Write proxy for field `D1CKRDY`"] pub struct D1CKRDY_W<'a> { w: &'a mut W, } impl<'a> D1CKRDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: D1CKRDY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut W { self.variant(HSIRDY_A::NOTREADY) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(HSIRDY_A::READY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "D2 domain clocks ready flag"] pub type D2CKRDY_A = HSIRDY_A; #[doc = "Reader of field `D2CKRDY`"] pub type D2CKRDY_R = crate::R<bool, HSIRDY_A>; #[doc = "Write proxy for field `D2CKRDY`"] pub struct D2CKRDY_W<'a> { w: &'a mut W, } impl<'a> D2CKRDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: D2CKRDY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut W { self.variant(HSIRDY_A::NOTREADY) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(HSIRDY_A::READY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "HSE clock enable"] pub type HSEON_A = HSION_A; #[doc = "Reader of field `HSEON`"] pub type HSEON_R = crate::R<bool, HSION_A>; #[doc = "Write proxy for field `HSEON`"] pub struct HSEON_W<'a> { w: &'a mut W, } impl<'a> HSEON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSEON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "HSE clock ready flag"] pub type HSERDY_A = HSIRDY_A; #[doc = "Reader of field `HSERDY`"] pub type HSERDY_R = crate::R<bool, HSIRDY_A>; #[doc = "Write proxy for field `HSERDY`"] pub struct HSERDY_W<'a> { w: &'a mut W, } impl<'a> HSERDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSERDY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut W { self.variant(HSIRDY_A::NOTREADY) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(HSIRDY_A::READY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "HSE clock bypass\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum HSEBYP_A { #[doc = "0: HSE crystal oscillator not bypassed"] NOTBYPASSED = 0, #[doc = "1: HSE crystal oscillator bypassed with external clock"] BYPASSED = 1, } impl From<HSEBYP_A> for bool { #[inline(always)] fn from(variant: HSEBYP_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `HSEBYP`"] pub type HSEBYP_R = crate::R<bool, HSEBYP_A>; impl HSEBYP_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSEBYP_A { match self.bits { false => HSEBYP_A::NOTBYPASSED, true => HSEBYP_A::BYPASSED, } } #[doc = "Checks if the value of the field is `NOTBYPASSED`"] #[inline(always)] pub fn is_not_bypassed(&self) -> bool { *self == HSEBYP_A::NOTBYPASSED } #[doc = "Checks if the value of the field is `BYPASSED`"] #[inline(always)] pub fn is_bypassed(&self) -> bool { *self == HSEBYP_A::BYPASSED } } #[doc = "Write proxy for field `HSEBYP`"] pub struct HSEBYP_W<'a> { w: &'a mut W, } impl<'a> HSEBYP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSEBYP_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "HSE crystal oscillator not bypassed"] #[inline(always)] pub fn not_bypassed(self) -> &'a mut W { self.variant(HSEBYP_A::NOTBYPASSED) } #[doc = "HSE crystal oscillator bypassed with external clock"] #[inline(always)] pub fn bypassed(self) -> &'a mut W { self.variant(HSEBYP_A::BYPASSED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "HSE Clock Security System enable"] pub type HSECSSON_A = HSION_A; #[doc = "Reader of field `HSECSSON`"] pub type HSECSSON_R = crate::R<bool, HSION_A>; #[doc = "Write proxy for field `HSECSSON`"] pub struct HSECSSON_W<'a> { w: &'a mut W, } impl<'a> HSECSSON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSECSSON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "PLL1 enable"] pub type PLL1ON_A = HSION_A; #[doc = "Reader of field `PLL1ON`"] pub type PLL1ON_R = crate::R<bool, HSION_A>; #[doc = "Write proxy for field `PLL1ON`"] pub struct PLL1ON_W<'a> { w: &'a mut W, } impl<'a> PLL1ON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL1ON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "PLL1 clock ready flag"] pub type PLL1RDY_A = HSIRDY_A; #[doc = "Reader of field `PLL1RDY`"] pub type PLL1RDY_R = crate::R<bool, HSIRDY_A>; #[doc = "Write proxy for field `PLL1RDY`"] pub struct PLL1RDY_W<'a> { w: &'a mut W, } impl<'a> PLL1RDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL1RDY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut W { self.variant(HSIRDY_A::NOTREADY) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(HSIRDY_A::READY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "PLL2 enable"] pub type PLL2ON_A = HSION_A; #[doc = "Reader of field `PLL2ON`"] pub type PLL2ON_R = crate::R<bool, HSION_A>; #[doc = "Write proxy for field `PLL2ON`"] pub struct PLL2ON_W<'a> { w: &'a mut W, } impl<'a> PLL2ON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL2ON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "PLL2 clock ready flag"] pub type PLL2RDY_A = HSIRDY_A; #[doc = "Reader of field `PLL2RDY`"] pub type PLL2RDY_R = crate::R<bool, HSIRDY_A>; #[doc = "Write proxy for field `PLL2RDY`"] pub struct PLL2RDY_W<'a> { w: &'a mut W, } impl<'a> PLL2RDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL2RDY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut W { self.variant(HSIRDY_A::NOTREADY) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(HSIRDY_A::READY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "PLL3 enable"] pub type PLL3ON_A = HSION_A; #[doc = "Reader of field `PLL3ON`"] pub type PLL3ON_R = crate::R<bool, HSION_A>; #[doc = "Write proxy for field `PLL3ON`"] pub struct PLL3ON_W<'a> { w: &'a mut W, } impl<'a> PLL3ON_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL3ON_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(HSION_A::OFF) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(HSION_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "PLL3 clock ready flag"] pub type PLL3RDY_A = HSIRDY_A; #[doc = "Reader of field `PLL3RDY`"] pub type PLL3RDY_R = crate::R<bool, HSIRDY_A>; #[doc = "Write proxy for field `PLL3RDY`"] pub struct PLL3RDY_W<'a> { w: &'a mut W, } impl<'a> PLL3RDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL3RDY_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut W { self.variant(HSIRDY_A::NOTREADY) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut W { self.variant(HSIRDY_A::READY) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } impl R { #[doc = "Bit 0 - Internal high-speed clock enable"] #[inline(always)] pub fn hsion(&self) -> HSION_R { HSION_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - High Speed Internal clock enable in Stop mode"] #[inline(always)] pub fn hsikeron(&self) -> HSIKERON_R { HSIKERON_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - HSI clock ready flag"] #[inline(always)] pub fn hsirdy(&self) -> HSIRDY_R { HSIRDY_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bits 3:4 - HSI clock divider"] #[inline(always)] pub fn hsidiv(&self) -> HSIDIV_R { HSIDIV_R::new(((self.bits >> 3) & 0x03) as u8) } #[doc = "Bit 5 - HSI divider flag"] #[inline(always)] pub fn hsidivf(&self) -> HSIDIVF_R { HSIDIVF_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 7 - CSI clock enable"] #[inline(always)] pub fn csion(&self) -> CSION_R { CSION_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - CSI clock ready flag"] #[inline(always)] pub fn csirdy(&self) -> CSIRDY_R { CSIRDY_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - CSI clock enable in Stop mode"] #[inline(always)] pub fn csikeron(&self) -> CSIKERON_R { CSIKERON_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 12 - RC48 clock enable"] #[inline(always)] pub fn hsi48on(&self) -> HSI48ON_R { HSI48ON_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - RC48 clock ready flag"] #[inline(always)] pub fn hsi48rdy(&self) -> HSI48RDY_R { HSI48RDY_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - D1 domain clocks ready flag"] #[inline(always)] pub fn d1ckrdy(&self) -> D1CKRDY_R { D1CKRDY_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - D2 domain clocks ready flag"] #[inline(always)] pub fn d2ckrdy(&self) -> D2CKRDY_R { D2CKRDY_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - HSE clock enable"] #[inline(always)] pub fn hseon(&self) -> HSEON_R { HSEON_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - HSE clock ready flag"] #[inline(always)] pub fn hserdy(&self) -> HSERDY_R { HSERDY_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - HSE clock bypass"] #[inline(always)] pub fn hsebyp(&self) -> HSEBYP_R { HSEBYP_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - HSE Clock Security System enable"] #[inline(always)] pub fn hsecsson(&self) -> HSECSSON_R { HSECSSON_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 24 - PLL1 enable"] #[inline(always)] pub fn pll1on(&self) -> PLL1ON_R { PLL1ON_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - PLL1 clock ready flag"] #[inline(always)] pub fn pll1rdy(&self) -> PLL1RDY_R { PLL1RDY_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - PLL2 enable"] #[inline(always)] pub fn pll2on(&self) -> PLL2ON_R { PLL2ON_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - PLL2 clock ready flag"] #[inline(always)] pub fn pll2rdy(&self) -> PLL2RDY_R { PLL2RDY_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - PLL3 enable"] #[inline(always)] pub fn pll3on(&self) -> PLL3ON_R { PLL3ON_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - PLL3 clock ready flag"] #[inline(always)] pub fn pll3rdy(&self) -> PLL3RDY_R { PLL3RDY_R::new(((self.bits >> 29) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Internal high-speed clock enable"] #[inline(always)] pub fn hsion(&mut self) -> HSION_W { HSION_W { w: self } } #[doc = "Bit 1 - High Speed Internal clock enable in Stop mode"] #[inline(always)] pub fn hsikeron(&mut self) -> HSIKERON_W { HSIKERON_W { w: self } } #[doc = "Bit 2 - HSI clock ready flag"] #[inline(always)] pub fn hsirdy(&mut self) -> HSIRDY_W { HSIRDY_W { w: self } } #[doc = "Bits 3:4 - HSI clock divider"] #[inline(always)] pub fn hsidiv(&mut self) -> HSIDIV_W { HSIDIV_W { w: self } } #[doc = "Bit 5 - HSI divider flag"] #[inline(always)] pub fn hsidivf(&mut self) -> HSIDIVF_W { HSIDIVF_W { w: self } } #[doc = "Bit 7 - CSI clock enable"] #[inline(always)] pub fn csion(&mut self) -> CSION_W { CSION_W { w: self } } #[doc = "Bit 8 - CSI clock ready flag"] #[inline(always)] pub fn csirdy(&mut self) -> CSIRDY_W { CSIRDY_W { w: self } } #[doc = "Bit 9 - CSI clock enable in Stop mode"] #[inline(always)] pub fn csikeron(&mut self) -> CSIKERON_W { CSIKERON_W { w: self } } #[doc = "Bit 12 - RC48 clock enable"] #[inline(always)] pub fn hsi48on(&mut self) -> HSI48ON_W { HSI48ON_W { w: self } } #[doc = "Bit 13 - RC48 clock ready flag"] #[inline(always)] pub fn hsi48rdy(&mut self) -> HSI48RDY_W { HSI48RDY_W { w: self } } #[doc = "Bit 14 - D1 domain clocks ready flag"] #[inline(always)] pub fn d1ckrdy(&mut self) -> D1CKRDY_W { D1CKRDY_W { w: self } } #[doc = "Bit 15 - D2 domain clocks ready flag"] #[inline(always)] pub fn d2ckrdy(&mut self) -> D2CKRDY_W { D2CKRDY_W { w: self } } #[doc = "Bit 16 - HSE clock enable"] #[inline(always)] pub fn hseon(&mut self) -> HSEON_W { HSEON_W { w: self } } #[doc = "Bit 17 - HSE clock ready flag"] #[inline(always)] pub fn hserdy(&mut self) -> HSERDY_W { HSERDY_W { w: self } } #[doc = "Bit 18 - HSE clock bypass"] #[inline(always)] pub fn hsebyp(&mut self) -> HSEBYP_W { HSEBYP_W { w: self } } #[doc = "Bit 19 - HSE Clock Security System enable"] #[inline(always)] pub fn hsecsson(&mut self) -> HSECSSON_W { HSECSSON_W { w: self } } #[doc = "Bit 24 - PLL1 enable"] #[inline(always)] pub fn pll1on(&mut self) -> PLL1ON_W { PLL1ON_W { w: self } } #[doc = "Bit 25 - PLL1 clock ready flag"] #[inline(always)] pub fn pll1rdy(&mut self) -> PLL1RDY_W { PLL1RDY_W { w: self } } #[doc = "Bit 26 - PLL2 enable"] #[inline(always)] pub fn pll2on(&mut self) -> PLL2ON_W { PLL2ON_W { w: self } } #[doc = "Bit 27 - PLL2 clock ready flag"] #[inline(always)] pub fn pll2rdy(&mut self) -> PLL2RDY_W { PLL2RDY_W { w: self } } #[doc = "Bit 28 - PLL3 enable"] #[inline(always)] pub fn pll3on(&mut self) -> PLL3ON_W { PLL3ON_W { w: self } } #[doc = "Bit 29 - PLL3 clock ready flag"] #[inline(always)] pub fn pll3rdy(&mut self) -> PLL3RDY_W { PLL3RDY_W { w: self } } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const CLSID_DeviceIoControl: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x12d3e372_874b_457d_9fdf_73977778686c); #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CreateDeviceAccessInstance<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(deviceinterfacepath: Param0, desiredaccess: u32) -> ::windows::core::Result<ICreateDeviceAccessAsync> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CreateDeviceAccessInstance(deviceinterfacepath: super::super::Foundation::PWSTR, desiredaccess: u32, createasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } let mut result__: <ICreateDeviceAccessAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); CreateDeviceAccessInstance(deviceinterfacepath.into_param().abi(), ::core::mem::transmute(desiredaccess), &mut result__).from_abi::<ICreateDeviceAccessAsync>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub const DEV_PORT_1394: u32 = 8u32; pub const DEV_PORT_ARTI: u32 = 7u32; pub const DEV_PORT_COM1: u32 = 2u32; pub const DEV_PORT_COM2: u32 = 3u32; pub const DEV_PORT_COM3: u32 = 4u32; pub const DEV_PORT_COM4: u32 = 5u32; pub const DEV_PORT_DIAQ: u32 = 6u32; pub const DEV_PORT_MAX: u32 = 9u32; pub const DEV_PORT_MIN: u32 = 1u32; pub const DEV_PORT_SIM: u32 = 1u32; pub const DEV_PORT_USB: u32 = 9u32; pub const ED_AUDIO_1: i32 = 1i32; pub const ED_AUDIO_10: i32 = 512i32; pub const ED_AUDIO_11: i32 = 1024i32; pub const ED_AUDIO_12: i32 = 2048i32; pub const ED_AUDIO_13: i32 = 4096i32; pub const ED_AUDIO_14: i32 = 8192i32; pub const ED_AUDIO_15: i32 = 16384i32; pub const ED_AUDIO_16: i32 = 32768i32; pub const ED_AUDIO_17: i32 = 65536i32; pub const ED_AUDIO_18: i32 = 131072i32; pub const ED_AUDIO_19: i32 = 262144i32; pub const ED_AUDIO_2: i32 = 2i32; pub const ED_AUDIO_20: i32 = 524288i32; pub const ED_AUDIO_21: i32 = 1048576i32; pub const ED_AUDIO_22: i32 = 2097152i32; pub const ED_AUDIO_23: i32 = 4194304i32; pub const ED_AUDIO_24: i32 = 8388608i32; pub const ED_AUDIO_3: i32 = 4i32; pub const ED_AUDIO_4: i32 = 8i32; pub const ED_AUDIO_5: i32 = 16i32; pub const ED_AUDIO_6: i32 = 32i32; pub const ED_AUDIO_7: i32 = 64i32; pub const ED_AUDIO_8: i32 = 128i32; pub const ED_AUDIO_9: i32 = 256i32; pub const ED_AUDIO_ALL: u32 = 268435456u32; pub const ED_BASE: i32 = 4096i32; pub const ED_BOTTOM: u32 = 4u32; pub const ED_CENTER: u32 = 512u32; pub const ED_LEFT: u32 = 256u32; pub const ED_MIDDLE: u32 = 2u32; pub const ED_RIGHT: u32 = 1024u32; pub const ED_TOP: u32 = 1u32; pub const ED_VIDEO: i32 = 33554432i32; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICreateDeviceAccessAsync(pub ::windows::core::IUnknown); impl ICreateDeviceAccessAsync { pub unsafe fn Cancel(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Wait(&self, timeout: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(timeout)).ok() } pub unsafe fn Close(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn GetResult<T: ::windows::core::Interface>(&self) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } } unsafe impl ::windows::core::Interface for ICreateDeviceAccessAsync { type Vtable = ICreateDeviceAccessAsync_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3474628f_683d_42d2_abcb_db018c6503bc); } impl ::core::convert::From<ICreateDeviceAccessAsync> for ::windows::core::IUnknown { fn from(value: ICreateDeviceAccessAsync) -> Self { value.0 } } impl ::core::convert::From<&ICreateDeviceAccessAsync> for ::windows::core::IUnknown { fn from(value: &ICreateDeviceAccessAsync) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICreateDeviceAccessAsync { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ICreateDeviceAccessAsync { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICreateDeviceAccessAsync_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, timeout: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, deviceaccess: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IDeviceIoControl(pub ::windows::core::IUnknown); impl IDeviceIoControl { pub unsafe fn DeviceIoControlSync(&self, iocontrolcode: u32, inputbuffer: *const u8, inputbuffersize: u32, outputbuffer: *mut u8, outputbuffersize: u32, bytesreturned: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(iocontrolcode), ::core::mem::transmute(inputbuffer), ::core::mem::transmute(inputbuffersize), ::core::mem::transmute(outputbuffer), ::core::mem::transmute(outputbuffersize), ::core::mem::transmute(bytesreturned)).ok() } pub unsafe fn DeviceIoControlAsync<'a, Param5: ::windows::core::IntoParam<'a, IDeviceRequestCompletionCallback>>(&self, iocontrolcode: u32, inputbuffer: *const u8, inputbuffersize: u32, outputbuffer: *mut u8, outputbuffersize: u32, requestcompletioncallback: Param5, cancelcontext: *mut usize) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)( ::core::mem::transmute_copy(self), ::core::mem::transmute(iocontrolcode), ::core::mem::transmute(inputbuffer), ::core::mem::transmute(inputbuffersize), ::core::mem::transmute(outputbuffer), ::core::mem::transmute(outputbuffersize), requestcompletioncallback.into_param().abi(), ::core::mem::transmute(cancelcontext), ) .ok() } pub unsafe fn CancelOperation(&self, cancelcontext: usize) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(cancelcontext)).ok() } } unsafe impl ::windows::core::Interface for IDeviceIoControl { type Vtable = IDeviceIoControl_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9eefe161_23ab_4f18_9b49_991b586ae970); } impl ::core::convert::From<IDeviceIoControl> for ::windows::core::IUnknown { fn from(value: IDeviceIoControl) -> Self { value.0 } } impl ::core::convert::From<&IDeviceIoControl> for ::windows::core::IUnknown { fn from(value: &IDeviceIoControl) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDeviceIoControl { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDeviceIoControl { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IDeviceIoControl_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iocontrolcode: u32, inputbuffer: *const u8, inputbuffersize: u32, outputbuffer: *mut u8, outputbuffersize: u32, bytesreturned: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iocontrolcode: u32, inputbuffer: *const u8, inputbuffersize: u32, outputbuffer: *mut u8, outputbuffersize: u32, requestcompletioncallback: ::windows::core::RawPtr, cancelcontext: *mut usize) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cancelcontext: usize) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IDeviceRequestCompletionCallback(pub ::windows::core::IUnknown); impl IDeviceRequestCompletionCallback { pub unsafe fn Invoke(&self, requestresult: ::windows::core::HRESULT, bytesreturned: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(requestresult), ::core::mem::transmute(bytesreturned)).ok() } } unsafe impl ::windows::core::Interface for IDeviceRequestCompletionCallback { type Vtable = IDeviceRequestCompletionCallback_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x999bad24_9acd_45bb_8669_2a2fc0288b04); } impl ::core::convert::From<IDeviceRequestCompletionCallback> for ::windows::core::IUnknown { fn from(value: IDeviceRequestCompletionCallback) -> Self { value.0 } } impl ::core::convert::From<&IDeviceRequestCompletionCallback> for ::windows::core::IUnknown { fn from(value: &IDeviceRequestCompletionCallback) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDeviceRequestCompletionCallback { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDeviceRequestCompletionCallback { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IDeviceRequestCompletionCallback_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requestresult: ::windows::core::HRESULT, bytesreturned: u32) -> ::windows::core::HRESULT, );
use crossbeam; use std::sync::Arc; use std::fs::{self, File}; use std::io::{self, Read}; use std::path::Path; use std::collections::HashMap; use std::ffi::OsStr; use liquid::Value; use walkdir::WalkDir; use document::Document; pub fn build(source: &Path, dest: &Path, layout_str: &str, posts_str: &str) -> io::Result<()> { // TODO make configurable let template_extensions = [OsStr::new("tpl"), OsStr::new("md")]; let layouts_path = source.join(layout_str); let posts_path = source.join(posts_str); let mut layouts: HashMap<String, String> = HashMap::new(); let walker = WalkDir::new(&layouts_path).into_iter(); // go through the layout directory and add // filename -> text content to the layout map for entry in walker.filter_map(|e| e.ok()).filter(|e| e.file_type().is_file()) { let mut text = String::new(); try!(File::open(entry.path()).expect(&format!("Failed to open file {:?}", entry)).read_to_string(&mut text)); layouts.insert(entry.path() .file_name() .expect(&format!("No file name from {:?}", entry)) .to_str() .expect(&format!("Invalid UTF-8 in {:?}", entry)) .to_owned(), text); } let mut documents = vec![]; let mut post_data = vec![]; let walker = WalkDir::new(&source).into_iter(); for entry in walker.filter_map(|e| e.ok()).filter(|e| e.file_type().is_file()) { if template_extensions.contains(&entry.path() .extension() .unwrap_or(OsStr::new(""))) && entry.path().parent() != Some(layouts_path.as_path()) { let doc = parse_document(&entry.path(), source); if entry.path().parent() == Some(posts_path.as_path()) { post_data.push(Value::Object(doc.get_attributes())); } documents.push(doc); } } let mut handles = vec![]; // generate documents (in parallel) // TODO I'm probably underutilizing crossbeam crossbeam::scope(|scope| { let post_data = Arc::new(post_data); let layouts = Arc::new(layouts); for doc in &documents { let post_data = post_data.clone(); let layouts = layouts.clone(); let handle = scope.spawn(move || { doc.create_file(dest, &layouts, &post_data) }); handles.push(handle); } }); for handle in handles { try!(handle.join()); } // copy all remaining files in the source to the destination if source != dest { let walker = WalkDir::new(&source) .into_iter() .filter_map(|e| e.ok()) // filter out files to not copy .filter(|f| { let p = f.path(); // don't copy hidden files !p.file_name() .expect(&format!("No file name for {:?}", p)) .to_str() .unwrap_or("") .starts_with(".") && // don't copy templates !template_extensions.contains(&p.extension().unwrap_or(OsStr::new(""))) && // this is madness p != dest && // don't copy from the layouts folder p != layouts_path.as_path() }); for entry in walker { let relative = entry.path() .to_str().expect(&format!("Invalid UTF-8 in {:?}", entry)) .split(source.to_str().expect(&format!("Invalid UTF-8 in {:?}", source))) .last().expect(&format!("Empty path")); if try!(entry.metadata()).is_dir() { try!(fs::create_dir_all(&dest.join(relative))); } else { try!(fs::copy(entry.path(), &dest.join(relative))); } } } Ok(()) } fn parse_document(path: &Path, source: &Path) -> Document { let attributes = extract_attributes(path); let content = extract_content(path).expect(&format!("No content in {:?}", path)); let new_path = path.to_str() .expect(&format!("Invalid UTF-8 in {:?}", path)) .split(source.to_str() .expect(&format!("Invalid UTF-8 in {:?}", source))) .last() .expect(&format!("Empty path")); let markdown = path.extension().unwrap_or(OsStr::new("")) == OsStr::new("md"); Document::new(new_path.to_owned(), attributes, content, markdown) } fn parse_file(path: &Path) -> io::Result<String> { let mut file = try!(File::open(path)); let mut text = String::new(); try!(file.read_to_string(&mut text)); Ok(text) } fn extract_attributes(path: &Path) -> HashMap<String, String> { let mut attributes = HashMap::new(); attributes.insert("name".to_owned(), path.file_stem() .expect(&format!("No file stem for {:?}", path)) .to_str() .expect(&format!("Invalid UTF-8 in file stem for {:?}", path)) .to_owned()); let content = parse_file(path).expect(&format!("Failed to parse {:?}", path)); if content.contains("---") { let mut content_splits = content.split("---"); let attribute_string = content_splits.nth(0).expect(&format!("Empty content")); for attribute_line in attribute_string.split("\n") { if !attribute_line.contains(':') { continue; } let attribute_split: Vec<&str> = attribute_line.split(':').collect(); let key = attribute_split[0].trim_matches(' ').to_owned(); let value = attribute_split[1].trim_matches(' ').to_owned(); attributes.insert(key, value); } } return attributes; } fn extract_content(path: &Path) -> io::Result<String> { let content = try!(parse_file(path)); if content.contains("---") { let mut content_splits = content.split("---"); return Ok(content_splits.nth(1).expect(&format!("No content after header")).to_owned()); } return Ok(content); }
#![allow(unused_imports)] use std::path::Path; mod utils; use utils::read_file; mod solutions; use solutions::a::main as solve; #[test] fn a() { let v = file!(); let base_path = Path::new(v); let file_stem = base_path.file_stem().unwrap(); let file_parent = base_path.parent().unwrap(); let input_path = format!( "{}/inputs/{}.txt", file_parent.to_str().unwrap(), file_stem.to_str().unwrap() ); let solution_path = format!( "{}/solutions/{}.rs", file_parent.to_str().unwrap(), file_stem.to_str().unwrap() ); let output_path = format!( "{}/outputs/{}", file_parent.to_str().unwrap(), file_stem.to_str().unwrap() ); read_file(&solve, &input_path, &solution_path, &output_path); }
mod hid; pub use hid::*;
use ggez::graphics as ggraphics; use ggez::input::mouse::MouseButton; use ggez::*; use std::env; use std::path; use torifune::core::Clock; use torifune::core::Updatable; use torifune::device; use torifune::graphics::object as tobj; use torifune::graphics::object::*; use torifune::graphics::drawable::*; use torifune::numeric; struct State { frames: usize, vertical_text: VerticalText, vertical_text2: VerticalText, mouse: device::MouseListener, key: device::KeyboardListener, image: tobj::SimpleObject, } fn sample_mouse_closure( msg: &'static str, ) -> Box<dyn Fn(&ggez::Context, Clock) -> Result<(), String>> { Box::new(move |ctx: &Context, _t| { let p = device::MouseListener::get_position(ctx); println!("{}: {}, {}", msg, p.x, p.y); Ok(()) }) } fn sample_keyboard_closure( msg: &'static str, ) -> Box<dyn Fn(&ggez::Context, Clock) -> Result<(), String>> { Box::new(move |_ctx: &Context, _t| { println!("key event ====> {}", msg); Ok(()) }) } impl State { fn new(ctx: &mut Context, image: tobj::SimpleObject) -> GameResult<State> { let font = graphics::Font::new(ctx, "/cinecaption226.ttf")?; // let mut raw_text = graphics::Text::new("Hello"); // raw_text.set_font(font, graphics::Scale {x: 48.0, y: 48.0}); let mut s = State { frames: 0, vertical_text: torifune::graphics::object::VerticalText::new( "これはテスト".to_string(), numeric::Point2f::new(0.78, 0.0), numeric::Vector2f::new(1.0, 1.0), 0.0, 0, torifune::graphics::object::FontInformation::new( font, numeric::Vector2f::new(72.0, 72.0), ggraphics::WHITE, ), ), vertical_text2: torifune::graphics::object::VerticalText::new( "これはテスト".to_string(), numeric::Point2f::new(80.78, 0.3), numeric::Vector2f::new(1.0, 1.0), 0.0, 0, torifune::graphics::object::FontInformation::new( font, numeric::Vector2f::new(72.0, 72.0), ggraphics::WHITE, ), ), mouse: device::MouseListener::new(), key: device::KeyboardListener::new_masked( vec![device::KeyInputDevice::GenericKeyboard], vec![device::VirtualKey::Action1, device::VirtualKey::Action2], ), image: image, }; Ok(s) } pub fn init(&mut self) { /* * indirect closure inserting */ let p = sample_mouse_closure("sample_closure!!"); self.mouse .register_event_handler(MouseButton::Left, device::MouseButtonEvent::Clicked, p); /* * direct closure inserting with closure returing func */ self.mouse.register_event_handler( MouseButton::Left, device::MouseButtonEvent::Pressed, sample_mouse_closure("Left button is Pressed!!"), ); /* * direct closure inserting with lambda */ self.mouse.register_event_handler( MouseButton::Left, device::MouseButtonEvent::Dragged, Box::new(|_ctx: &Context, _t| { println!("Dragging!!"); Ok(()) }), ); self.key.register_event_handler( device::VirtualKey::Action1, device::KeyboardEvent::FirstPressed, sample_keyboard_closure("Pressed!!"), ); self.key.register_event_handler( device::VirtualKey::Action2, device::KeyboardEvent::FirstPressed, Box::new(move |_ctx: &Context, _t| Ok(())), ); } } impl ggez::event::EventHandler for State { fn update(&mut self, ctx: &mut Context) -> GameResult<()> { self.mouse.update(ctx, 0); self.key.update(ctx, 0); let p = self.vertical_text.get_texture_size(ctx); println!("size: {}, {}", p.x, p.y); self.image.move_with_func(0); Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { graphics::clear(ctx, [0.0, 0.0, 0.0, 0.0].into()); let offset = self.frames as f32 / 10.0; self.image.set_alpha(0.1); self.image.draw(ctx)?; ggraphics::set_default_filter(ctx, ggraphics::FilterMode::Linear); self.vertical_text.draw(ctx); ggraphics::set_default_filter(ctx, ggraphics::FilterMode::Nearest); self.vertical_text2.draw(ctx); ggraphics::set_default_filter(ctx, ggraphics::FilterMode::Linear); graphics::present(ctx)?; self.frames += 1; if (self.frames % 100) == 0 { println!("FPS: {}", timer::fps(ctx)); } Ok(()) } } #[test] pub fn graphic_test() { let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") { let mut path = path::PathBuf::from(manifest_dir); path.push("resources"); path } else { path::PathBuf::from("./resources") }; let mut c = conf::Conf::new(); c.window_setup = conf::WindowSetup { samples: conf::NumSamples::Four, ..Default::default() }; let (ref mut ctx, ref mut event_loop) = ContextBuilder::new("test", "akichi") .add_resource_path(resource_dir) .conf(c) .build() .unwrap(); let textures = vec![std::rc::Rc::new( ggraphics::Image::new(ctx, "/ghost1.png").unwrap(), )]; let image = tobj::SimpleObject::new( MovableUniTexture::new( textures[0].clone(), torifune::numeric::Point2f::new(0.0, 0.0), torifune::numeric::Vector2f::new(1.0, 1.0), 0.0, 0, None, 0, ), vec![], ); let state = &mut State::new(ctx, image).unwrap(); state.init(); event::run(ctx, event_loop, state).unwrap(); } #[test] pub fn vertical_text() {}
//! # dynonym - The API documentation //! //! Welcome to the `dynonym` API documentation! //! //! This document is a technical reference for developers using `dynonym` as library crate. //! Since `dynonym` is mainly used as an application, you're probably more interested in a user //! guide. In that case, please have a look at the [README][readme] and consider using //! `dynonym --help`! //! //! [readme]: https://github.com/teiesti/dynonym#dynonym //! //! ## Usage //! //! In order to use `dynonym` within your project, you need to add the following dependency into //! your `Cargo.toml`: //! //! ```toml //! [dependencies] //! dynonym = "0.1" //! ``` //! //! A simple application may look like this: //! //! ```no_run //! extern crate dynonym; //! //! fn main() { //! dynonym::main() //! } //! ``` //! //! (This is actually all you need to mimic `dynonym`'s behavior since every little bit is //! implemented within the library.) //! //! ## Module structure //! //! At the top level, modules can be grouped as follows: //! //! * Modules that fulfill a certain task //! * Modules that provide a remote interface //! * [`http`]: Web server (incl. routes) //! * [`dns`]: Domain Name System update client (RFC 2136: "DNS UPDATE") //! * Modules that deal with the operating system //! * [`cli`]: Command-line argument parsing and instruction assembly //! * [`config`]: Configuration file parsing //! * [`lock`]: Lock file management //! * Modules that provide general support //! * [`types`]: Shared types (e.g. for a domain name) //! * [`errors`]: Error types and handling //! //! [`cli`]: cli/index.html //! [`config`]: config/index.html //! [`dns`]: dns/index.html //! [`http`]: http/index.html //! [`errors`]: errors/index.html //! [`types`]: types/index.html //! [`lock`]: lock/index.html #![feature( custom_derive, plugin, try_from, )] #![plugin(rocket_codegen)] #![recursion_limit="256"] // `error_chain!` can recurse deeply #![warn( // missing_docs, trivial_casts, trivial_numeric_casts, unreachable_pub, unused_extern_crates, unused_import_braces, unused_qualifications, )] extern crate bcrypt; #[macro_use] extern crate clap; extern crate ctrlc; #[macro_use] extern crate error_chain; extern crate hyper; extern crate libc; extern crate num_cpus; extern crate rocket; extern crate rpassword; #[macro_use] extern crate serde_derive; #[cfg(test)] extern crate tempfile; extern crate toml; extern crate trust_dns; extern crate trust_dns_proto; extern crate yansi; pub mod cli; pub mod config; pub mod dns; pub mod errors; pub mod http; pub mod lock; pub mod types; pub use cli::main;
//! `refs` or the references of dag-pb and other supported IPLD formats functionality. use crate::ipld::{decode_ipld, Ipld}; use crate::{Block, Ipfs, IpfsTypes}; use async_stream::stream; use cid::{self, Cid}; use futures::stream::Stream; use std::borrow::Borrow; use std::collections::HashSet; use std::collections::VecDeque; use std::fmt; /// Represents a single link in an IPLD tree encountered during a `refs` walk. #[derive(Clone, PartialEq, Eq)] pub struct Edge { /// Source document which links to [`Edge::destination`] pub source: Cid, /// The destination document pub destination: Cid, /// The name of the link, in case of dag-pb pub name: Option<String>, } impl fmt::Debug for Edge { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!( fmt, "Edge {{ source: {}, destination: {}, name: {:?} }}", self.source, self.destination, self.name ) } } #[derive(Debug, thiserror::Error)] pub enum IpldRefsError { #[error("nested ipld document parsing failed")] Block(#[from] crate::ipld::BlockError), #[error("loading failed")] Loading(#[from] crate::Error), #[error("block not found locally: {}", .0)] BlockNotFound(Cid), } pub(crate) struct IpldRefs { max_depth: Option<u64>, unique: bool, download_blocks: bool, } impl Default for IpldRefs { fn default() -> Self { IpldRefs { max_depth: None, // unlimited unique: false, download_blocks: true, } } } impl IpldRefs { /// Overrides the default maximum depth of "unlimited" with the given maximum depth. Zero is /// allowed and will result in an empty stream. #[allow(dead_code)] pub fn with_max_depth(mut self, depth: u64) -> IpldRefs { self.max_depth = Some(depth); self } /// Overrides the default of returning all links by supressing the links which have already /// been reported once. pub fn with_only_unique(mut self) -> IpldRefs { self.unique = true; self } /// Overrides the default of allowing the refs operation to fetch blocks. Useful at least /// internally in rust-ipfs to implement pinning recursively. This changes the stream's /// behaviour to stop on first block which is not found locally. pub fn with_existing_blocks(mut self) -> IpldRefs { self.download_blocks = false; self } pub fn refs_of_resolved<'a, Types, MaybeOwned, Iter>( self, ipfs: MaybeOwned, iplds: Iter, ) -> impl Stream<Item = Result<Edge, IpldRefsError>> + Send + 'a where Types: IpfsTypes, MaybeOwned: Borrow<Ipfs<Types>> + Send + 'a, Iter: IntoIterator<Item = (Cid, Ipld)> + Send + 'a, { iplds_refs_inner(ipfs, iplds, self) } } /// Gather links as edges between two documents from all of the `iplds` which represent the /// document and it's original `Cid`, as the `Ipld` can be a subtree of the document. /// /// This stream does not stop on **error**. /// /// # Differences from other implementations /// /// `js-ipfs` does seem to do a recursive descent on all links. Looking at the tests it would /// appear that `go-ipfs` implements this in similar fashion. This implementation is breadth-first /// to be simpler at least. /// /// Related: https://github.com/ipfs/js-ipfs/pull/2982 /// /// # Lifetime of returned stream /// /// Depending on how this function is called, the lifetime will be tied to the lifetime of given /// `&Ipfs` or `'static` when given ownership of `Ipfs`. pub fn iplds_refs<'a, Types, MaybeOwned, Iter>( ipfs: MaybeOwned, iplds: Iter, max_depth: Option<u64>, unique: bool, ) -> impl Stream<Item = Result<Edge, crate::ipld::BlockError>> + Send + 'a where Types: IpfsTypes, MaybeOwned: Borrow<Ipfs<Types>> + Send + 'a, Iter: IntoIterator<Item = (Cid, Ipld)> + Send + 'a, { use futures::stream::TryStreamExt; let opts = IpldRefs { max_depth, unique, download_blocks: true, }; iplds_refs_inner(ipfs, iplds, opts).map_err(|e| match e { IpldRefsError::Block(e) => e, x => unreachable!( "iplds_refs_inner should not return other errors for download_blocks: false; {}", x ), }) } fn iplds_refs_inner<'a, Types, MaybeOwned, Iter>( ipfs: MaybeOwned, iplds: Iter, opts: IpldRefs, ) -> impl Stream<Item = Result<Edge, IpldRefsError>> + Send + 'a where Types: IpfsTypes, MaybeOwned: Borrow<Ipfs<Types>> + Send + 'a, Iter: IntoIterator<Item = (Cid, Ipld)>, { let mut work = VecDeque::new(); let mut queued_or_visited = HashSet::new(); let IpldRefs { max_depth, unique, download_blocks, } = opts; let empty_stream = max_depth.map(|n| n == 0).unwrap_or(false); // double check the max_depth before filling the work and queued_or_visited up just in case we // are going to be returning an empty stream if !empty_stream { // not building these before moving the work and hashset into the stream would impose // apparently impossible bounds on `Iter`, in addition to `Send + 'a`. for (origin, ipld) in iplds { for (link_name, next_cid) in ipld_links(&origin, ipld) { if unique && !queued_or_visited.insert(next_cid.clone()) { trace!("skipping already queued {}", next_cid); continue; } work.push_back((0, next_cid, origin.clone(), link_name)); } } } stream! { if empty_stream { return; } while let Some((depth, cid, source, link_name)) = work.pop_front() { let traverse_links = match max_depth { Some(d) if d <= depth => { // important to continue instead of stopping continue; }, // no need to list links which would be filtered out Some(d) if d + 1 == depth => false, _ => true }; // if this is not bound to a local variable it'll introduce a Sync requirement on // `MaybeOwned` which we don't necessarily need. let borrowed = ipfs.borrow(); let data = if download_blocks { match borrowed.get_block(&cid).await { Ok(Block { data, .. }) => data, Err(e) => { warn!("failed to load {}, linked from {}: {}", cid, source, e); // TODO: yield error msg // unsure in which cases this happens, because we'll start to search the content // and stop only when request has been cancelled (FIXME: no way to stop this // operation) continue; } } } else { match borrowed.repo.get_block_now(&cid).await { Ok(Some(Block { data, .. })) => data, Ok(None) => { yield Err(IpldRefsError::BlockNotFound(cid.to_owned())); return; } Err(e) => { yield Err(IpldRefsError::from(e)); return; } } }; trace!(cid = %cid, "loaded next"); let ipld = match decode_ipld(&cid, &data) { Ok(ipld) => ipld, Err(e) => { warn!(cid = %cid, source = %cid, "failed to parse: {}", e); // go-ipfs on raw Qm hash: // > failed to decode Protocol Buffers: incorrectly formatted merkledag node: unmarshal failed. proto: illegal wireType 6 yield Err(e.into()); continue; } }; if traverse_links { for (link_name, next_cid) in ipld_links(&cid, ipld) { if unique && !queued_or_visited.insert(next_cid.clone()) { trace!(queued = %next_cid, "skipping already queued"); continue; } work.push_back((depth + 1, next_cid, cid.clone(), link_name)); } } yield Ok(Edge { source, destination: cid, name: link_name }); } } } fn ipld_links( cid: &Cid, ipld: Ipld, ) -> impl Iterator<Item = (Option<String>, Cid)> + Send + 'static { // a wrapping iterator without there being a libipld_base::IpldIntoIter might not be doable // with safe code let items = if cid.codec() == cid::Codec::DagProtobuf { dagpb_links(ipld) } else { ipld.iter() .filter_map(|val| match val { Ipld::Link(cid) => Some(cid), _ => None, }) .cloned() // only dag-pb ever has any link names, probably because in cbor the "name" on the LHS // might have a different meaning from a "link name" in dag-pb ... Doesn't seem // immediatedly obvious why this is done. .map(|cid| (None, cid)) .collect::<Vec<(Option<String>, Cid)>>() }; items.into_iter() } /// Special handling for the structure created while loading dag-pb as ipld. /// /// # Panics /// /// If the dag-pb ipld tree doesn't conform to expectations, as in, we are out of sync with the /// libipld crate. This is on purpose. fn dagpb_links(ipld: Ipld) -> Vec<(Option<String>, Cid)> { let links = match ipld { Ipld::Map(mut m) => m.remove("Links"), // lets assume this means "no links" _ => return Vec::new(), }; let links = match links { Some(Ipld::List(v)) => v, x => panic!("Expected dag-pb2ipld \"Links\" to be a list, got: {:?}", x), }; links .into_iter() .enumerate() .filter_map(|(i, ipld)| { match ipld { Ipld::Map(mut m) => { let link = match m.remove("Hash") { Some(Ipld::Link(cid)) => cid, Some(x) => panic!( "Expected dag-pb2ipld \"Links[{}]/Hash\" to be a link, got: {:?}", i, x ), None => return None, }; let name = match m.remove("Name") { // not sure of this, not covered by tests, though these are only // present for multi-block files so maybe it's better to panic Some(Ipld::String(s)) if s == "/" => { unimplemented!("Slashes as the name of link") } Some(Ipld::String(s)) => Some(s), Some(x) => panic!( "Expected dag-pb2ipld \"Links[{}]/Name\" to be a string, got: {:?}", i, x ), // not too sure of this, this could be the index as string as well? None => unimplemented!( "Default name for dag-pb2ipld links, should it be index?" ), }; Some((name, link)) } x => panic!( "Expected dag-pb2ipld \"Links[{}]\" to be a map, got: {:?}", i, x ), } }) .collect() } #[cfg(test)] mod tests { use super::{ipld_links, iplds_refs, Edge}; use crate::ipld::{decode_ipld, validate}; use crate::{Block, Node}; use cid::Cid; use futures::stream::TryStreamExt; use hex_literal::hex; use std::collections::HashSet; use std::convert::TryFrom; #[test] fn dagpb_links() { // this is the same as in ipfs-http::v0::refs::path::tests::walk_dagpb_links let payload = hex!( "12330a2212206aad27d7e2fc815cd15bf679535062565dc927a831547281 fc0af9e5d7e67c74120b6166726963616e2e747874180812340a221220fd 36ac5279964db0cba8f7fa45f8c4c44ef5e2ff55da85936a378c96c9c632 04120c616d6572696361732e747874180812360a2212207564c20415869d 77a8a40ca68a9158e397dd48bdff1325cdb23c5bcd181acd17120e617573 7472616c69616e2e7478741808" ); let cid = Cid::try_from("QmbrFTo4s6H23W6wmoZKQC2vSogGeQ4dYiceSqJddzrKVa").unwrap(); let decoded = decode_ipld(&cid, &payload).unwrap(); let links = ipld_links(&cid, decoded) .map(|(name, _)| name.unwrap()) .collect::<Vec<_>>(); assert_eq!(links, ["african.txt", "americas.txt", "australian.txt",]); } #[tokio::test] async fn all_refs_from_root() { let Node { ipfs, .. } = preloaded_testing_ipfs().await; let (root, dag0, unixfs0, dag1, unixfs1) = ( // this is the dag with content: [dag0, unixfs0, dag1, unixfs1] "bafyreihpc3vupfos5yqnlakgpjxtyx3smkg26ft7e2jnqf3qkyhromhb64", // {foo: dag1, bar: unixfs0} "bafyreidquig3arts3bmee53rutt463hdyu6ff4zeas2etf2h2oh4dfms44", "QmPJ4A6Su27ABvvduX78x2qdWMzkdAYxqeH5TVrHeo3xyy", // {foo: unixfs1} "bafyreibvjvcv745gig4mvqs4hctx4zfkono4rjejm2ta6gtyzkqxfjeily", "QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL", ); let root_block = ipfs.get_block(&Cid::try_from(root).unwrap()).await.unwrap(); let ipld = decode_ipld(root_block.cid(), root_block.data()).unwrap(); let all_edges: Vec<_> = iplds_refs(ipfs, vec![(root_block.cid, ipld)], None, false) .map_ok( |Edge { source, destination, .. }| (source.to_string(), destination.to_string()), ) .try_collect() .await .unwrap(); // not sure why go-ipfs outputs this order, this is more like dfs? let expected = [ (root, dag0), (dag0, unixfs0), (dag0, dag1), (dag1, unixfs1), (root, unixfs0), (root, dag1), (dag1, unixfs1), (root, unixfs1), ]; println!("found edges:\n{:#?}", all_edges); assert_edges(&expected, all_edges.as_slice()); } #[tokio::test] async fn all_unique_refs_from_root() { let Node { ipfs, .. } = preloaded_testing_ipfs().await; let (root, dag0, unixfs0, dag1, unixfs1) = ( // this is the dag with content: [dag0, unixfs0, dag1, unixfs1] "bafyreihpc3vupfos5yqnlakgpjxtyx3smkg26ft7e2jnqf3qkyhromhb64", // {foo: dag1, bar: unixfs0} "bafyreidquig3arts3bmee53rutt463hdyu6ff4zeas2etf2h2oh4dfms44", "QmPJ4A6Su27ABvvduX78x2qdWMzkdAYxqeH5TVrHeo3xyy", // {foo: unixfs1} "bafyreibvjvcv745gig4mvqs4hctx4zfkono4rjejm2ta6gtyzkqxfjeily", "QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL", ); let root_block = ipfs.get_block(&Cid::try_from(root).unwrap()).await.unwrap(); let ipld = decode_ipld(root_block.cid(), root_block.data()).unwrap(); let destinations: HashSet<_> = iplds_refs(ipfs, vec![(root_block.cid, ipld)], None, true) .map_ok(|Edge { destination, .. }| destination.to_string()) .try_collect() .await .unwrap(); // go-ipfs output: // bafyreihpc3vupfos5yqnlakgpjxtyx3smkg26ft7e2jnqf3qkyhromhb64 -> bafyreidquig3arts3bmee53rutt463hdyu6ff4zeas2etf2h2oh4dfms44 // bafyreihpc3vupfos5yqnlakgpjxtyx3smkg26ft7e2jnqf3qkyhromhb64 -> QmPJ4A6Su27ABvvduX78x2qdWMzkdAYxqeH5TVrHeo3xyy // bafyreihpc3vupfos5yqnlakgpjxtyx3smkg26ft7e2jnqf3qkyhromhb64 -> bafyreibvjvcv745gig4mvqs4hctx4zfkono4rjejm2ta6gtyzkqxfjeily // bafyreihpc3vupfos5yqnlakgpjxtyx3smkg26ft7e2jnqf3qkyhromhb64 -> QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL let expected = [dag0, unixfs0, dag1, unixfs1] .iter() .map(|&s| String::from(s)) .collect::<HashSet<_>>(); let diff = destinations .symmetric_difference(&expected) .map(|s| s.as_str()) .collect::<Vec<&str>>(); assert!(diff.is_empty(), "{:?}", diff); } fn assert_edges(expected: &[(&str, &str)], actual: &[(String, String)]) { let expected: HashSet<_> = expected.iter().map(|&(a, b)| (a, b)).collect(); let actual: HashSet<_> = actual .iter() .map(|(a, b)| (a.as_str(), b.as_str())) .collect(); let diff: Vec<_> = expected.symmetric_difference(&actual).collect(); assert!(diff.is_empty(), "{:#?}", diff); } async fn preloaded_testing_ipfs() -> Node { let ipfs = Node::new("test_node").await; let blocks = [ ( // echo -n '{ "foo": { "/": "bafyreibvjvcv745gig4mvqs4hctx4zfkono4rjejm2ta6gtyzkqxfjeily" }, "bar": { "/": "QmPJ4A6Su27ABvvduX78x2qdWMzkdAYxqeH5TVrHeo3xyy" } }' | /ipfs dag put "bafyreidquig3arts3bmee53rutt463hdyu6ff4zeas2etf2h2oh4dfms44", &hex!("a263626172d82a58230012200e317512b6f9f86e015a154cb97a9ddcdc7e372cccceb3947921634953c6537463666f6fd82a58250001711220354d455ff3a641b8cac25c38a77e64aa735dc8a48966a60f1a78caa172a4885e")[..] ), ( // echo barfoo > file2 && ipfs add file2 "QmPJ4A6Su27ABvvduX78x2qdWMzkdAYxqeH5TVrHeo3xyy", &hex!("0a0d08021207626172666f6f0a1807")[..] ), ( // echo -n '{ "foo": { "/": "QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL" } }' | ipfs dag put "bafyreibvjvcv745gig4mvqs4hctx4zfkono4rjejm2ta6gtyzkqxfjeily", &hex!("a163666f6fd82a582300122031c3d57080d8463a3c63b2923df5a1d40ad7a73eae5a14af584213e5f504ac33")[..] ), ( // echo foobar > file1 && ipfs add file1 "QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL", &hex!("0a0d08021207666f6f6261720a1807")[..] ), ( // echo -e '[{"/":"bafyreidquig3arts3bmee53rutt463hdyu6ff4zeas2etf2h2oh4dfms44"},{"/":"QmPJ4A6Su27ABvvduX78x2qdWMzkdAYxqeH5TVrHeo3xyy"},{"/":"bafyreibvjvcv745gig4mvqs4hctx4zfkono4rjejm2ta6gtyzkqxfjeily"},{"/":"QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL"}]' | ./ipfs dag put "bafyreihpc3vupfos5yqnlakgpjxtyx3smkg26ft7e2jnqf3qkyhromhb64", &hex!("84d82a5825000171122070a20db04672d858427771a4e7cf6ce3c53c52f32404b4499747d38fc19592e7d82a58230012200e317512b6f9f86e015a154cb97a9ddcdc7e372cccceb3947921634953c65374d82a58250001711220354d455ff3a641b8cac25c38a77e64aa735dc8a48966a60f1a78caa172a4885ed82a582300122031c3d57080d8463a3c63b2923df5a1d40ad7a73eae5a14af584213e5f504ac33")[..] ) ]; for (cid_str, data) in blocks.iter() { let cid = Cid::try_from(*cid_str).unwrap(); validate(&cid, data).unwrap(); decode_ipld(&cid, data).unwrap(); let block = Block { cid, data: (*data).into(), }; ipfs.put_block(block).await.unwrap(); } ipfs } }
pub mod test_helpers; mod file_finder_test_suite_walkdir { use crate::test_helpers::*; use hackscanner_lib::file_finder::walkdir::FileFinder; use hackscanner_lib::file_finder::FileFinderTrait; #[test] fn find_files_test() { let rules = get_rules_multiple_results(); let matches = FileFinder::new().find(get_test_dir(), &rules); assert_multiple_paths(matches); } #[test] fn find_files_one_test() { let rules = get_rules_single_result(); // Call `find` multiple times to make sure the results are cleared between calls FileFinder::new().find(get_test_dir(), &rules); let matches = FileFinder::new().find(get_test_dir(), &rules); assert_single_path(matches); } #[test] fn find_files_one_multi_threading_test() { test_multi_threading(FileFinder::new()); } }
pub extern crate image; pub extern crate vecmath; use image::Rgb; use vecmath::Vector3; pub type Vecf = Vector3<f32>; pub type Color = Rgb<u8>; pub mod scene; pub mod view;
pub mod clamp; pub mod logger; pub mod path; pub mod uv; pub use self::clamp::*; pub use self::logger::setup_logger; pub use self::path::cargo_path; pub use self::uv::*;
// calculater module to perform all kind of calculations mod calculater { // sub module for arthmetic_operations pub mod arthmetic_opertions { pub fn add (input_1: f32, input_2: f32) -> f32 { let result = input_1 + input_2; result } } } fn main() { let variable_1 = 11.2; let variable_2 = 34.0; println!("sum of {}, and {}, will be calculated using calculater module",variable_1, variable_2); // calling the module in the main function let output = crate::calculater::arthmetic_opertions::add(variable_1, variable_2); println!("sum of the given numbers is {}",output); }
extern crate structopt; use example::player::*; use example::player_connection::*; use example::{connection_handler::*, opt::*}; use spatialos_sdk::worker::connection::Connection; use spatialos_specs::*; use specs::prelude::*; use std::thread; use std::time::Duration; use structopt::StructOpt; fn main() { let opt = Opt::from_args(); let connection = match get_connection(opt) { Ok(c) => c, Err(e) => panic!("{}", e), }; println!("Connected as: {}", connection.get_worker_id()); let mut world = World::new(); world.add_resource(connection); let mut dispatcher = DispatcherBuilder::new() .with(SpatialReaderSystem, "reader", &[]) .with_barrier() .with( ClientBootstrap { has_requested_player: false, }, "", &[], ) .with(PlayerCreatorSys, "", &[]) .with(MovePlayerSys, "", &[]) .with_barrier() .with(SpatialWriterSystem, "writer", &[]) .build(); dispatcher.setup(&mut world.res); loop { dispatcher.dispatch(&world.res); thread::sleep(Duration::from_millis(30)); } }
pub mod float_to_string; use std::convert::TryInto; use std::sync::atomic::AtomicUsize; use std::sync::Arc; use num_bigint::BigInt; use num_traits::Num; use proptest::strategy::{Just, Strategy}; use proptest::test_runner::{Config, TestCaseResult, TestRunner}; use proptest::{prop_assert, prop_assert_eq}; use liblumen_alloc::erts::message::{self, Message}; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::erts::{exception, Node}; use crate::test::strategy::term::binary; use crate::test::strategy::term::binary::sub::{bit_offset, byte_count, byte_offset}; use super::strategy; pub fn arc_process_subbinary_to_arc_process_subbinary_two_less_than_length_start( (arc_process, binary): (Arc<Process>, Term), ) -> ( impl Strategy<Value = Arc<Process>>, impl Strategy<Value = Term>, impl Strategy<Value = usize>, ) { let subbinary: Boxed<SubBinary> = binary.try_into().unwrap(); let byte_count = subbinary.full_byte_len(); // `start` must be 2 less than `byte_count` so that `length` can be at least 1 // and still get a full byte ( Just(arc_process.clone()), Just(binary), (1..=(byte_count - 2)), ) } pub fn arc_process_to_arc_process_subbinary_zero_start_byte_count_length( arc_process: Arc<Process>, ) -> impl Strategy<Value = (Arc<Process>, Term, Term, Term)> { ( Just(arc_process.clone()), binary::sub::with_size_range( byte_offset(), bit_offset(), byte_count(), (1_u8..=7_u8).boxed(), arc_process.clone(), ), ) .prop_map(|(arc_process, binary)| { let subbinary: Boxed<SubBinary> = binary.try_into().unwrap(); ( arc_process.clone(), binary, arc_process.integer(0), arc_process.integer(subbinary.full_byte_len()), ) }) } pub fn external_arc_node() -> Arc<Node> { Arc::new(Node::new( 1, Atom::try_from_str("node@external").unwrap(), 0, )) } pub fn has_message(process: &Process, data: Term) -> bool { process.mailbox.lock().borrow().iter().any(|message| { &data == match message { Message::Process(message::Process { data }) => data, Message::HeapFragment(message::HeapFragment { data, .. }) => data, } }) } pub fn has_heap_message(process: &Process, data: Term) -> bool { process .mailbox .lock() .borrow() .iter() .any(|message| match message { Message::HeapFragment(message::HeapFragment { data: message_data, .. }) => message_data == &data, _ => false, }) } pub fn has_process_message(process: &Process, data: Term) -> bool { process .mailbox .lock() .borrow() .iter() .any(|message| match message { Message::Process(message::Process { data: message_data, .. }) => message_data == &data, _ => false, }) } pub fn monitor_count(process: &Process) -> usize { process.monitor_by_reference.len() } pub fn monitored_count(process: &Process) -> usize { process.monitored_pid_by_reference.len() } pub fn number_to_integer_with_float( source_file: &'static str, result: fn(&Process, Term) -> exception::Result<Term>, non_zero_assertion: fn(Term, f64, Term) -> TestCaseResult, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::float(arc_process.clone()), ) }, |(arc_process, number)| { let result = result(&arc_process, number); prop_assert!(result.is_ok()); let result_term = result.unwrap(); prop_assert!(result_term.is_integer()); let number_float: Float = number.try_into().unwrap(); let number_f64: f64 = number_float.into(); if number_f64.fract() == 0.0 { // f64::to_string() has no decimal point when there is no `fract`. let number_big_int = <BigInt as Num>::from_str_radix(&number_f64.to_string(), 10).unwrap(); let result_big_int: BigInt = result_term.try_into().unwrap(); prop_assert_eq!(number_big_int, result_big_int); Ok(()) } else { non_zero_assertion(number, number_f64, result_term) } }, ); } pub fn receive_message(process: &Process) -> Option<Term> { process .mailbox .lock() .borrow_mut() .receive(process) .map(|result| result.unwrap()) } static REGISTERED_NAME_COUNTER: AtomicUsize = AtomicUsize::new(0); pub fn registered_name() -> Term { Atom::str_to_term( format!( "registered{}", REGISTERED_NAME_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst) ) .as_str(), ) } pub fn run<S: Strategy, F: Fn(Arc<Process>) -> S>( source_file: &'static str, arc_process_fun: F, test: impl Fn(S::Value) -> TestCaseResult, ) { TestRunner::new(Config::with_source_file(source_file)) .run(&strategy::process().prop_flat_map(arc_process_fun), test) .unwrap(); } pub fn timeout_message(timer_reference: Term, message: Term, process: &Process) -> Term { timer_message("timeout", timer_reference, message, process) } pub fn timer_message(tag: &str, timer_reference: Term, message: Term, process: &Process) -> Term { process.tuple_from_slice(&[Atom::str_to_term(tag), timer_reference, message]) } pub fn with_binary_without_atom_encoding_errors_badarg( source_file: &'static str, result: fn(Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( strategy::term::is_binary(arc_process.clone()), strategy::term::is_not_atom(arc_process), ) }, |(binary, encoding)| { prop_assert_badarg!( result(binary, encoding), format!("invalid encoding name value: `{}` is not an atom", encoding) ); Ok(()) }, ); } pub fn with_binary_with_atom_without_name_encoding_errors_badarg( source_file: &'static str, result: fn(Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( strategy::term::is_binary(arc_process.clone()), strategy::term::atom::is_not_encoding(), ) }, |(binary, encoding)| { let encoding_atom: Atom = encoding.try_into().unwrap(); prop_assert_badarg!( result(binary, encoding), format!("invalid atom encoding name: '{0}' is not one of the supported values (latin1, unicode, or utf8)", encoding_atom.name()) ); Ok(()) }, ); } pub fn with_integer_returns_integer( source_file: &'static str, result: fn(&Process, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_integer(arc_process.clone()), ) }, |(arc_process, number)| { prop_assert_eq!(result(&arc_process, number), Ok(number)); Ok(()) }, ); } pub fn without_boolean_left_errors_badarg( source_file: &'static str, result: fn(Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( strategy::term::is_not_boolean(arc_process.clone()), strategy::term::is_boolean(), ) }, |(left_boolean, right_boolean)| { prop_assert_is_not_boolean!(result(left_boolean, right_boolean), left_boolean); Ok(()) }, ); } pub fn without_binary_errors_badarg( source_file: &'static str, result: fn(&Process, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_binary(arc_process.clone()), ) }, |(arc_process, binary)| { prop_assert_badarg!( result(&arc_process, binary), format!("binary ({}) must be a binary", binary) ); Ok(()) }, ); } pub fn without_binary_with_encoding_is_not_binary( source_file: &'static str, result: fn(Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( strategy::term::is_not_binary(arc_process.clone()), strategy::term::is_encoding(), ) }, |(binary, encoding)| { prop_assert_is_not_binary!(result(binary, encoding), binary); Ok(()) }, ); } pub fn without_bitstring_errors_badarg( source_file: &'static str, result: fn(&Process, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_bitstring(arc_process.clone()), ) }, |(arc_process, bitstring)| { prop_assert_badarg!( result(&arc_process, bitstring), format!("bitstring ({}) is not a bitstring", bitstring) ); Ok(()) }, ); } pub fn without_float_errors_badarg( source_file: &'static str, result: fn(&Process, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_float(arc_process.clone()), ) }, |(arc_process, float)| { prop_assert_badarg!( result(&arc_process, float), format!("float ({}) is not a float", float) ); Ok(()) }, ); } pub fn without_float_with_empty_options_errors_badarg( source_file: &'static str, result: fn(&Process, Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_float(arc_process.clone()), ) }, |(arc_process, float)| { let options = Term::NIL; prop_assert_badarg!( result(&arc_process, float, options), format!("float ({}) is not a float", float) ); Ok(()) }, ); } pub fn without_function_errors_badarg( source_file: &'static str, result: fn(&Process, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_function(arc_process.clone()), ) }, |(arc_process, function)| { prop_assert_badarg!( result(&arc_process, function), format!("function ({}) is not a function", function) ); Ok(()) }, ); } pub fn without_integer_errors_badarg( source_file: &'static str, result: fn(&Process, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_integer(arc_process.clone()), ) }, |(arc_process, integer)| { prop_assert_badarg!( result(&arc_process, integer), format!("integer ({}) is not an integer", integer) ); Ok(()) }, ); } pub fn without_integer_integer_with_base_errors_badarg( source_file: &'static str, result: fn(&Process, Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_integer(arc_process.clone()), strategy::term::is_base(arc_process.clone()), ) }, |(arc_process, integer, base)| { prop_assert_badarg!( result(&arc_process, integer, base), format!("integer ({}) is not an integer", integer) ); Ok(()) }, ); } pub fn with_integer_integer_without_base_base_errors_badarg( source_file: &'static str, result: fn(&Process, Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_integer(arc_process.clone()), strategy::term::is_not_base(arc_process.clone()), ) }, |(arc_process, integer, base)| { prop_assert_badarg!( result(&arc_process, integer, base), "base must be an integer in 2-36" ); Ok(()) }, ); } pub fn without_integer_dividend_errors_badarith( source_file: &'static str, result: fn(&Process, Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_integer(arc_process.clone()), strategy::term::is_integer(arc_process.clone()), ) }, |(arc_process, dividend, divisor)| { prop_assert_badarith!( result(&arc_process, dividend, divisor), format!( "dividend ({}) and divisor ({}) are not both numbers", dividend, divisor ) ); Ok(()) }, ); } pub fn with_integer_dividend_without_integer_divisor_errors_badarith( source_file: &'static str, result: fn(&Process, Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_integer(arc_process.clone()), strategy::term::is_not_integer(arc_process.clone()), ) }, |(arc_process, dividend, divisor)| { prop_assert_badarith!( result(&arc_process, dividend, divisor), format!( "dividend ({}) and divisor ({}) are not both numbers", dividend, divisor ) ); Ok(()) }, ); } pub fn with_integer_dividend_with_zero_divisor_errors_badarith( source_file: &'static str, result: fn(&Process, Term, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_integer(arc_process.clone()), Just(arc_process.integer(0)), ) }, |(arc_process, dividend, divisor)| { prop_assert_badarith!( result(&arc_process, dividend, divisor), format!("divisor ({}) cannot be zero", divisor) ); Ok(()) }, ); } pub fn without_number_errors_badarg( source_file: &'static str, result: fn(&Process, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_number(arc_process.clone()), ) }, |(arc_process, number)| { prop_assert_is_not_number!(result(&arc_process, number), number); Ok(()) }, ); } pub fn without_timer_reference_errors_badarg( source_file: &'static str, result: fn(&Process, Term) -> exception::Result<Term>, ) { run( source_file, |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_reference(arc_process.clone()), ) }, |(arc_process, timer_reference)| { prop_assert_badarg!( result(&arc_process, timer_reference,), format!( "timer_reference ({}) is not a local reference", timer_reference ) ); Ok(()) }, ); } pub enum FirstSecond { First, Second, }
use fs2::FileExt; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; pub(crate) struct FileLock { f: File, } impl FileLock { pub(crate) fn exclusive(f: File) -> io::Result<Self> { f.lock_exclusive()?; Ok(FileLock { f }) } pub(crate) fn file(&self) -> &File { &self.f } } impl Read for FileLock { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.f.read(buf) } } impl Seek for FileLock { fn seek(&mut self, to: SeekFrom) -> io::Result<u64> { self.f.seek(to) } } impl Write for FileLock { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.f.write(buf) } fn flush(&mut self) -> io::Result<()> { self.f.flush() } } impl Drop for FileLock { fn drop(&mut self) { let _ = self.f.unlock(); } }
use actix_web::HttpRequest; use bcrypt::{DEFAULT_COST, hash, verify}; use chrono::prelude::*; use common::Error; use jsonwebtoken as jwt; use serde::{Deserialize, Serialize}; use crate::models; const DEFAULT_USER_TOKEN_EXP: i64 = 60 * 60 * 2; // Two hours. /// Generate a bcrypt hash of the given password string. pub fn hash_pw(pw: &str) -> Result<String, Error> { Ok(hash(pw, DEFAULT_COST).map_err(|err| { tracing::error!("Failed to hash given password. {}", err); Error::new_ise() })?) } pub fn verify_user_pw(user: &models::User, pw: &str) -> Result<(), Error> { let is_valid = verify(pw, &user.pwhash).map_err(|err| { tracing::error!("Failed to hash given password. {}", err); Error::new_ise() })?; if !is_valid { return Err(Error::new_invalid_credentials()); } Ok(()) } /// The definition of our JWT claims structure. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Claims { /// The ID of the entity for which the token was issued. pub sub: i64, /// The time which the token was issued. /// /// This is an epoch timestamp. **Seconds** since the epoch (not milliseconds, or nanoseconds). pub iat: i64, /// The time when this token will expire, if any. /// /// This is an epoch timestamp. **Seconds** since the epoch (not milliseconds, or nanoseconds). pub exp: i64, } impl Claims { /// Generate a new JWT for the user specified by ID. pub fn new_for_user(private_key: &jwt::EncodingKey, sub: i64) -> Result<String, Error> { // Build a new claims body. let now = Utc::now(); let exp_duration = chrono::Duration::seconds(DEFAULT_USER_TOKEN_EXP); let claims = Claims{sub, iat: now.timestamp(), exp: (now + exp_duration).timestamp()}; // Generate token. Ok(jwt::encode(&jwt::Header::new(jwt::Algorithm::RS512), &claims, private_key).map_err(|err| { tracing::error!({error=%err}, "Error generating new JWT for user."); Error::new_ise() })?) } /// Extract JWT claims from the given request. pub async fn from_request(request: &HttpRequest, pub_key: &jwt::DecodingKey<'static>) -> Result<Self, Error> { // Extract auth val from header. let authval = match request.headers().get("authorization") { Some(val) => match val.to_str() { Ok(strval) => strval, Err(_) => return Err(Error::new("Invalid contents of header 'Authorization'.".into(), 401, None)), } // No auth header presented. None => return Err(Error::new("No credentials provided in request.".into(), 401, None)), }; // Evaluate token's presented auth scheme. let mut token_segments = authval.splitn(2, " "); let is_schema_valid = match token_segments.next() { Some(scheme) if scheme.to_lowercase() == "bearer" => { true } _ => false, }; if !is_schema_valid { return Err(Error::new("Invalid authorization scheme specified, must be 'bearer'.".into(), 401, None)); } // Scheme is good, now ensure we have a token with non-zero size. let token = match token_segments.next() { Some(token) => token, None => return Err(Error::new("Invalid authorization token specified. It appears to be zero-size.".into(), 401, None)), }; // Extract claims. Ok(Self::from_jwt(&token, pub_key)?) } /// Attempt to extract a claims body from the given JWT. /// /// This routine will check the veracity of the token's signature, ensuring the token /// has not been tampered with, and that the token is not expired. pub fn from_jwt(jwt: &str, pub_key: &jwt::DecodingKey<'static>) -> Result<Self, Error> { // Decode token & extract claims. let claims = match jwt::decode::<Self>(jwt, pub_key, &jwt::Validation::new(jwt::Algorithm::RS512)) { Ok(t) => t.claims, Err(_) => Err(Error::new_invalid_token())?, }; // Ensure the claims are valid. claims.must_not_be_expired()?; Ok(claims) } /// Validate that the given claims have not expired. fn must_not_be_expired(&self) -> Result<(), Error> { let now = Utc::now().timestamp(); if now > self.exp { Err(Error::new_token_expired()) } else { Ok(()) } } }
use crate::assets::database::AssetsDatabase; use specs::{System, Write}; pub struct AssetsSystem; impl<'s> System<'s> for AssetsSystem { type SystemData = Option<Write<'s, AssetsDatabase>>; fn run(&mut self, data: Self::SystemData) { if let Some(mut data) = data { data.process(); } } }
#[macro_use] use psistats::{ ReporterFunction, ReporterInitFunction, ReporterConfig }; use psistats::PluginRegistrar; use psistats::PsistatsReport; use psistats::PluginError; use psistats::FunctionType; mod memory; extern "C" fn register(registrar: &mut Box<dyn PluginRegistrar + Send>) { registrar.register_plugin("memory", FunctionType::ReporterInit(Box::new(Init))); registrar.register_plugin("memory", FunctionType::Reporter(Box::new(Reporter))); } psistats::export_plugin!(register); #[derive(Debug, Clone, PartialEq)] struct Init; impl ReporterInitFunction for Init { fn call(&self, _: &ReporterConfig) -> Result<(), PluginError> { memory::start_mem_thread(); Ok(()) } } #[derive(Debug, Clone, PartialEq)] struct Reporter; impl ReporterFunction for Reporter { fn call(&self, _: &ReporterConfig) -> Result<PsistatsReport, PluginError> { return memory::get_report(); } }
use amethyst::{GameData, SimpleState, SimpleTrans, StateData, StateEvent, Trans}; use amethyst::assets::{Handle, Loader, AssetStorage}; use amethyst::core::ecs::{Entity, WorldExt, World, Builder}; use amethyst::input::{is_close_requested, is_key_down, VirtualKeyCode}; use amethyst::renderer::{SpriteSheet, Texture, ImageFormat, SpriteRender, Sprite}; use amethyst::ui::{UiCreator, UiEvent, UiEventType, UiFinder}; use crate::state::pong::{Pong}; use crate::state::start::StartScreen; use crate::taunt::{TauntComponent, Taunt}; use amethyst::core::Transform; use crate::state::options::OptionState; use crate::persistence::window::WindowSettings; use amethyst::core::math::Vector3; use crate::persistence::Settings; const BUTTON_START: &str = "start"; const BUTTON_OPTIONS: &str = "options"; const BUTTON_EXIT: &str = "exit"; #[derive(Default)] pub struct MainMenu { sprite_sheet: Option<Handle<SpriteSheet>>, ui_root: Option<Entity>, button_start: Option<Entity>, button_options: Option<Entity>, button_exit: Option<Entity>, } impl SimpleState for MainMenu { fn on_start(&mut self, data: StateData<'_, GameData>) { // create UI from prefab and save the reference. let world = data.world; let read = world.read_resource::<Settings>(); let settings = *read; drop(read); let sprite_sheet = load_sprite_sheet(world); self.sprite_sheet.replace(sprite_sheet.clone()); initialize_taunt(world, sprite_sheet.clone(), settings.window_settings); self.ui_root = Some(world.exec(|mut creator: UiCreator<'_>| creator.create("ui/menu.ron", ()))); } fn on_stop(&mut self, data: StateData<GameData>) { // after destroying the current UI, invalidate references as well (makes things cleaner) if let Some(root_entity) = self.ui_root { data.world .delete_entity(root_entity) .expect("Failed to remove MainMenu"); } self.ui_root = None; self.button_start = None; self.button_options = None; self.button_exit = None; } fn handle_event(&mut self, data: StateData<'_, GameData>, event: StateEvent) -> SimpleTrans { match event { StateEvent::Window(event) => { if is_close_requested(&event) { log::info!("[Trans::Quit] Quitting Application!"); Trans::Quit } else if is_key_down(&event, VirtualKeyCode::Escape) { log::info!("[Trans::Switch] Switching back to WelcomeScreen!"); Trans::Switch(Box::new(StartScreen::new(*data.world.read_resource::<Settings>()))) } else { Trans::None } } StateEvent::Ui(UiEvent { event_type: UiEventType::Click, target, }) => { if Some(target) == self.button_start { log::info!("[Trans::Switch] Switching to Game!"); return Trans::Switch(Box::new(Pong::new(self.sprite_sheet.clone().unwrap(), data.world.read_resource::<Settings>().window_settings))); } if Some(target) == self.button_options { return Trans::Switch(Box::new(OptionState::default())); } if Some(target) == self.button_exit { return Trans::Quit } Trans::None } _ => Trans::None, } } fn update(&mut self, state_data: &mut StateData<'_, GameData>) -> SimpleTrans { // only search for buttons if they have not been found yet let StateData { world, .. } = state_data; if self.button_start.is_none() || self.button_options.is_none() || self.button_exit.is_none() { world.exec(|ui_finder: UiFinder<'_>| { self.button_start = ui_finder.find(BUTTON_START); self.button_options = ui_finder.find(BUTTON_OPTIONS); self.button_exit = ui_finder.find(BUTTON_EXIT); }); } Trans::None } } fn load_sprite_sheet(world: &mut World) -> Handle<SpriteSheet> { // Load the sprite sheet necessary to render the graphics. // The texture is the pixel data // `texture_handle` is a cloneable reference to the texture let texture_handle = { let loader = world.read_resource::<Loader>(); let texture_storage = world.read_resource::<AssetStorage<Texture>>(); loader.load( "texture/spritesheet.png", ImageFormat::default(), (), &texture_storage, ) }; { let sheet = SpriteSheet { texture: texture_handle, sprites: vec![ to_sprite(16, 64, 768, 0), to_sprite(25, 25, 1024, 0), to_sprite(256, 256, 0, 0), to_sprite(256, 256, 256, 0), to_sprite(256, 256, 512, 0), ] }; let loader = world.read_resource::<Loader>(); let mut sprite_storage = world.write_resource::<AssetStorage<SpriteSheet>>(); sprite_storage.insert(sheet.clone()); loader.load_from_data(sheet, (), &sprite_storage) } } fn to_sprite(width: u32, height: u32, x: u32, y: u32) -> Sprite { Sprite::from_pixel_values( 1280, 256, width, height as u32, x, y, [0f32, 0.0], false, false) } fn initialize_taunt(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>, window_settings: WindowSettings) { world.register::<TauntComponent>(); let mut taunt_transform = Transform::default(); taunt_transform.set_translation_xyz(window_settings.arena_width() / 2.0, window_settings.arena_height() - window_settings.taunt_height() / 2.0, -1.0); taunt_transform.set_scale(Vector3::new(window_settings.taunt_scale(), window_settings.taunt_scale(), 1.0)); let sprite = SpriteRender::new(sprite_sheet_handle, 3); let taunt = world.create_entity() .with(taunt_transform) .with(TauntComponent) .with(sprite) .build(); world.get_mut::<Taunt>().unwrap().face.replace(taunt); }
use nalgebra as na; use na::{allocator::Allocator, RealField, DimName, Point, VectorN, DefaultAllocator}; /// Given a vector of `D`-dimensional points in `N`, returns the centroid. /// When no points, returns the origin. Safe to use with INF and NaNs. pub fn get_centroid<N, D>(points: &Vec<Point<N, D>>) -> Point<N, D> where N: RealField, D: DimName, DefaultAllocator: Allocator<N, D> { let lenrecip: N = na::one::<N>() / na::convert(points.len() as f64); points.iter().fold(Point::origin(), |l, r| l + (r.coords.scale(lenrecip))) } /// Given a vector of `D`-dimensional points in `N`, returns a hypersphere /// encompassing all the points. The first tuple value is the radius, and the /// second is the center of the hypersphere. pub fn bounding_nsphere<N, D>(points: &Vec<Point<N, D>>) -> (N, Point<N, D>) where N: RealField, D: DimName, DefaultAllocator: Allocator<N, D> { let center = get_centroid(points); let maxradius: Option<N> = points.iter() .map(|p| na::distance(p, &center)) .max_by(|x, y| match x.partial_cmp(y) { None => std::cmp::Ordering::Less, Some(ord) => ord } ); (if let Some(maxr) = maxradius { maxr } else { na::zero() }, center) } fn basis_vs<N, D>() -> Vec<VectorN<N, D>> where N: RealField, D: DimName, DefaultAllocator: Allocator<N, D> { debug_assert!(D::dim() >= 1, "The dimension must be at least 1 to get basis vectors!"); let dimsub1 = D::dim() - 1; (0..dimsub1) .collect::<Vec<_>>() .iter() .map(|x| VectorN::<N, D>::from_fn(|i, _| na::convert((i == *x) as u8 as f64))) .collect::<Vec<VectorN<N, D>>>() } /// Given a vector of `D`-dimensional points in `N`, returns a `D`-simplex encompassing /// all the points. The vector returned is the vertices of the simplex, and should have /// `D` length. Assumes `D >= 2` and will debug-assert that to be the case. pub fn bounding_simplex<N, D>(points: &Vec<Point<N, D>>) -> Vec<Point<N, D>> where N: RealField, D: DimName, DefaultAllocator: Allocator<N, D> { debug_assert!(D::dim() >= 2, "The dimension must be at least 2!"); let bsphere = bounding_nsphere(points); // 6.0 * -(2.0 + 5.0f64.sqrt()). c'mon rust, get const sqrt already! const FACTOR: f64 = -25.41640786499873817; let mut simplexverts = basis_vs().iter() .map(|v| v.scale(na::convert::<_, N>(3.0) * bsphere.0) + bsphere.1.clone().coords) .collect::<Vec<VectorN<N, D>>>(); if let Some(fin) = simplexverts.last_mut() { *fin = VectorN::<N, D>::repeat(bsphere.0 * na::convert(FACTOR)) + bsphere.1.coords; } simplexverts.iter() .map(|v| Point::<N, D>::from(v.clone())) .collect() } // Unit tests #[cfg(test)] mod tests { use super::*; use pretty_assertions::{assert_eq, assert_ne}; // No panic when getting the centroid of U0 points. #[test] fn get_centroid_test_u0() { let data: Vec<na::Point<f32, na::dimension::U0>> = vec![ na::Point::origin(), na::Point::origin(), na::Point::origin(), na::Point::origin() ]; assert_eq!(get_centroid(&data), na::Point::origin()); } // No panic when getting the centroid of an empty set of U0 points. #[test] fn get_centroid_test_u0_empty() { let data: Vec<na::Point<f32, na::dimension::U0>> = vec![]; assert_eq!(get_centroid(&data), na::Point::origin()); } // No panic when getting the centroid of U1 points. #[test] fn get_centroid_test_u1() { let data: Vec<na::Point1<f64>> = vec![ na::Point1::new(1.0), na::Point1::new(-2.0), na::Point1::new(3.0), na::Point1::origin() ]; assert_eq!(get_centroid(&data), na::Point1::new(0.5)); } // Centroid of empty set of U1 is origin. #[test] fn get_centroid_test_u1_empty() { let data: Vec<na::Point1<f32>> = vec![]; assert_eq!(get_centroid(&data), na::Point1::origin()); } // NaN in any component will make the centroid's component NaN. #[test] fn get_centroid_test_nan() { let data: Vec<na::Point1<f64>> = vec![ na::Point1::new(std::f64::NAN), na::Point1::new(-2.0), na::Point1::new(3.0), na::Point1::origin() ]; let centroid = get_centroid(&data); assert_ne!(centroid, centroid); } // INF in any component will make the centroid's component INF. #[test] fn get_centroid_test_inf() { let data: Vec<na::Point1<f32>> = vec![ na::Point1::new(std::f32::INFINITY), na::Point1::new(-2.0), na::Point1::new(3.0), na::Point1::origin() ]; assert_eq!(get_centroid(&data), na::Point1::new(std::f32::INFINITY)); } // No panic when getting the centroid of U3 points. #[test] fn get_centroid_test_u3() { let data: Vec<na::Point3<f32>> = vec![ na::Point3::new(1.0, 3.5, 10.0), na::Point3::new(-2.0, 0.0, -2.0), na::Point3::new(1.0, -0.5, 1.0), na::Point3::origin() ]; assert_eq!(get_centroid(&data), na::Point3::new(0.0, 0.75, 2.25)); } // Centroid of empty set of U3 is origin. #[test] fn get_centroid_test_u3_empty() { let data: Vec<na::Point3<f64>> = vec![]; assert_eq!(get_centroid(&data), na::Point3::origin()); } // No panic when getting the bounding sphere of U0 points. #[test] fn bounding_nsphere_test_u0() { let data: Vec<na::Point<f32, na::dimension::U0>> = vec![ na::Point::origin(), na::Point::origin(), na::Point::origin(), na::Point::origin() ]; assert_eq!(bounding_nsphere(&data), (0.0, na::Point::origin())); } // No panic when getting the bounding sphere of an empty set of U0 points. #[test] fn bounding_nsphere_test_u0_empty() { let data: Vec<na::Point<f32, na::dimension::U0>> = vec![]; assert_eq!(bounding_nsphere(&data), (0.0, na::Point::origin())); } // No panic when getting the bounding sphere of U1 points. #[test] fn bounding_nsphere_test_u1() { let data: Vec<na::Point1<f64>> = vec![ na::Point1::new(0.1), na::Point1::new(10.0), na::Point1::new(-5.0), na::Point1::origin() ]; assert_eq!(bounding_nsphere(&data), (8.725, na::Point1::new(1.275))); } // No panic when getting the bounding sphere of an empty set of U1 points. #[test] fn bounding_nsphere_test_u1_empty() { let data: Vec<na::Point1<f64>> = vec![]; assert_eq!(bounding_nsphere(&data), (0.0, na::Point::origin())); } }
use crate::dto::Link; use crate::http::Http; use crate::parser::{Html, Links, Paging}; use std::convert::TryFrom; use crate::config::Config; use std::sync::{mpsc, Arc}; use std::thread; use std::collections::HashMap; use crate::http::CurlHttp; use std::cmp::min; #[derive(Debug)] pub enum Command { Query { query: String, offset: u16 }, Abort, } pub struct FetchResult { pub links: Vec<Link>, pub has_more: bool, } pub struct LinkFetcher {} impl LinkFetcher { pub fn start( config: Arc<Config>, ctrl_rx: mpsc::Receiver<Command>, ui_tx: mpsc::Sender<Result<FetchResult, String>>, ) { let (worker_tx, worker_rx) = mpsc::channel(); let limit = config.limit as usize; let _worker = thread::spawn(move || { let http = CurlHttp::new(); let mut links: HashMap<String, (Vec<Link>, Option<Paging>)> = HashMap::new(); 'worker: for r in worker_rx { if let Command::Query { query, offset } = r { let query = query.trim(); let (ref mut links, ref mut paging) = links.entry(query.to_string()).or_default(); let from = offset as usize; let to = from + limit as usize; let mut has_more = true; // fetch more pages until there are enough to fulfil the offset request, or // there are no more pages while links.len() < to { let fetched = Self::fetch( &http, query, paging.as_ref(), &config, ); match fetched { Ok(Links { links: next_links, paging: next_paging, .. }) => { links.extend(next_links); *paging = next_paging; if *paging == None { // no more pages to load has_more = false; break; } } Err(s) => { ui_tx.send(Err(s)).unwrap(); continue 'worker; } } } let to = min(to, links.len()); let fetch_result = FetchResult { links: links[from..to].to_vec(), has_more, }; ui_tx.send(Ok(fetch_result)).unwrap(); } } }); let _ctrl = thread::spawn(move || { for received in ctrl_rx { match received { c @ Command::Query { .. } => { worker_tx.send(c).unwrap(); } Command::Abort => { unimplemented!() } } } }); } pub fn fetch<H>(http: &H, query: &str, paging: Option<&Paging>, config: &Config) -> Result<Links, String> where H: Http { let url = format!("{}/html", config.url); //TODO reuse static params let query = query.trim(); let mut data = hash_map! { "q" => query, "nextParams" => "", "v" => "l", "o" => "json", "api" => "/d.js" }; let mut s_value; let mut dc_value; if let Some(Paging { s, dc }) = paging { s_value = s.to_string(); dc_value = dc.to_string(); data.insert("s", s_value.as_str()); data.insert("dc", dc_value.as_str()); }; http.post(url.as_str(), data) .and_then(|r| { Links::try_from(Html(r.as_slice())) }) } }
// every T implicity as T: Sized, and the ? undoes this default struct Foo<T: ?Sized> { f: T, }
#[macro_use] extern crate clap; use color_eyre::eyre::Result; use hecs::World; use smol::future; use std::{ collections::VecDeque, net::SocketAddr, sync::{Arc, RwLock}, time::{Duration, Instant}, }; use crate::{ constants::*, cvars::{set_cli_cvars, Config, NetConfig}, networking::Networking, }; use soldank_shared::{messages::NetworkMessage, networking::GameWorld}; mod cheat; mod cli; mod constants; mod cvars; mod networking; mod state; mod systems; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum GameState { Lobby, InGame, } fn main() -> Result<()> { color_eyre::install()?; env_logger::init(); smol::block_on(async { let cmd = cli::parse_cli_args(); let mut map_name = cmd.value_of("map").unwrap_or(DEFAULT_MAP).to_owned(); map_name.push_str(".pms"); log::info!("Using map: {}", map_name); let mut config = Config { net: NetConfig { orb: Arc::new(RwLock::new(orb::Config { timestep_seconds: TIMESTEP_RATE, ..Default::default() })), ..Default::default() }, ..Default::default() }; set_cli_cvars(&mut config, &cmd); let mut networking = Networking::new(cmd.value_of("bind")).await; if let Some(key) = cmd.value_of("key") { networking.connection_key = key.to_string(); } let mut messages: VecDeque<(SocketAddr, NetworkMessage)> = VecDeque::new(); let mut world = World::new(); let mut game_state = GameState::Lobby; let mut server = orb::server::Server::<GameWorld>::new(config.net.orb.clone(), 0.0); let startup_time = Instant::now(); let mut previous_time = Instant::now(); let mut running = true; while running { let timeout = Duration::from_millis( (config.net.orb.read().unwrap().snapshot_send_period * 1000.) as _, ); future::race( // loop is driven by incoming packets networking.process(&mut world, &mut config, &mut messages), // or timeout async { smol::Timer::after(timeout).await; // drop Timer result }, ) .await; let current_time = Instant::now(); let delta_seconds = current_time.duration_since(previous_time).as_secs_f64(); let seconds_since_startup = current_time.duration_since(startup_time).as_secs_f64(); systems::process_network_messages( &mut world, &mut messages, &mut networking.connections, ); systems::message_dump(&mut messages); match game_state { GameState::Lobby => { systems::lobby(&mut world, &mut game_state, &networking); } GameState::InGame => { server.update(delta_seconds, seconds_since_startup); let server_display_state = server.display_state(); log::trace!( "server_display_state: {}", server_display_state.inner().len() ); networking.process_simulation(&mut server); // push above server's results in the wild // let time = systems::Time { // time: current_time, // tick: (server // .last_completed_timestamp() // .as_seconds(config.net.orb.read().unwrap().timestep_seconds) // * 1000.) as usize, // frame_percent: 1., // }; // systems::tick_debug(&world, &time); if networking.connections.is_empty() { log::info!("No connections left - exiting"); running = false; } } } previous_time = current_time; networking.post_process(&config); } log::info!("Exiting server"); Ok(()) }) }
use std::borrow::BorrowMut; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use rbatis_core::convert::StmtConvert; use crate::ast::ast::RbatisAST; use crate::ast::node::node::{create_deep, do_child_nodes, print_child, SqlNodePrint}; use crate::ast::node::node_type::NodeType; use crate::engine::runtime::RbatisEngine; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ResultMapResultNode { pub column: String, pub lang_type: String, pub version_enable: String, pub logic_enable: String, pub logic_undelete: String, pub logic_deleted: String, } impl RbatisAST for ResultMapResultNode { fn eval(&self, convert: &impl StmtConvert, env: &mut Value, engine: &RbatisEngine, arg_array: &mut Vec<Value>) -> Result<String, rbatis_core::Error> { return Result::Ok("".to_string()); } } impl SqlNodePrint for ResultMapResultNode { fn print(&self, deep: i32) -> String { let mut result = create_deep(deep) + "<result "; result = result + " column=\"" + self.column.as_str() + "\""; result = result + " lang_type=\"" + self.lang_type.as_str() + "\""; result = result + "></result>"; return result; } }
use crate::ast::*; use std::collections::HashMap; pub(crate) trait Visitor { fn visit_binder(&mut self, _: &mut Option<usize>, _: &mut String) {} fn visit_expression(&mut self, _: &mut Expression) {} fn leave_expression(&mut self, _: &mut Expression) {} fn visit_reference(&mut self, _: &mut Option<usize>, _: &mut String) {} fn visit_fructose(&mut self, _: &mut Vec<Binder>, _: &mut Vec<Expression>) {} fn visit_galactose(&mut self, _: &mut Vec<Expression>) {} fn visit_literal(&mut self, _: &mut String) {} fn visit_number(&mut self, _: &mut u64) {} fn visit_statement(&mut self, _: &mut Statement) {} fn leave_statement(&mut self, _: &mut Statement) {} fn visit_closure(&mut self, _: &mut Vec<Binder>, _: &mut Vec<Expression>) {} fn visit_call(&mut self, _: &mut Vec<Expression>) {} fn visit_block(&mut self, _: &mut Vec<Statement>) {} } pub(crate) trait Host { fn visit<V: Visitor>(&mut self, visitor: &mut V); } impl Host for Binder { fn visit<V: Visitor>(&mut self, visitor: &mut V) { visitor.visit_binder(&mut self.0, &mut self.1); } } impl Host for Expression { fn visit<V: Visitor>(&mut self, visitor: &mut V) { visitor.visit_expression(self); match self { Expression::Reference(a, b) => visitor.visit_reference(a, b), Expression::Fructose(a, b) => { visitor.visit_fructose(a, b); for ai in a.iter_mut() { ai.visit(visitor); } for bi in b.iter_mut() { bi.visit(visitor); } } Expression::Galactose(a) => { visitor.visit_galactose(a); for ai in a.iter_mut() { ai.visit(visitor); } } Expression::Literal(a) => visitor.visit_literal(a), Expression::Number(a) => visitor.visit_number(a), } visitor.leave_expression(self); } } impl Host for Statement { fn visit<V: Visitor>(&mut self, visitor: &mut V) { visitor.visit_statement(self); match self { Statement::Closure(a, b) => { visitor.visit_closure(a, b); for ai in a.iter_mut() { ai.visit(visitor); } for bi in b.iter_mut() { bi.visit(visitor); } } Statement::Call(a) => { visitor.visit_call(a); for ai in a.iter_mut() { ai.visit(visitor); } } Statement::Block(a) => { visitor.visit_block(a); for ai in a.iter_mut() { ai.visit(visitor); } } } visitor.leave_statement(self); } } /// Bind References to their Binders and flattens Blocks. pub(crate) fn bind(block: &mut Statement) -> usize { // Number binders starting from zero struct NumberBinders(usize); impl Visitor for NumberBinders { fn visit_binder(&mut self, n: &mut Option<usize>, _: &mut String) { *n = Some(self.0); self.0 += 1; } } let mut number_binders = NumberBinders(0); block.visit(&mut number_binders); let num_binders = number_binders.0; // Bind references struct BindReferences(HashMap<String, usize>); impl Visitor for BindReferences { fn visit_binder(&mut self, n: &mut Option<usize>, s: &mut String) { // TODO: Scoping. // TODO: Forward looking. let _ = self.0.insert((*s).to_string(), n.unwrap()); } fn visit_reference(&mut self, n: &mut Option<usize>, s: &mut String) { *n = self.0.get(s).cloned(); } } let mut bind_references = BindReferences(HashMap::new()); block.visit(&mut bind_references); // Flatten blocks struct Flatten(Vec<Statement>); impl Visitor for Flatten { fn visit_statement(&mut self, s: &mut Statement) { match s { Statement::Block(_) => {} _ => self.0.push(s.clone()), } } } let mut flatten = Flatten(Vec::new()); block.visit(&mut flatten); *block = Statement::Block(flatten.0); num_binders } fn merge(target: &mut Vec<Expression>, call: Vec<Expression>) { // Empty expressions get replaces in entirety if target.is_empty() { *target = call; return; } // Visit expression struct State(bool, Vec<Expression>); impl Visitor for State { fn visit_fructose(&mut self, _: &mut Vec<Binder>, tcall: &mut Vec<Expression>) { self.visit_galactose(tcall); } fn visit_galactose(&mut self, tcall: &mut Vec<Expression>) { if !self.0 && tcall.is_empty() { *tcall = self.1.clone(); self.0 = true; } } } let mut state = State(false, call); for expr in target { expr.visit(&mut state); if state.0 { return; } } panic!("Can not digest glucose."); } /// Fill empty calls with following statement pub(crate) fn glucase(statements: &[Statement]) -> Vec<Statement> { let mut result = Vec::new(); let mut closure: Option<(Vec<Binder>, Vec<Expression>)> = None; for statement in statements { match statement { Statement::Block(_) => panic!("Blocks not allowed here."), Statement::Closure(a, b) => { if let Some((c, d)) = closure { // TODO: Assert that result has no empty calls result.push(Statement::Closure(c, d)); } closure = Some((a.clone(), b.clone())); } Statement::Call(a) => { if let Some((_, d)) = &mut closure { merge(d, a.clone()); } else { panic!("Call without preceding closure.") } } } } if let Some((c, d)) = closure { result.push(Statement::Closure(c, d)); } result } pub(crate) fn glucase_wrap(block: &mut Statement) { if let Statement::Block(statements) = block { *statements = glucase(&statements); } } /// Converts all Fructose to Closures. pub(crate) fn fructase(block: &mut Statement, binder_id: &mut usize) { struct State(usize, Vec<Statement>); impl Visitor for State { fn leave_expression(&mut self, e: &mut Expression) { *e = if let Expression::Fructose(p, c) = e { let replacement = Expression::Reference(Some(self.0), String::default()); let mut procedure = Vec::new(); std::mem::swap(p, &mut procedure); let mut call = Vec::new(); std::mem::swap(c, &mut call); procedure.insert(0, Binder(Some(self.0), String::default())); self.0 += 1; // TODO: For glucase may need merge with sibling self.1.push(Statement::Closure(procedure, call)); replacement } else { // TODO: Avoid copies e.clone() } } } let mut state = State(*binder_id, Vec::new()); block.visit(&mut state); *binder_id = state.0; if let Statement::Block(statements) = block { statements.extend(state.1); } else { panic!("Statement must be a block.") } } pub(crate) fn galac_vec(exprs: &mut Vec<Expression>, binder_id: &mut usize) { // Find first Galactose or return if let Some(index) = exprs.iter().position(|e| { match e { Expression::Galactose(_) => true, _ => false, } }) { // Invert Galactose into Fructose // Replace galactose by a reference and fetch the call vec let mut temp = Expression::Reference(Some(*binder_id), String::default()); std::mem::swap(&mut exprs[index], &mut temp); let mut call = match temp { Expression::Galactose(c) => c, _ => panic!("No Galactose at index."), }; // Swap expression and call std::mem::swap(exprs, &mut call); // Append new fructose to the expression in the last position exprs.push(Expression::Fructose( vec![Binder(Some(*binder_id), String::default())], call, )); // Update next binder id *binder_id += 1; // Iterate till fix-point // TODO: What about iterating on `call`? galac_vec(exprs, binder_id) } } pub(crate) fn galactase(block: &mut Statement, binder_id: &mut usize) { struct State(usize); impl Visitor for State { fn visit_closure(&mut self, _: &mut Vec<Binder>, exprs: &mut Vec<Expression>) { galac_vec(exprs, &mut self.0); } fn visit_fructose(&mut self, _: &mut Vec<Binder>, exprs: &mut Vec<Expression>) { galac_vec(exprs, &mut self.0); } fn visit_galactose(&mut self, exprs: &mut Vec<Expression>) { galac_vec(exprs, &mut self.0); } } let mut state = State(*binder_id); block.visit(&mut state); *binder_id = state.0; } pub(crate) fn desugar(block: &mut Statement) { let mut binder_count = bind(block); glucase_wrap(block); galactase(block, &mut binder_count); fructase(block, &mut binder_count); }
use smartcore::dataset::*; // DenseMatrix wrapper around Vec use smartcore::linalg::naive::dense_matrix::DenseMatrix; // K-Means use smartcore::cluster::kmeans::{KMeans, KMeansParameters}; // DBSCAN use smartcore::cluster::dbscan::{DBSCANParameters, DBSCAN}; // PCA use smartcore::decomposition::pca::{PCAParameters, PCA}; use smartcore::metrics::*; // SVD use smartcore::decomposition::svd::{SVDParameters, SVD}; use smartcore::linalg::svd::SVDDecomposableMatrix; use smartcore::linalg::BaseMatrix; use crate::utils; pub fn digits_clusters() { // Load dataset let digits_data = digits::load_dataset(); // Transform dataset into a NxM matrix let x = DenseMatrix::from_array( digits_data.num_samples, digits_data.num_features, &digits_data.data, ); // These are our target class labels let true_labels = digits_data.target; // Fit & predict let labels = KMeans::fit(&x, KMeansParameters::default().with_k(10)) .and_then(|kmeans| kmeans.predict(&x)) .unwrap(); // Measure performance println!("Homogeneity: {}", homogeneity_score(&true_labels, &labels)); println!( "Completeness: {}", completeness_score(&true_labels, &labels) ); println!("V Measure: {}", v_measure_score(&true_labels, &labels)); } pub fn circles() { // Load dataset let circles = generator::make_circles(1000, 0.5, 0.05); // Transform dataset into a NxM matrix let x = DenseMatrix::from_array(circles.num_samples, circles.num_features, &circles.data); // These are our target class labels let true_labels = circles.target; // Fit & predict let labels = DBSCAN::fit( &x, DBSCANParameters::default() .with_eps(0.2) .with_min_samples(5), ) .and_then(|c| c.predict(&x)) .unwrap(); // Measure performance println!("Homogeneity: {}", homogeneity_score(&true_labels, &labels)); println!( "Completeness: {}", completeness_score(&true_labels, &labels) ); println!("V Measure: {}", v_measure_score(&true_labels, &labels)); utils::scatterplot( &x, Some(&labels.into_iter().map(|f| f as usize).collect()), "test", ) .unwrap(); } pub fn digits_pca() { // Load dataset let digits_data = digits::load_dataset(); // Transform dataset into a NxM matrix let x = DenseMatrix::from_array( digits_data.num_samples, digits_data.num_features, &digits_data.data, ); // These are our target class labels let labels = digits_data.target; // Fit PCA to digits dataset let pca = PCA::fit(&x, PCAParameters::default().with_n_components(2)).unwrap(); // Reduce dimensionality of X let x_transformed = pca.transform(&x).unwrap(); // Plot transformed X to 2 principal components utils::scatterplot( &x_transformed, Some(&labels.into_iter().map(|f| f as usize).collect()), "digits_pca", ) .unwrap(); } pub fn digits_svd1() { // Load dataset let digits_data = digits::load_dataset(); // Transform dataset into a NxM matrix let x = DenseMatrix::from_array( digits_data.num_samples, digits_data.num_features, &digits_data.data, ); // These are our target class labels let labels = digits_data.target; // Fit SVD to digits dataset let svd = SVD::fit(&x, SVDParameters::default().with_n_components(2)).unwrap(); // Reduce dimensionality of X let x_transformed = svd.transform(&x).unwrap(); // Plot transformed X to 2 principal components utils::scatterplot( &x_transformed, Some(&labels.into_iter().map(|f| f as usize).collect()), "digits_svd", ) .unwrap(); } pub fn digits_svd2() { // Load dataset let digits_data = digits::load_dataset(); // Transform dataset into a NxM matrix let x = DenseMatrix::from_array( digits_data.num_samples, digits_data.num_features, &digits_data.data, ); // Decompose matrix into U . Sigma . V^T let svd = x.svd().unwrap(); let u: &DenseMatrix<f32> = &svd.U; //U let v: &DenseMatrix<f32> = &svd.V; // V let s: &DenseMatrix<f32> = &svd.S(); // Sigma // Print dimensions of components println!("U is {}x{}", u.shape().0, u.shape().1); println!("V is {}x{}", v.shape().0, v.shape().1); println!("sigma is {}x{}", s.shape().0, s.shape().1); // Restore original matrix let x_hat = u.matmul(s).matmul(&v.transpose()); for (x_i, x_hat_i) in x.iter().zip(x_hat.iter()) { assert!((x_i - x_hat_i).abs() < 1e-3) } }
/* origin: FreeBSD /usr/src/lib/msun/src/e_asinf.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ use super::fabsf::fabsf; use super::sqrt::sqrt; const PIO2: f64 = 1.570796326794896558e+00; /* coefficients for R(x^2) */ const P_S0: f32 = 1.6666586697e-01; const P_S1: f32 = -4.2743422091e-02; const P_S2: f32 = -8.6563630030e-03; const Q_S1: f32 = -7.0662963390e-01; fn r(z: f32) -> f32 { let p = z * (P_S0 + z * (P_S1 + z * P_S2)); let q = 1. + z * Q_S1; p / q } /// Arcsine (f32) /// /// Computes the inverse sine (arc sine) of the argument `x`. /// Arguments to asin must be in the range -1 to 1. /// Returns values in radians, in the range of -pi/2 to pi/2. #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn asinf(mut x: f32) -> f32 { let x1p_120 = f64::from_bits(0x3870000000000000); // 0x1p-120 === 2 ^ (-120) let hx = x.to_bits(); let ix = hx & 0x7fffffff; if ix >= 0x3f800000 { /* |x| >= 1 */ if ix == 0x3f800000 { /* |x| == 1 */ return ((x as f64) * PIO2 + x1p_120) as f32; /* asin(+-1) = +-pi/2 with inexact */ } return 0. / (x - x); /* asin(|x|>1) is NaN */ } if ix < 0x3f000000 { /* |x| < 0.5 */ /* if 0x1p-126 <= |x| < 0x1p-12, avoid raising underflow */ if (ix < 0x39800000) && (ix >= 0x00800000) { return x; } return x + x * r(x * x); } /* 1 > |x| >= 0.5 */ let z = (1. - fabsf(x)) * 0.5; let s = sqrt(z as f64); x = (PIO2 - 2. * (s + s * (r(z) as f64))) as f32; if (hx >> 31) != 0 { -x } else { x } }
#[doc = "Reader of register CFGR2"] pub type R = crate::R<u32, super::CFGR2>; #[doc = "Writer for register CFGR2"] pub type W = crate::W<u32, super::CFGR2>; #[doc = "Register CFGR2 `reset()`'s with value 0"] impl crate::ResetValue for super::CFGR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "PREDIV1 division factor\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PREDIV1_A { #[doc = "0: PREDIV input clock not divided"] DIV1 = 0, #[doc = "1: PREDIV input clock divided by 2"] DIV2 = 1, #[doc = "2: PREDIV input clock divided by 3"] DIV3 = 2, #[doc = "3: PREDIV input clock divided by 4"] DIV4 = 3, #[doc = "4: PREDIV input clock divided by 5"] DIV5 = 4, #[doc = "5: PREDIV input clock divided by 6"] DIV6 = 5, #[doc = "6: PREDIV input clock divided by 7"] DIV7 = 6, #[doc = "7: PREDIV input clock divided by 8"] DIV8 = 7, #[doc = "8: PREDIV input clock divided by 9"] DIV9 = 8, #[doc = "9: PREDIV input clock divided by 10"] DIV10 = 9, #[doc = "10: PREDIV input clock divided by 11"] DIV11 = 10, #[doc = "11: PREDIV input clock divided by 12"] DIV12 = 11, #[doc = "12: PREDIV input clock divided by 13"] DIV13 = 12, #[doc = "13: PREDIV input clock divided by 14"] DIV14 = 13, #[doc = "14: PREDIV input clock divided by 15"] DIV15 = 14, #[doc = "15: PREDIV input clock divided by 16"] DIV16 = 15, } impl From<PREDIV1_A> for u8 { #[inline(always)] fn from(variant: PREDIV1_A) -> Self { variant as _ } } #[doc = "Reader of field `PREDIV1`"] pub type PREDIV1_R = crate::R<u8, PREDIV1_A>; impl PREDIV1_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PREDIV1_A { match self.bits { 0 => PREDIV1_A::DIV1, 1 => PREDIV1_A::DIV2, 2 => PREDIV1_A::DIV3, 3 => PREDIV1_A::DIV4, 4 => PREDIV1_A::DIV5, 5 => PREDIV1_A::DIV6, 6 => PREDIV1_A::DIV7, 7 => PREDIV1_A::DIV8, 8 => PREDIV1_A::DIV9, 9 => PREDIV1_A::DIV10, 10 => PREDIV1_A::DIV11, 11 => PREDIV1_A::DIV12, 12 => PREDIV1_A::DIV13, 13 => PREDIV1_A::DIV14, 14 => PREDIV1_A::DIV15, 15 => PREDIV1_A::DIV16, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIV1`"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == PREDIV1_A::DIV1 } #[doc = "Checks if the value of the field is `DIV2`"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == PREDIV1_A::DIV2 } #[doc = "Checks if the value of the field is `DIV3`"] #[inline(always)] pub fn is_div3(&self) -> bool { *self == PREDIV1_A::DIV3 } #[doc = "Checks if the value of the field is `DIV4`"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == PREDIV1_A::DIV4 } #[doc = "Checks if the value of the field is `DIV5`"] #[inline(always)] pub fn is_div5(&self) -> bool { *self == PREDIV1_A::DIV5 } #[doc = "Checks if the value of the field is `DIV6`"] #[inline(always)] pub fn is_div6(&self) -> bool { *self == PREDIV1_A::DIV6 } #[doc = "Checks if the value of the field is `DIV7`"] #[inline(always)] pub fn is_div7(&self) -> bool { *self == PREDIV1_A::DIV7 } #[doc = "Checks if the value of the field is `DIV8`"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == PREDIV1_A::DIV8 } #[doc = "Checks if the value of the field is `DIV9`"] #[inline(always)] pub fn is_div9(&self) -> bool { *self == PREDIV1_A::DIV9 } #[doc = "Checks if the value of the field is `DIV10`"] #[inline(always)] pub fn is_div10(&self) -> bool { *self == PREDIV1_A::DIV10 } #[doc = "Checks if the value of the field is `DIV11`"] #[inline(always)] pub fn is_div11(&self) -> bool { *self == PREDIV1_A::DIV11 } #[doc = "Checks if the value of the field is `DIV12`"] #[inline(always)] pub fn is_div12(&self) -> bool { *self == PREDIV1_A::DIV12 } #[doc = "Checks if the value of the field is `DIV13`"] #[inline(always)] pub fn is_div13(&self) -> bool { *self == PREDIV1_A::DIV13 } #[doc = "Checks if the value of the field is `DIV14`"] #[inline(always)] pub fn is_div14(&self) -> bool { *self == PREDIV1_A::DIV14 } #[doc = "Checks if the value of the field is `DIV15`"] #[inline(always)] pub fn is_div15(&self) -> bool { *self == PREDIV1_A::DIV15 } #[doc = "Checks if the value of the field is `DIV16`"] #[inline(always)] pub fn is_div16(&self) -> bool { *self == PREDIV1_A::DIV16 } } #[doc = "Write proxy for field `PREDIV1`"] pub struct PREDIV1_W<'a> { w: &'a mut W, } impl<'a> PREDIV1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PREDIV1_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "PREDIV input clock not divided"] #[inline(always)] pub fn div1(self) -> &'a mut W { self.variant(PREDIV1_A::DIV1) } #[doc = "PREDIV input clock divided by 2"] #[inline(always)] pub fn div2(self) -> &'a mut W { self.variant(PREDIV1_A::DIV2) } #[doc = "PREDIV input clock divided by 3"] #[inline(always)] pub fn div3(self) -> &'a mut W { self.variant(PREDIV1_A::DIV3) } #[doc = "PREDIV input clock divided by 4"] #[inline(always)] pub fn div4(self) -> &'a mut W { self.variant(PREDIV1_A::DIV4) } #[doc = "PREDIV input clock divided by 5"] #[inline(always)] pub fn div5(self) -> &'a mut W { self.variant(PREDIV1_A::DIV5) } #[doc = "PREDIV input clock divided by 6"] #[inline(always)] pub fn div6(self) -> &'a mut W { self.variant(PREDIV1_A::DIV6) } #[doc = "PREDIV input clock divided by 7"] #[inline(always)] pub fn div7(self) -> &'a mut W { self.variant(PREDIV1_A::DIV7) } #[doc = "PREDIV input clock divided by 8"] #[inline(always)] pub fn div8(self) -> &'a mut W { self.variant(PREDIV1_A::DIV8) } #[doc = "PREDIV input clock divided by 9"] #[inline(always)] pub fn div9(self) -> &'a mut W { self.variant(PREDIV1_A::DIV9) } #[doc = "PREDIV input clock divided by 10"] #[inline(always)] pub fn div10(self) -> &'a mut W { self.variant(PREDIV1_A::DIV10) } #[doc = "PREDIV input clock divided by 11"] #[inline(always)] pub fn div11(self) -> &'a mut W { self.variant(PREDIV1_A::DIV11) } #[doc = "PREDIV input clock divided by 12"] #[inline(always)] pub fn div12(self) -> &'a mut W { self.variant(PREDIV1_A::DIV12) } #[doc = "PREDIV input clock divided by 13"] #[inline(always)] pub fn div13(self) -> &'a mut W { self.variant(PREDIV1_A::DIV13) } #[doc = "PREDIV input clock divided by 14"] #[inline(always)] pub fn div14(self) -> &'a mut W { self.variant(PREDIV1_A::DIV14) } #[doc = "PREDIV input clock divided by 15"] #[inline(always)] pub fn div15(self) -> &'a mut W { self.variant(PREDIV1_A::DIV15) } #[doc = "PREDIV input clock divided by 16"] #[inline(always)] pub fn div16(self) -> &'a mut W { self.variant(PREDIV1_A::DIV16) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } impl R { #[doc = "Bits 0:3 - PREDIV1 division factor"] #[inline(always)] pub fn prediv1(&self) -> PREDIV1_R { PREDIV1_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - PREDIV1 division factor"] #[inline(always)] pub fn prediv1(&mut self) -> PREDIV1_W { PREDIV1_W { w: self } } }
use std::collections::HashMap; mod network { pub trait SockUtilTrait { fn connect(host: String, port: usize, b_async: bool, local_ip: String, local_port: usize) -> usize; fn listen(port: usize, local_ip: String, back_log: usize) -> usize; fn bind_udp_sock(port: usize, local_ip: String) -> usize; fn bind_sock(sock_fd: usize, local_ip: String, port: usize) -> usize; fn set_no_delay(sock_fd: usize, on: bool) -> usize; fn set_no_sigpipe(sock: usize) -> usize; fn set_no_blocked(sock: usize, noblock: bool) -> usize; fn set_recv_buf(sock: usize, size: usize) -> usize; fn set_send_buf(sock: usize, size: usize) -> usize; fn set_resuseable(sock_fd: usize, on: bool) -> usize; fn set_broadcast(sock_fd: usize, on: bool) -> usize; fn set_keep_alive(sock_fd: usize, on: bool) -> usize; fn set_multi_ttl(sock_fd: usize, ttl: usize) -> usize; fn set_multi_if(sock_fd: usize, str_local_ip: String) -> usize; fn set_multi_loop(sock_fd: usize, b_accept: bool) -> usize; fn join_multi_addr(sock_fd: usize, str_addr: String, str_local_ip: String) -> usize; fn leave_multi_addr(sock_fd: usize, str_addr: String, str_local_ip: String) -> usize; fn join_multi_addr_filter(sock_fd: usize, str_addr: String, str_src_ip: String, str_local_ip: String) -> usize; fn leave_multi_addr_filter(sock_fd: usize, str_addr: String, str_src_ip: String, str_local_ip: String) -> usize; fn get_sock_error(sock_fd: usize) -> usize; fn set_close_wait(sock_fd: usize, second: usize) -> usize; //fn getInterfaceList(&self) -> Vec<HashMap<String, String>>; fn get_local_ip(fd: usize) -> String; fn get_local_ip_v2(&self) -> String; fn get_local_port(fd: usize) -> usize; fn get_peer_ip(fd: usize) -> String; fn get_peer_port(fd: usize) -> usize; fn get_ifr_ip(ifr_name: String) -> String; fn get_ifr_name(localip: String) -> String; fn get_ifr_mask(ifr_name: String) -> String; fn get_ifr_brdaddr(ifr_name: String) -> String; fn is_same_lan(ip: String, dsr_ip: String) -> bool; } }
//! Iterating over set flag values. use crate::{Flag, Flags}; /// An iterator over a set of flags. /// /// Any bits that don't correspond to a valid flag will be yielded /// as a final item from the iterator. pub struct Iter<B: 'static> { inner: IterNames<B>, done: bool, } impl<B: Flags> Iter<B> { /// Create a new iterator over the given set of flags. pub(crate) fn new(flags: &B) -> Self { Iter { inner: IterNames::new(flags), done: false, } } } impl<B: 'static> Iter<B> { #[doc(hidden)] pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, remaining: B) -> Self { Iter { inner: IterNames::__private_const_new(flags, source, remaining), done: false, } } } impl<B: Flags> Iterator for Iter<B> { type Item = B; fn next(&mut self) -> Option<Self::Item> { match self.inner.next() { Some((_, flag)) => Some(flag), None if !self.done => { self.done = true; // After iterating through valid names, if there are any bits left over // then return one final value that includes them. This makes `into_iter` // and `from_iter` roundtrip if !self.inner.remaining().is_empty() { Some(B::from_bits_retain(self.inner.remaining.bits())) } else { None } } None => None, } } } /// An iterator over a set of flags and their names. /// /// Any bits that don't correspond to a valid flag will be ignored. pub struct IterNames<B: 'static> { flags: &'static [Flag<B>], idx: usize, source: B, remaining: B, } impl<B: Flags> IterNames<B> { /// Create a new iterator over the given set of flags. pub(crate) fn new(flags: &B) -> Self { IterNames { flags: B::FLAGS, idx: 0, remaining: B::from_bits_retain(flags.bits()), source: B::from_bits_retain(flags.bits()), } } } impl<B: 'static> IterNames<B> { #[doc(hidden)] pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, remaining: B) -> Self { IterNames { flags, idx: 0, remaining, source, } } /// Get the remaining (unyielded) flags. /// /// Once the iterator has finished, this method can be used to /// check whether or not there are any bits that didn't correspond /// to a valid flag remaining. pub fn remaining(&self) -> &B { &self.remaining } } impl<B: Flags> Iterator for IterNames<B> { type Item = (&'static str, B); fn next(&mut self) -> Option<Self::Item> { while let Some(flag) = self.flags.get(self.idx) { // Short-circuit if our state is empty if self.remaining.is_empty() { return None; } self.idx += 1; let bits = flag.value().bits(); // If the flag is set in the original source _and_ it has bits that haven't // been covered by a previous flag yet then yield it. These conditions cover // two cases for multi-bit flags: // // 1. When flags partially overlap, such as `0b00000001` and `0b00000101`, we'll // yield both flags. // 2. When flags fully overlap, such as in convenience flags that are a shorthand for others, // we won't yield both flags. if self.source.contains(B::from_bits_retain(bits)) && self.remaining.intersects(B::from_bits_retain(bits)) { self.remaining.remove(B::from_bits_retain(bits)); return Some((flag.name(), B::from_bits_retain(bits))); } } None } }
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use hashbrown::{hash_map, HashMap}; use std::cell::Cell; use std::path::{Path, PathBuf}; use super::include::{DefaultIncludeLocator, IncludeLocator, PathIndex}; use super::macros::{ Macro, MacroCounter, MacroFile, MacroFunction, MacroLine, MacroObject, MacroType, }; use crate::lexer::buffer::{BufferData, FileInfo}; use crate::lexer::source::{FileId, SourceMutex}; /// Indicate the state of the if statement /// Eval: indicates that we're evaluating the tokens /// Skip: indicates that we're skipping everything until the corresponding endif /// SkipAndSwitch: indicates that we're skipping until the else (if one) #[derive(Clone, Debug, PartialEq)] pub enum IfState { Eval, Skip, SkipAndSwitch, } pub trait PreprocContext: Default + IncludeLocator { /// Set the if state fn add_if(&mut self, state: IfState); /// Call on endif fn rm_if(&mut self); /// Get the current if state fn if_state(&self) -> Option<&IfState>; /// Change the state /// For example if we're in SkipAndSwitch state then switch to Eval on else fn if_change(&mut self, state: IfState); /// Add a macro function: #define foo(a, b)... fn add_function(&mut self, name: String, mac: MacroFunction); /// Add a macro object: #define foo ... fn add_object(&mut self, name: String, mac: MacroObject); /// Remove a macro /// Called on undef fn undef(&mut self, name: &str); /// Check if a macro is defined (used in condition with function defined()) fn defined(&mut self, name: &str) -> bool; /// Get a macro (if one) with the given name fn get(&self, name: &str) -> Option<&Macro>; /// Get MacroType fn get_type(&self, name: &str) -> MacroType; } #[derive(Default)] pub struct EmptyContext {} impl PreprocContext for EmptyContext { fn add_if(&mut self, _state: IfState) {} fn rm_if(&mut self) {} fn if_state(&self) -> Option<&IfState> { None } fn if_change(&mut self, _state: IfState) {} fn add_function(&mut self, _name: String, _mac: MacroFunction) {} fn add_object(&mut self, _name: String, _mac: MacroObject) {} fn undef(&mut self, _name: &str) {} fn defined(&mut self, _name: &str) -> bool { false } fn get(&self, _name: &str) -> Option<&Macro> { None } fn get_type(&self, _name: &str) -> MacroType { MacroType::None } } impl IncludeLocator for EmptyContext { fn find( &mut self, _angle: bool, _path: &str, _next: bool, _current: FileId, _path_index: PathIndex, ) -> Option<BufferData> { None } fn get_id(&mut self, _path: &PathBuf) -> FileId { FileId(0) } fn get_path(&self, _id: FileId) -> PathBuf { PathBuf::from("") } fn set_source(&mut self, _source: SourceMutex) {} fn set_sys_paths<P: AsRef<Path>>(&mut self, _paths: &[P]) {} } #[derive(Clone, Debug, PartialEq)] pub enum IfKind { If, Ifdef, Ifndef, } #[derive(Clone, Debug)] pub struct Context<IL: IncludeLocator> { macros: HashMap<String, Macro>, if_stack: Vec<IfState>, include: IL, buffer: Option<()>, } pub type DefaultContext = Context<DefaultIncludeLocator>; impl<IL: IncludeLocator> Default for Context<IL> { fn default() -> Self { Self { macros: { let mut map = HashMap::default(); map.insert("__LINE__".to_string(), Macro::Line(MacroLine::new())); map.insert("__FILE__".to_string(), Macro::File(MacroFile::new())); map.insert( "__COUNTER__".to_string(), Macro::Counter(MacroCounter::new()), ); map }, if_stack: Vec::new(), include: IL::default(), buffer: None, } } } impl<IL: IncludeLocator> Context<IL> { pub fn new(include: IL) -> Self { Self { macros: HashMap::default(), if_stack: Vec::new(), include, buffer: None, } } } impl<IL: IncludeLocator> PreprocContext for Context<IL> { fn add_if(&mut self, state: IfState) { self.if_stack.push(state); } fn rm_if(&mut self) { self.if_stack.pop(); } fn if_state(&self) -> Option<&IfState> { self.if_stack.last() } fn if_change(&mut self, state: IfState) { *self.if_stack.last_mut().unwrap() = state; } fn add_function(&mut self, name: String, mac: MacroFunction) { self.macros.insert(name, Macro::Function(mac)); } fn add_object(&mut self, name: String, mac: MacroObject) { self.macros.insert(name, Macro::Object(mac)); } fn undef(&mut self, name: &str) { self.macros.remove(name); } fn defined(&mut self, name: &str) -> bool { self.macros.contains_key(name) } fn get(&self, name: &str) -> Option<&Macro> { if let Some(mac) = self.macros.get(name) { match mac { Macro::Object(m) => { if m.in_use.get() { None } else { Some(mac) } } Macro::Function(m) => { if m.in_use.get() { None } else { Some(mac) } } Macro::Line(_) | Macro::File(_) | Macro::Counter(_) => Some(mac), } } else { None } } fn get_type(&self, name: &str) -> MacroType { if let Some(mac) = self.get(name) { match mac { Macro::Object(mac) => MacroType::Object(&mac), Macro::Function(mac) => MacroType::Function((mac.len(), mac.va_args)), Macro::Line(mac) => MacroType::Line(*mac), Macro::File(mac) => MacroType::File(*mac), Macro::Counter(mac) => MacroType::Counter(mac), } } else { MacroType::None } } } impl<IL: IncludeLocator> IncludeLocator for Context<IL> { fn find( &mut self, angle: bool, path: &str, next: bool, current: FileId, path_index: PathIndex, ) -> Option<BufferData> { self.include.find(angle, path, next, current, path_index) } fn get_id(&mut self, path: &PathBuf) -> FileId { self.include.get_id(path) } fn get_path(&self, id: FileId) -> PathBuf { self.include.get_path(id) } fn set_source(&mut self, source: SourceMutex) { self.include.set_source(source); } fn set_sys_paths<P: AsRef<Path>>(&mut self, paths: &[P]) { self.include.set_sys_paths(paths); } } #[derive(Clone)] pub struct Stats { pub info: FileInfo, pub counter: Cell<usize>, } #[derive(Default)] pub struct StatsContext { default: DefaultContext, stats: HashMap<String, Stats>, toto: HashMap<(String, FileInfo), usize>, } impl StatsContext { pub fn get_stats(&self) -> &HashMap<String, Stats> { &self.stats } } impl PreprocContext for StatsContext { fn add_if(&mut self, state: IfState) { self.default.add_if(state); } fn rm_if(&mut self) { self.default.rm_if(); } fn if_state(&self) -> Option<&IfState> { self.default.if_state() } fn if_change(&mut self, state: IfState) { self.default.if_change(state); } fn add_function(&mut self, name: String, mac: MacroFunction) { let info = mac.file_info.clone(); self.default.add_function(name.clone(), mac); match self.stats.entry(name) { hash_map::Entry::Occupied(p) => { let p = p.into_mut(); p.info = info; } hash_map::Entry::Vacant(p) => { p.insert(Stats { info, counter: Cell::new(0), }); } } } fn add_object(&mut self, name: String, mac: MacroObject) { let info = mac.file_info.clone(); self.default.add_object(name.clone(), mac); match self.stats.entry(name) { hash_map::Entry::Occupied(p) => { let p = p.into_mut(); p.info = info; } hash_map::Entry::Vacant(p) => { p.insert(Stats { info, counter: Cell::new(0), }); } } } fn undef(&mut self, name: &str) { self.default.undef(name); } fn defined(&mut self, name: &str) -> bool { if self.default.defined(name) { if let Some(stat) = self.stats.get(name) { stat.counter.set(stat.counter.get() + 1); } true } else { self.stats.insert( name.to_string(), Stats { info: FileInfo::default(), counter: Cell::new(1), }, ); false } } fn get(&self, name: &str) -> Option<&Macro> { let mac = self.default.get(name); if mac.is_some() { if let Some(stat) = self.stats.get(name) { stat.counter.set(stat.counter.get() + 1); } } mac } fn get_type(&self, name: &str) -> MacroType { let typ = self.default.get_type(name); if let MacroType::Object(_) = typ { if let Some(stat) = self.stats.get(name) { stat.counter.set(stat.counter.get() + 1); } } typ } } impl IncludeLocator for StatsContext { fn find( &mut self, angle: bool, path: &str, next: bool, current: FileId, path_index: PathIndex, ) -> Option<BufferData> { self.default.find(angle, path, next, current, path_index) } fn get_id(&mut self, path: &PathBuf) -> FileId { self.default.get_id(path) } fn get_path(&self, id: FileId) -> PathBuf { self.default.get_path(id) } fn set_source(&mut self, source: SourceMutex) { self.default.set_source(source) } fn set_sys_paths<P: AsRef<Path>>(&mut self, paths: &[P]) { self.default.set_sys_paths(paths); } }
use wasc::compile; use wasc::context; use wasc::gcc; fn main() -> Result<(), Box<dyn std::error::Error>> { // Usage of wasc: // // wasc // --gcc [GCC binary] // -p --platform [PLATFORM] // -s --save // -v --verbose // --wasm [WAVM binary] // source [WASM/WA(S)T source file] // // PLATFORM: // ckb_vm_assemblyscript // ckb_vm_spectest // posix_x86_64 // posix_x86_64_spectest // posix_x86_64_wasi let mut fl_source = String::from(""); let mut fl_platform = String::from(""); let mut fl_wavm = String::from( std::env::current_exe()? .parent() .unwrap() .join("wavm") .to_str() .unwrap(), ); let mut fl_gcc = String::from(""); let mut fl_verbose = false; let mut fl_save = false; { let mut ap = argparse::ArgumentParser::new(); ap.set_description("WASC: WebAssembly native compilter"); ap.refer(&mut fl_source) .add_argument("source", argparse::Store, "WASM/WA(S)T source file"); ap.refer(&mut fl_platform).add_option( &["-p", "--platform"], argparse::Store, "posix_x86_64 posix_x86_64_spectest posix_x86_64_wasi", ); ap.refer(&mut fl_wavm) .add_option(&["--wavm"], argparse::Store, "WAVM binary"); ap.refer(&mut fl_gcc).add_option(&["--gcc"], argparse::Store, "GCC"); ap.refer(&mut fl_verbose) .add_option(&["-v", "--verbose"], argparse::StoreTrue, ""); ap.refer(&mut fl_save) .add_option(&["-s", "--save"], argparse::StoreTrue, "save temporary files"); ap.parse_args_or_exit(); } if fl_source.is_empty() { rog::println!("wasc: missing file operand"); std::process::exit(1); } if fl_verbose { rog::reg("wasc"); rog::reg("wasc::aot_generator"); rog::reg("wasc::code_builder"); rog::reg("wasc::compile"); rog::reg("wasc::gcc"); } let mut config = context::Config::default(); config.platform = match fl_platform.as_str() { "ckb_vm_assemblyscript" => context::Platform::CKBVMAssemblyScript, "ckb_vm_spectest" => context::Platform::CKBVMSpectest, "posix_x86_64" => context::Platform::PosixX8664, "posix_x86_64_spectest" => context::Platform::PosixX8664Spectest, "posix_x86_64_wasi" => context::Platform::PosixX8664Wasi, "" => { if cfg!(unix) { context::Platform::PosixX8664Wasi } else { context::Platform::Unknown } } x => { rog::println!("wasc: unknown platform {}", x); std::process::exit(1); } }; if fl_gcc.is_empty() { match config.platform { context::Platform::CKBVMAssemblyScript | context::Platform::CKBVMSpectest => { fl_gcc = String::from("riscv64-unknown-elf-gcc"); } context::Platform::PosixX8664 | context::Platform::PosixX8664Spectest | context::Platform::PosixX8664Wasi => { fl_gcc = String::from("gcc"); } _ => {} } } config.binary_wavm = fl_wavm; config.binary_cc = fl_gcc; let middle = compile::compile(&fl_source, config)?; gcc::build(&middle)?; std::fs::copy( middle.path_output.clone(), middle.file.parent().unwrap().join(middle.file_stem.clone()), )?; if !fl_save { rog::debugln!("remove {}", middle.path_prog.to_str().unwrap()); std::fs::remove_dir_all(middle.path_prog)?; } Ok(()) }
use std::ptr; use libc::c_int; use curses; use {Error, Result, Attributes as Attr}; use super::Window; pub struct Attributes<'a> { window: &'a mut Window<'a>, } impl<'a> Attributes<'a> { #[inline] pub unsafe fn wrap<'b>(window: &'b mut Window<'b>) -> Attributes<'b> { Attributes { window: window } } } impl<'a> Attributes<'a> { #[inline] pub fn on(self, attr: Attr) -> Result<&'a mut Window<'a>> { unsafe { try!(Error::check(curses::wattron(self.window.as_mut_ptr(), attr.bits() as c_int))); } Ok(self.window) } #[inline] pub fn off(self, attr: Attr) -> Result<&'a mut Window<'a>> { unsafe { try!(Error::check(curses::wattroff(self.window.as_mut_ptr(), attr.bits() as c_int))); } Ok(self.window) } #[inline] pub fn set(self, attr: Attr) -> Result<&'a mut Window<'a>> { unsafe { try!(Error::check(curses::wattrset(self.window.as_mut_ptr(), attr.bits() as c_int))); } Ok(self.window) } #[inline] pub fn clear(self) -> Result<&'a mut Window<'a>> { unsafe { try!(Error::check(curses::wstandend(self.window.as_mut_ptr()))); } Ok(self.window) } #[inline] pub fn current(&self) -> Result<Attr> { unsafe { let mut attr = 0; let mut pair = 0; try!(Error::check(curses::wattr_get(self.window.as_ptr(), &mut attr, &mut pair, ptr::null()))); Ok(Attr::from_bits_truncate(attr)) } } #[inline] pub fn change(&mut self, attr: Attr, len: Option<usize>) -> Result<()> { unsafe { if let Some(n) = len { try!(Error::check(curses::wchgat(self.window.as_mut_ptr(), n as c_int, attr.bits(), 0, ptr::null()))); } else { try!(Error::check(curses::wchgat(self.window.as_mut_ptr(), -1, attr.bits(), 0, ptr::null()))); } } Ok(()) } }
use log::{self, debug}; use aws_sdk_dynamodb::Client; use aws_sdk_dynamodb::{error::PutItemError, output::PutItemOutput, types::SdkError}; use crate::types::Storable; pub async fn store_database_item( table_name: &str, data: &impl Storable, client: &Client, ) -> Result<PutItemOutput, SdkError<PutItemError>> { debug!("About to update DynamoDB"); client .put_item() .table_name(table_name) .item("PK", data.get_pk()) .item("value", data.to_dynamo_db()) .send() .await }
use wce_formats::binary_reader::BinaryReader; use wce_formats::blp::BLP; use wce_formats::MapArchive; use crate::globals::MAP_MINIMAP; use crate::OpeningError; pub struct MinimapFile { minimap: BLP } impl MinimapFile { pub fn read_file(map: &mut MapArchive) -> Result<Self, OpeningError>{ let file = map.open_file(MAP_MINIMAP).map_err(|e| OpeningError::Minimap(format!("{}",e)))?; let mut buffer: Vec<u8> = vec![0; file.size() as usize]; file.read(map, &mut buffer).map_err(|e| OpeningError::Minimap(format!("{}",e)))?; let mut reader = BinaryReader::new(buffer); let minimap: BLP = BLP::from(&mut reader); Ok(Self{ minimap }) } }
use super::text_doc::TextDoc; use jsonrpc_core::request::Notification; use jsonrpc_core::Params; use lsp_types::*; use pine::ast::input::StrRange; use std::collections::HashMap; use std::sync::mpsc::Sender; pub struct PineServer<'a> { init_params: Option<InitializeParams>, text_docs: HashMap<Url, TextDoc<'a>>, sender: Sender<String>, } fn from_str_range(range: StrRange) -> Range { Range::new( Position::new( range.start.get_line() as u64, range.start.get_character() as u64, ), Position::new( range.end.get_line() as u64, range.end.get_character() as u64, ), ) } // fn to_str_range(range: Range) -> StrRange { // StrRange::new( // StrPos::new(range.start.line as u32, range.start.character as u32), // StrPos::new(range.end.line as u32, range.end.character as u32), // ) // } impl<'a> PineServer<'a> { pub fn new(sender: Sender<String>) -> PineServer<'a> { PineServer { sender, init_params: None, text_docs: HashMap::new(), } } pub fn init_params(&mut self, init_params: InitializeParams) { self.init_params = Some(init_params); } pub fn add_doc(&mut self, params: DidOpenTextDocumentParams) { let text = params.text_document.text; let uri = params.text_document.uri; let mut new_doc = TextDoc::new(text, uri.clone()); self.parse_doc(&mut new_doc); self.text_docs.insert(uri, new_doc); self.send_notification( "window/showMessage", ShowMessageParams { typ: MessageType::Log, message: String::from("After open text document"), }, ); } pub fn change_doc(&mut self, params: DidChangeTextDocumentParams) { match self.text_docs.get_mut(&params.text_document.uri) { Some(doc) => { params.content_changes.into_iter().for_each(|item| { if let Some(range) = item.range { // let StrRange { start, end } = to_str_range(range); doc.change( range.start, range.end, item.range_length.unwrap() as usize, item.text, ); } else { doc.reset(item.text); } }); } None => return, }; let mut text_doc = self.text_docs.remove(&params.text_document.uri).unwrap(); self.parse_doc(&mut text_doc); self.text_docs.insert(params.text_document.uri, text_doc); self.send_notification( "window/showMessage", ShowMessageParams { typ: MessageType::Log, message: String::from("Change text document"), }, ); } pub fn parse_doc(&mut self, doc: &mut TextDoc) { // The below is the test code for publishing diagnostics. // let range = Range { // start: lsp_types::Position { // line: 3, // character: 0, // }, // end: lsp_types::Position { // line: 3, // character: 2, // }, // }; // let diagnostics = vec![Diagnostic { // range: range.clone(), // code: None, // severity: Some(DiagnosticSeverity::Error), // source: Some("pine ls".to_owned()), // message: "No entity \'ent2\' within library \'lib\'".to_owned(), // related_information: Some(vec![DiagnosticRelatedInformation { // location: Location::new(doc.get_uri().clone(), range.clone()), // message: String::from("Spelling matters"), // }]), // tags: None, // }]; // let publish_diagnostics = PublishDiagnosticsParams { // uri: doc.get_uri().clone(), // diagnostics: diagnostics, // version: None, // }; // info!("publish errors {:?}", publish_diagnostics); // self.send_notification("textDocument/publishDiagnostics", publish_diagnostics); if let Err(errs) = doc.parse_src() { let diagnostics: Vec<_> = errs .into_iter() .map(|err| { Diagnostic::new( from_str_range(err.range), Some(DiagnosticSeverity::Error), None, Some(String::from("pine ls")), err.message, None, None, ) }) .collect(); let publish_diagnostics = PublishDiagnosticsParams { uri: doc.get_uri().clone(), diagnostics: diagnostics, version: None, }; // info!("publish errors {:?}", publish_diagnostics); self.send_notification("textDocument/publishDiagnostics", publish_diagnostics); } else { let publish_diagnostics = PublishDiagnosticsParams { uri: doc.get_uri().clone(), diagnostics: vec![], version: None, }; self.send_notification("textDocument/publishDiagnostics", publish_diagnostics); } } pub fn send_notification( &self, method: impl Into<String>, notification: impl serde::ser::Serialize, ) { let params_json = match serde_json::to_value(notification).unwrap() { serde_json::Value::Object(map) => map, map => panic!("{:?}", map), }; let notification_json = Notification { jsonrpc: Some(jsonrpc_core::Version::V2), method: method.into(), params: Params::Map(params_json), }; self.sender .send(serde_json::to_string(&notification_json).unwrap()) .unwrap(); } } // fn client_supports_related_information(init_params: &InitializeParams) -> bool { // let try_fun = || { // init_params // .capabilities // .text_document // .as_ref()? // .publish_diagnostics // .as_ref()? // .related_information // }; // try_fun().unwrap_or(false) // } #[cfg(test)] mod tests { use super::*; use std::sync::mpsc::channel; #[test] fn pine_server_test() { let (sender, receiver) = channel::<String>(); let mut server = PineServer::new(sender); server.add_doc(DidOpenTextDocumentParams { text_document: TextDocumentItem::new( Url::parse("http://a.b").unwrap(), String::from("pine"), 2, String::from("a = "), ), }); // println!("receive msg {:?}", receiver.recv().unwrap()); // assert_eq!(1, 2); } }
use actix_web::{http::StatusCode, FromRequest, HttpResponse, Json, Path, Query}; use bigneon_api::controllers::events; use bigneon_api::controllers::events::*; use bigneon_api::models::PathParameters; use bigneon_api::models::*; use bigneon_db::models::*; use chrono::prelude::*; use serde_json; use support; use support::database::TestDatabase; use support::test_request::TestRequest; pub fn create(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let venue = database.create_venue().finish(); let name = "event Example"; let new_event = NewEvent { name: name.to_string(), organization_id: organization.id, venue_id: Some(venue.id), event_start: Some(NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11)), door_time: Some(NaiveDate::from_ymd(2016, 7, 8).and_hms(8, 11, 12)), publish_date: Some(NaiveDate::from_ymd(2016, 7, 1).and_hms(9, 10, 11)), ..Default::default() }; // Emulate serialization for default serde behavior let new_event: NewEvent = serde_json::from_str(&serde_json::to_string(&new_event).unwrap()).unwrap(); let json = Json(new_event); let response: HttpResponse = events::create((database.connection.into(), json, auth_user.clone())).into(); if should_test_succeed { assert_eq!(response.status(), StatusCode::CREATED); let body = support::unwrap_body_to_string(&response).unwrap(); let event: Event = serde_json::from_str(&body).unwrap(); assert_eq!(event.status, EventStatus::Draft.to_string()); } else { support::expects_unauthorized(&response); } } pub fn update(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let event = database .create_event() .with_organization(&organization) .finish(); let new_name = "New Event Name"; let test_request = TestRequest::create(); let json = Json(EventEditableAttributes { name: Some(new_name.to_string()), ..Default::default() }); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = event.id; let response: HttpResponse = events::update((database.connection.into(), path, json, auth_user.clone())).into(); let body = support::unwrap_body_to_string(&response).unwrap(); if should_test_succeed { assert_eq!(response.status(), StatusCode::OK); let updated_event: Event = serde_json::from_str(&body).unwrap(); assert_eq!(updated_event.name, new_name); } else { support::expects_unauthorized(&response); } } pub fn cancel(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let event = database .create_event() .with_organization(&organization) .finish(); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = event.id; let response: HttpResponse = events::cancel((database.connection.into(), path, auth_user)).into(); if should_test_succeed { let body = support::unwrap_body_to_string(&response).unwrap(); assert_eq!(response.status(), StatusCode::OK); let updated_event: Event = serde_json::from_str(&body).unwrap(); assert!(!updated_event.cancelled_at.is_none()); } else { support::expects_unauthorized(&response); } } pub fn add_artist(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let event = database .create_event() .with_organization(&organization) .finish(); let artist = database .create_artist() .with_organization(&organization) .finish(); let test_request = TestRequest::create(); let new_event_artist = AddArtistRequest { artist_id: artist.id, rank: 5, set_time: Some(NaiveDate::from_ymd(2016, 7, 1).and_hms(9, 10, 11)), }; let json = Json(new_event_artist); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = event.id; let response: HttpResponse = events::add_artist((database.connection.into(), path, json, auth_user.clone())).into(); if should_test_succeed { assert_eq!(response.status(), StatusCode::CREATED); } else { support::expects_unauthorized(&response); } } pub fn list_interested_users(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let event = database.create_event().finish(); let primary_user = support::create_auth_user(role, None, &database); EventInterest::create(event.id, primary_user.id()) .commit(&database.connection) .unwrap(); let n_secondary_users = 5; let mut secondary_users: Vec<DisplayEventInterestedUser> = Vec::new(); secondary_users.reserve(n_secondary_users); for _u_id in 0..n_secondary_users { let current_secondary_user = database.create_user().finish(); EventInterest::create(event.id, current_secondary_user.id) .commit(&database.connection) .unwrap(); let current_user_entry = DisplayEventInterestedUser { user_id: current_secondary_user.id, first_name: current_secondary_user.first_name.clone(), last_name: current_secondary_user.last_name.clone(), thumb_profile_pic_url: None, }; secondary_users.push(current_user_entry); } secondary_users.sort_by_key(|x| x.user_id); //Sort results for testing purposes //Construct api query let page: usize = 0; let limit: usize = 10; let test_request = TestRequest::create_with_uri(&format!( "/interest?page={}&limit={}", page.to_string(), limit.to_string() )); let query_parameters = Query::<PagingParameters>::from_request(&test_request.request, &()).unwrap(); let mut path_parameters = Path::<PathParameters>::extract(&test_request.request).unwrap(); path_parameters.id = event.id; let response: HttpResponse = events::list_interested_users(( database.connection.into(), path_parameters, query_parameters, primary_user, )).into(); let response_body = support::unwrap_body_to_string(&response).unwrap(); //Construct expected output let expected_data = DisplayEventInterestedUserList { total_interests: secondary_users.len() as u64, users: secondary_users, }; let wrapped_expected_date = Payload { data: expected_data.users, paging: Paging { page: 0, limit: 10, sort: "".to_string(), dir: SortingDir::None, total: expected_data.total_interests, tags: Vec::new(), }, }; let expected_json_body = serde_json::to_string(&wrapped_expected_date).unwrap(); if should_test_succeed { assert_eq!(response.status(), StatusCode::OK); assert_eq!(response_body, expected_json_body); } else { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); let temp_json = HttpResponse::Unauthorized().json(json!({"error": "Unauthorized"})); let updated_event = support::unwrap_body_to_string(&temp_json).unwrap(); assert_eq!(response_body, updated_event); } } pub fn add_interest(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let event = database.create_event().finish(); let user = support::create_auth_user(role, None, &database); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = event.id; let response: HttpResponse = events::add_interest((database.connection.into(), path, user)).into(); let body = support::unwrap_body_to_string(&response).unwrap(); if should_test_succeed { assert_eq!(response.status(), StatusCode::CREATED); } else { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); let temp_json = HttpResponse::Unauthorized().json(json!({"error": "Unauthorized"})); let updated_event = support::unwrap_body_to_string(&temp_json).unwrap(); assert_eq!(body, updated_event); } } pub fn remove_interest(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let event = database.create_event().finish(); EventInterest::create(event.id, user.id) .commit(&database.connection) .unwrap(); let user = support::create_auth_user_from_user(&user, role, None, &database); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = event.id; let response: HttpResponse = events::remove_interest((database.connection.into(), path, user)).into(); let body = support::unwrap_body_to_string(&response).unwrap(); if should_test_succeed { assert_eq!(response.status(), StatusCode::OK); assert_eq!(body, "1"); } else { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); let temp_json = HttpResponse::Unauthorized().json(json!({"error": "Unauthorized"})); let updated_event = support::unwrap_body_to_string(&temp_json).unwrap(); assert_eq!(body, updated_event); } } pub fn update_artists(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let event = database .create_event() .with_organization(&organization) .finish(); let artist1 = database.create_artist().finish(); let artist2 = database.create_artist().finish(); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = event.id; let mut payload: UpdateArtistsRequestList = Default::default(); payload.artists.push(UpdateArtistsRequest { artist_id: artist1.id, set_time: Some(NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11)), }); payload.artists.push(UpdateArtistsRequest { artist_id: artist2.id, set_time: None, }); let response: HttpResponse = events::update_artists(( database.connection.into(), path, Json(payload), auth_user.clone(), )).into(); let body = support::unwrap_body_to_string(&response).unwrap(); if should_test_succeed { assert_eq!(response.status(), StatusCode::OK); let returned_event_artists: Vec<EventArtist> = serde_json::from_str(&body).unwrap(); assert_eq!(returned_event_artists[0].artist_id, artist1.id); assert_eq!(returned_event_artists[1].set_time, None); } else { support::expects_unauthorized(&response); } } pub fn guest_list(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let event = database .create_event() .with_organization(&organization) .with_ticket_pricing() .finish(); database.create_order().for_event(&event).is_paid().finish(); database.create_order().for_event(&event).is_paid().finish(); let test_request = TestRequest::create_with_uri(&format!("/events/{}/guest?query=", event.id,)); let query_parameters = Query::<GuestListQueryParameters>::from_request(&test_request.request, &()).unwrap(); let mut path_parameters = Path::<PathParameters>::extract(&test_request.request).unwrap(); path_parameters.id = event.id; let response: HttpResponse = events::guest_list(( database.connection.into(), query_parameters, path_parameters, auth_user, )).into(); if should_test_succeed { assert_eq!(response.status(), StatusCode::OK); } else { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } }
pub use VkImageUsageFlags::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkImageUsageFlags { VK_IMAGE_USAGE_TRANSFER_SRC_BIT = 0x0000_0001, VK_IMAGE_USAGE_TRANSFER_DST_BIT = 0x0000_0002, VK_IMAGE_USAGE_SAMPLED_BIT = 0x0000_0004, VK_IMAGE_USAGE_STORAGE_BIT = 0x0000_0008, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT = 0x0000_0010, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT = 0x0000_0020, VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT = 0x0000_0040, VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT = 0x0000_0080, } use crate::SetupVkFlags; #[repr(C)] #[derive(Clone, Copy, Eq, PartialEq, Hash, Default)] pub struct VkImageUsageFlagBits(u32); SetupVkFlags!(VkImageUsageFlags, VkImageUsageFlagBits);
#[path = "math/random_integer_1.rs"] pub mod random_integer_1; use super::*;
// // web.rs // pub mod controllers; pub mod cors; pub mod error; pub mod guards; pub mod types; use self::controllers::*; use db::{create_pool, Pool}; use rocket::Rocket; pub fn build() -> Rocket { rocket::ignite() .manage(Pool(create_pool())) .mount( "/", routes![ cors::cors, accounts::login, accounts::register, accounts::all_users, accounts::user_by_id, accounts::create_user, accounts::create_profile, accounts::update_profile, accounts::get_profile, deal::create_deal, deal::get_deals, deal::update_deal, ], ) .attach(cors::CORS()) } pub fn launch() { build().launch(); }
// @author shailendra.sharma use std::ops::Range; use std::slice::Iter; use arrayvec::ArrayVec; use crate::bit_page::BitPage; pub enum BitPageActiveBitsIterator { AllZeroes, AllOnes { range: Range<usize> }, Some { iter: Box<dyn Iterator<Item = usize>> }, } impl<'a> Iterator for BitPageActiveBitsIterator { type Item = usize; fn next(&mut self) -> Option<Self::Item> { match self { BitPageActiveBitsIterator::AllZeroes => None, BitPageActiveBitsIterator::AllOnes { range } => range.next(), BitPageActiveBitsIterator::Some { iter } => iter.next(), } } } impl BitPage { pub fn active_bits(value: u64) -> BitPageActiveBitsIterator { match value { BitPage::MIN_VALUE => BitPageActiveBitsIterator::AllZeroes, BitPage::MAX_VALUE => BitPageActiveBitsIterator::AllOnes { range: (0..BitPage::MAX_BITS), }, _ => { let mut byte_masks = Vec::<u8>::with_capacity(BitPage::NUM_BYTES); for i in 0..BitPage::NUM_BYTES { let byte = (value >> (i * 8)) as u8; byte_masks.push(byte); } let iter = byte_masks .into_iter() .enumerate() .flat_map(|(byte_idx, byte_mask)| active_bits_iter(byte_mask).map(move |bit_idx| byte_idx * 8 + *bit_idx)); BitPageActiveBitsIterator::Some { iter: Box::new(iter) } } } } } const ACTIVE_BITS_LEN: usize = u8::max_value() as usize + 1; type ActiveBitsType = ArrayVec<[Vec<usize>; ACTIVE_BITS_LEN]>; lazy_static! { static ref ACTIVE_BITS: ActiveBitsType = build_byte_to_active_bits(); } fn build_byte_to_active_bits() -> ActiveBitsType { let mut array = ArrayVec::<[_; ACTIVE_BITS_LEN]>::new(); for i in 0..ACTIVE_BITS_LEN { array.push(build_active_bits(i as u8)); } array } fn build_active_bits(mut bit: u8) -> Vec<usize> { let mut index = 0; let mut bits = Vec::new(); while bit != 0 { if bit & 1 == 1 { bits.push(index); } bit >>= 1; index += 1; } bits } fn active_bits_iter(byte: u8) -> Iter<'static, usize> { ACTIVE_BITS[byte as usize].iter() } #[cfg(test)] mod tests { use itertools::Itertools; use crate::BitPage; #[test] fn test_ops() { println!("ALL ZEROS -- SET BIT"); for i in 0..64 { let mut bit_page = BitPage::zeroes(); BitPage::set_bit(&mut bit_page, i); println!( "BitPage[{}] = {:?} ==> {} ==> {:?}", i, bit_page, BitPage::is_bit_set(&bit_page, i), BitPage::active_bits(bit_page).collect_vec() ); } } }
// This example demonstrates a use-case where a lifetime in the owner is required. use std::borrow::Cow; use self_cell::self_cell; type Ast<'a> = Vec<&'a str>; self_cell!( struct AstCell<'input> { owner: Cow<'input, str>, #[covariant] dependent: Ast, } ); impl<'input> AstCell<'input> { // Escape input if necessary before constructing AST. fn from_un_escaped(input: &'input str) -> Self { println!("input: {:?}", input); let escaped_input = if input.contains("x") { Cow::from(input) } else { println!("escaping input (owned alloc)"); let owned: String = input.replace('u', "z"); Cow::from(owned) }; // This would be impossible without a self-referential struct. // escaped_input could either be a pointer to the input or an owned // string on stack. // We only want to depend on the input lifetime and encapsulate the // string escaping logic in a function. Which we can't do with // vanilla Rust. // Non self-referential version https://godbolt.org/z/3Pcc9a5za error. Self::new(escaped_input, |escaped_input| { // Dummy for expensive computation you don't want to redo. escaped_input.split(' ').collect() }) } } fn main() { let not_escaped = AstCell::from_un_escaped("au bx"); println!( "not_escaped.borrow_dependent() -> {:?}", not_escaped.borrow_dependent() ); let escaped = AstCell::from_un_escaped("au bz"); println!( "escaped.borrow_dependent() -> {:?}", escaped.borrow_dependent() ); }