text
stringlengths
8
4.13M
#![allow(dead_code)] use crate::{aocbail, utils}; use utils::{AOCResult, AOCError}; pub fn day9() { let input = utils::get_input("day9"); let bad_value = find_bad_value(input, 25).unwrap(); println!("encoding_error part 1: {}", bad_value.1); let input = utils::get_input("day9"); println!("encoding_error part 2: {}", find_sum(input, bad_value.0).unwrap()); } pub fn find_bad_value(input: impl Iterator<Item = String>, cache_size: usize) -> AOCResult<(usize, i32)> { let mut cache: Vec<i32> = Vec::with_capacity(cache_size); 'outer: for (i, line) in input.enumerate() { let value = line.parse::<i32>()?; if i < cache_size { cache.push(value); continue; } else { for j in 0..cache.len() { for k in 1..cache.len() { if cache[j] + cache[k] == value { cache.remove(0); cache.push(value); continue 'outer; } } } } return Ok((i, value)); } aocbail!("Unable to find illegal entry"); } pub fn find_sum(mut input: impl Iterator<Item = String>, target_id: usize) -> AOCResult<i32> { let mut values: Vec<i32> = Vec::new(); for _ in 0..=target_id { let value = input.next()?; values.push(value.parse::<i32>()?); } let target = values[target_id]; let mut end = 0; let mut running_sum = values[0]; 'outer: for start in 0..target_id { while running_sum != target { if running_sum > target { running_sum -= values[start]; while running_sum > target { running_sum -= values[end]; end -= 1; } continue 'outer; } end += 1; running_sum += values[end]; } let mut min = values[start]; let mut max = values[start]; for i in start..=end { min = std::cmp::min(min, values[i]); max = std::cmp::max(max, values[i]); } return Ok(min + max); } aocbail!("Something horrible happened"); } #[test] pub fn encoding_error() { let input = utils::get_input("test_day9"); let bad_value = find_bad_value(input, 5).unwrap(); assert_eq!( bad_value.1, 127 ); let input = utils::get_input("test_day9"); assert_eq!( find_sum(input, bad_value.0).unwrap(), 62 ); }
use std::collections::HashSet; use std::io; use std::io::Read; fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); println!("{}", input.split("\n\n").map(|x| { x.chars().filter(|y| y.is_ascii_lowercase()).collect::<HashSet<char>>().len() }).sum::<usize>()); }
use std::collections::HashMap; use std::iter::FromIterator; struct Pos { x: i32, y: i32, } fn create_map() -> HashMap<char, Pos> { let iter = "123456789.0".chars().enumerate() .map(|(n, c)| { (c, Pos{ x: (n as i32) % 3, y: (n as i32) / 3 } ) }); HashMap::<char, Pos>::from_iter(iter) } fn dist(p1: &Pos, p2: &Pos) -> f32 { let dx = p1.x - p2.x; let dy = p1.y - p2.y; ((dx*dx + dy*dy) as f32).sqrt() } fn main() { let map = create_map(); let seq = "219.45.143.143"; let tot = seq.chars().zip(seq.chars().skip(1)) .fold(0f32, |sum, (p, c)| { sum + dist(map.get(&p).unwrap(), map.get(&c).unwrap()) }); println!("Tot: {}", tot); }
use scanner_proc_macro::insert_scanner; #[insert_scanner] fn main() { let (n, x) = scan!((usize, usize)); let ab = scan!((usize, usize); n); let mut dp = vec![false; x + 1]; dp[0] = true; for (a, b) in ab { let mut nxt = vec![false; x + 1]; for y in 0..x { if y + a <= x { nxt[y + a] |= dp[y]; } if y + b <= x { nxt[y + b] |= dp[y]; } } dp = nxt; } if dp[x] { println!("Yes"); } else { println!("No"); } }
use std::cmp; use std::collections::BTreeMap; type PreReqVec = Vec<char>; type NodeMap = BTreeMap<char, PreReqVec>; #[derive(Debug, Clone)] struct Job { node: char, end_time: u32 } #[derive(Debug, Clone)] struct Worker { queue: Vec<Job> } impl Worker { fn get_node_end_time(&self, node: char) -> Option<u32> { self.queue.iter().find(|j| j.node == node).and_then(|j| Some(j.end_time)) } fn get_earliest_start_time(&self) -> u32 { self.queue.iter().map(|j| j.end_time).last().unwrap_or(0) } fn schedule(&mut self, n: char, not_before: u32, duration: u32) { //println!("\t\tQueue => {:?}", self.queue); let start_at = cmp::max(not_before, self.get_earliest_start_time()); let d = get_node_time(n, duration); let e = start_at + get_node_time(n, duration); //println!("\t\tScheduling node {} to start at {} with duration {}", n, start_at, d); self.queue.push(Job { node: n, end_time: e }); //println!("\t\tQueue => {:?}", self.queue); } fn bid_node(&self, start_time: u32) -> u32 { let e = self.get_earliest_start_time(); cmp::max(e, start_time) - start_time } fn node_at_time(&self, time: u32, duration: u32) -> Option<char> { self.queue.iter().find(|j| { time >= (j.end_time - get_node_time(j.node, duration)) && time < j.end_time }).and_then(|j| Some(j.node)) } } struct ElfPool { workers : Vec<Worker>, duration : u32, nodes : NodeMap } impl ElfPool { fn new(num_workers: u32, dur: u32, map: &NodeMap) -> ElfPool { ElfPool { workers : vec!(Worker { queue: vec!() } ; num_workers as usize), duration : dur, nodes: map.to_owned() } } fn get_node_end_time(&self, node: char) -> Option<u32> { self.workers.iter().find_map(|w| w.get_node_end_time(node)) } fn is_node_queued(&self, node: char) -> bool { self.workers.iter().any(|w| w.get_node_end_time(node).is_some()) } fn can_schedule(&mut self, node: char) -> bool { !self.is_node_queued(node) && self.nodes.get(&node).unwrap_or(&PreReqVec::new()).iter().all(|p| self.is_node_queued(*p)) } fn schedule(&mut self, node: char) { //println!("Attempting to schedule node {}", node); let start_time = self.nodes.get(&node).unwrap_or(&PreReqVec::new()).iter().filter_map(|n| { self.get_node_end_time(*n) }).max().unwrap_or(0); // println!("\tEarliest possible start time is {}", start_time); (*self.workers.iter_mut().min_by_key(|w| w.bid_node(start_time)).unwrap()).schedule(node, start_time, self.duration); } fn resolve(&self) -> u32 { self.workers.iter().map(|w| w.get_earliest_start_time()).max().unwrap() } fn print(&self) { for x in 0..=self.resolve() { print!("{:04}", x); for job in self.workers.iter().map(|w| w.node_at_time(x, self.duration)) { let c = match job { Some(n) => n, None => '.' }; print!("\t{}", c); } println!(""); } } } fn get_node_time(node: char, base_time: u32) -> u32 { assert!(node.is_alphabetic() && node.is_uppercase()); (node as u8 - 64) as u32 + base_time } fn build_node_map(input_str: &str) -> NodeMap { input_str.lines().fold(NodeMap::new(), |mut map, l| { let (pre_req, node) = (l.chars().nth(5).unwrap(), l.chars().nth(36).unwrap()); if !map.contains_key(&pre_req) { map.insert(pre_req, vec!()); } (*map.entry(node).or_insert(PreReqVec::new())).push(pre_req); map }) } fn is_node_available(node: &char, nodes: &NodeMap, visited: &Vec<char>) -> bool { !visited.contains(node) && nodes.get(node).unwrap().iter().all(|n| visited.contains(n)) } fn traverse_nodes(nodes: &NodeMap) -> String { let mut visited : Vec<char> = vec!(); let mut keys = nodes.keys().cloned().collect::<Vec<char>>(); while !keys.is_empty() { let found_idx = keys.iter().enumerate().find(|x| is_node_available(x.1, nodes, &visited)).unwrap().0; visited.push(keys.drain(found_idx..found_idx+1).nth(0).unwrap()); } visited.iter().collect::<String>() } fn part_1_solve(input_str: &str) -> String { traverse_nodes(&build_node_map(input_str)) } fn traverse_nodes_parallel(nodes: &NodeMap, num_workers: u32, duration: u32) -> u32 { let mut pool = ElfPool::new(num_workers, duration, nodes); while nodes.keys().any(|n| !pool.is_node_queued(*n)) { let schedule_keys = nodes.keys().cloned().filter(|k| pool.can_schedule(*k)).collect::<Vec<char>>(); //println!("== Schedule Pass for {:?} ==", schedule_keys); for n in schedule_keys { pool.schedule(n); } //println!("================================="); } pool.print(); pool.resolve() } fn part_2_solve(input_str: &str, num_workers: u32, duration: u32) -> u32 { traverse_nodes_parallel(&build_node_map(input_str), num_workers, duration) } fn main() { println!("Part 1: {}", part_1_solve(include_str!("../input/input.txt"))); println!("Part 2: {}", part_2_solve(include_str!("../input/input.txt"), 5, 60)); } #[test] fn part_1_test() { assert_eq!(part_1_solve(include_str!("../input/test_input_1.txt")), "CABDFE"); } #[test] fn part_2_test() { assert_eq!(part_2_solve(include_str!("../input/test_input_1.txt"), 2, 0), 15); assert_eq!(get_node_time('A', 0), 1); assert_eq!(get_node_time('Z', 0), 26); }
//! https://github.com/lumen/otp/tree/lumen/lib/parsetools/src use super::*; test_compiles_lumen_otp!(leex); test_compiles_lumen_otp!(yecc); test_compiles_lumen_otp!(yeccparser); test_compiles_lumen_otp!(yeccscan imports "lib/stdlib/src/erl_scan", "lib/stdlib/src/io"); fn relative_directory_path() -> PathBuf { super::relative_directory_path().join("parsetools/src") }
use std::{ collections::HashMap, sync::{Arc, Mutex}, }; use crate::events::SenseiEvent; use super::database::WalletDatabase; use bitcoin::{Transaction, Txid}; use lightning::chain::chaininterface::BroadcasterInterface; use tokio::sync::broadcast; pub struct SenseiBroadcaster { pub debounce: Mutex<HashMap<Txid, usize>>, pub node_id: String, pub broadcaster: Arc<dyn BroadcasterInterface + Send + Sync>, pub wallet_database: Arc<Mutex<WalletDatabase>>, pub event_sender: broadcast::Sender<SenseiEvent>, } impl SenseiBroadcaster { pub fn new( node_id: String, broadcaster: Arc<dyn BroadcasterInterface + Send + Sync>, wallet_database: Arc<Mutex<WalletDatabase>>, event_sender: broadcast::Sender<SenseiEvent>, ) -> Self { Self { node_id, broadcaster, wallet_database, event_sender, debounce: Mutex::new(HashMap::new()), } } pub fn set_debounce(&self, txid: Txid, count: usize) { let mut debounce = self.debounce.lock().unwrap(); debounce.insert(txid, count); } pub fn broadcast(&self, tx: &Transaction) { self.broadcaster.broadcast_transaction(tx); // TODO: there's a bug here if the broadcast fails // best solution is to probably setup a zmq listener let mut database = self.wallet_database.lock().unwrap(); database.process_mempool_tx(tx); self.event_sender .send(SenseiEvent::TransactionBroadcast { node_id: self.node_id.clone(), txid: tx.txid(), }) .unwrap_or_default(); } } impl BroadcasterInterface for SenseiBroadcaster { fn broadcast_transaction(&self, tx: &Transaction) { let txid = tx.txid(); let mut debounce = self.debounce.lock().unwrap(); let can_broadcast = match debounce.get_mut(&txid) { Some(count) => { *count -= 1; *count == 0 } None => true, }; if can_broadcast { self.broadcast(tx); } } }
use std::fmt; use std::io; use std::result; /// A convenient type alias for `Result<T, snap::Error>`. pub type Result<T> = result::Result<T, Error>; /// `IntoInnerError` occurs when consuming an encoder fails. /// /// Consuming the encoder causes a flush to happen. If the flush fails, then /// this error is returned, which contains both the original encoder and the /// error that occurred. /// /// The type parameter `W` is the unconsumed writer. pub struct IntoInnerError<W> { wtr: W, err: io::Error, } impl<W> IntoInnerError<W> { pub(crate) fn new(wtr: W, err: io::Error) -> IntoInnerError<W> { IntoInnerError { wtr, err } } /// Returns the error which caused the call to `into_inner` to fail. /// /// This error was returned when attempting to flush the internal buffer. pub fn error(&self) -> &io::Error { &self.err } /// Returns the error which caused the call to `into_inner` to fail. /// /// This error was returned when attempting to flush the internal buffer. pub fn into_error(self) -> io::Error { self.err } /// Returns the underlying writer which generated the error. /// /// The returned value can be used for error recovery, such as /// re-inspecting the buffer. pub fn into_inner(self) -> W { self.wtr } } impl<W: std::any::Any> std::error::Error for IntoInnerError<W> {} impl<W> fmt::Display for IntoInnerError<W> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.err.fmt(f) } } impl<W> fmt::Debug for IntoInnerError<W> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.err.fmt(f) } } /// Error describes all the possible errors that may occur during Snappy /// compression or decompression. /// /// Note that it's unlikely that you'll need to care about the specific error /// reported since all of them indicate a corrupt Snappy data or a limitation /// that cannot be worked around. Therefore, /// `From<snap::Error> for std::io::Error` is provided so that any Snappy /// errors will be converted to a `std::io::Error` automatically when using /// `try!`. #[derive(Clone, Debug)] pub enum Error { /// This error occurs when the given input is too big. This can happen /// during compression or decompression. TooBig { /// The size of the given input. given: u64, /// The maximum allowed size of an input buffer. max: u64, }, /// This error occurs when the given buffer is too small to contain the /// maximum possible compressed bytes or the total number of decompressed /// bytes. BufferTooSmall { /// The size of the given output buffer. given: u64, /// The minimum size of the output buffer. min: u64, }, /// This error occurs when trying to decompress a zero length buffer. Empty, /// This error occurs when an invalid header is found during decompression. Header, /// This error occurs when there is a mismatch between the number of /// decompressed bytes reported in the header and the number of /// actual decompressed bytes. In this error case, the number of actual /// decompressed bytes is always less than the number reported in the /// header. HeaderMismatch { /// The total number of decompressed bytes expected (i.e., the header /// value). expected_len: u64, /// The total number of actual decompressed bytes. got_len: u64, }, /// This error occurs during decompression when there was a problem /// reading a literal. Literal { /// The expected length of the literal. len: u64, /// The number of remaining bytes in the compressed bytes. src_len: u64, /// The number of remaining slots in the decompression buffer. dst_len: u64, }, /// This error occurs during decompression when there was a problem /// reading a copy. CopyRead { /// The expected length of the copy (as encoded in the compressed /// bytes). len: u64, /// The number of remaining bytes in the compressed bytes. src_len: u64, }, /// This error occurs during decompression when there was a problem /// writing a copy to the decompression buffer. CopyWrite { /// The length of the copy (i.e., the total number of bytes to be /// produced by this copy in the decompression buffer). len: u64, /// The number of remaining bytes in the decompression buffer. dst_len: u64, }, /// This error occurs during decompression when an invalid copy offset /// is found. An offset is invalid if it is zero or if it is out of bounds. Offset { /// The offset that was read. offset: u64, /// The current position in the decompression buffer. If the offset is /// non-zero, then the offset must be greater than this position. dst_pos: u64, }, /// This error occurs when a stream header chunk type was expected but got /// a different chunk type. /// This error only occurs when reading a Snappy frame formatted stream. StreamHeader { /// The chunk type byte that was read. byte: u8, }, /// This error occurs when the magic stream headers bytes do not match /// what is expected. /// This error only occurs when reading a Snappy frame formatted stream. StreamHeaderMismatch { /// The bytes that were read. bytes: Vec<u8>, }, /// This error occurs when an unsupported chunk type is seen. /// This error only occurs when reading a Snappy frame formatted stream. UnsupportedChunkType { /// The chunk type byte that was read. byte: u8, }, /// This error occurs when trying to read a chunk with an unexpected or /// incorrect length when reading a Snappy frame formatted stream. /// This error only occurs when reading a Snappy frame formatted stream. UnsupportedChunkLength { /// The length of the chunk encountered. len: u64, /// True when this error occured while reading the stream header. header: bool, }, /// This error occurs when a checksum validity check fails. /// This error only occurs when reading a Snappy frame formatted stream. Checksum { /// The expected checksum read from the stream. expected: u32, /// The computed checksum. got: u32, }, } impl From<Error> for io::Error { fn from(err: Error) -> io::Error { io::Error::new(io::ErrorKind::Other, err) } } impl Eq for Error {} impl PartialEq for Error { fn eq(&self, other: &Error) -> bool { use self::Error::*; match (self, other) { ( &TooBig { given: given1, max: max1 }, &TooBig { given: given2, max: max2 }, ) => (given1, max1) == (given2, max2), ( &BufferTooSmall { given: given1, min: min1 }, &BufferTooSmall { given: given2, min: min2 }, ) => (given1, min1) == (given2, min2), (&Empty, &Empty) | (&Header, &Header) => true, ( &HeaderMismatch { expected_len: elen1, got_len: glen1 }, &HeaderMismatch { expected_len: elen2, got_len: glen2 }, ) => (elen1, glen1) == (elen2, glen2), ( &Literal { len: len1, src_len: src_len1, dst_len: dst_len1 }, &Literal { len: len2, src_len: src_len2, dst_len: dst_len2 }, ) => (len1, src_len1, dst_len1) == (len2, src_len2, dst_len2), ( &CopyRead { len: len1, src_len: src_len1 }, &CopyRead { len: len2, src_len: src_len2 }, ) => (len1, src_len1) == (len2, src_len2), ( &CopyWrite { len: len1, dst_len: dst_len1 }, &CopyWrite { len: len2, dst_len: dst_len2 }, ) => (len1, dst_len1) == (len2, dst_len2), ( &Offset { offset: offset1, dst_pos: dst_pos1 }, &Offset { offset: offset2, dst_pos: dst_pos2 }, ) => (offset1, dst_pos1) == (offset2, dst_pos2), (&StreamHeader { byte: byte1 }, &StreamHeader { byte: byte2 }) => { byte1 == byte2 } ( &StreamHeaderMismatch { bytes: ref bytes1 }, &StreamHeaderMismatch { bytes: ref bytes2 }, ) => bytes1 == bytes2, ( &UnsupportedChunkType { byte: byte1 }, &UnsupportedChunkType { byte: byte2 }, ) => byte1 == byte2, ( &UnsupportedChunkLength { len: len1, header: header1 }, &UnsupportedChunkLength { len: len2, header: header2 }, ) => (len1, header1) == (len2, header2), ( &Checksum { expected: e1, got: g1 }, &Checksum { expected: e2, got: g2 }, ) => (e1, g1) == (e2, g2), _ => false, } } } impl std::error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Error::TooBig { given, max } => write!( f, "snappy: input buffer (size = {}) is larger than \ allowed (size = {})", given, max ), Error::BufferTooSmall { given, min } => write!( f, "snappy: output buffer (size = {}) is smaller than \ required (size = {})", given, min ), Error::Empty => write!(f, "snappy: corrupt input (empty)"), Error::Header => { write!(f, "snappy: corrupt input (invalid header)") } Error::HeaderMismatch { expected_len, got_len } => write!( f, "snappy: corrupt input (header mismatch; expected \ {} decompressed bytes but got {})", expected_len, got_len ), Error::Literal { len, src_len, dst_len } => write!( f, "snappy: corrupt input (expected literal read of \ length {}; remaining src: {}; remaining dst: {})", len, src_len, dst_len ), Error::CopyRead { len, src_len } => write!( f, "snappy: corrupt input (expected copy read of \ length {}; remaining src: {})", len, src_len ), Error::CopyWrite { len, dst_len } => write!( f, "snappy: corrupt input (expected copy write of \ length {}; remaining dst: {})", len, dst_len ), Error::Offset { offset, dst_pos } => write!( f, "snappy: corrupt input (expected valid offset but \ got offset {}; dst position: {})", offset, dst_pos ), Error::StreamHeader { byte } => write!( f, "snappy: corrupt input (expected stream header but \ got unexpected chunk type byte {})", byte ), Error::StreamHeaderMismatch { ref bytes } => write!( f, "snappy: corrupt input (expected sNaPpY stream \ header but got {})", escape(&**bytes) ), Error::UnsupportedChunkType { byte } => write!( f, "snappy: corrupt input (unsupported chunk type: {})", byte ), Error::UnsupportedChunkLength { len, header: false } => write!( f, "snappy: corrupt input \ (unsupported chunk length: {})", len ), Error::UnsupportedChunkLength { len, header: true } => write!( f, "snappy: corrupt input \ (invalid stream header length: {})", len ), Error::Checksum { expected, got } => write!( f, "snappy: corrupt input (bad checksum; \ expected: {}, got: {})", expected, got ), } } } fn escape(bytes: &[u8]) -> String { use std::ascii::escape_default; bytes.iter().flat_map(|&b| escape_default(b)).map(|b| b as char).collect() }
#![crate_name = "fserve"] extern crate either; #[macro_use] extern crate log; extern crate env_logger; extern crate mio; #[macro_use] extern crate mioco; extern crate rand; extern crate base64; extern crate time; mod controller; mod model; mod messagebuilder; mod state; mod utils; use either::*; use mio::tcp::TcpStream; use mioco::tcp::TcpListener; use mioco::MioAdapter; use mioco::sync::Mutex; use mioco::sync::mpsc::{channel, Receiver, Sender}; use std::env; use log::{LogRecord, LogLevelFilter}; use env_logger::LogBuilder; use std::io::prelude::*; use std::io; use std::net::SocketAddr; use std::sync::Arc; use std::sync::mpsc::TryRecvError; use std::str::FromStr; use std::thread; use messagebuilder::*; use controller::HandlerMessage; use model::*; use state::State; use utils::*; type HandlerParam = (HandlerMessage, Arc<Player>); fn listend_addr() -> SocketAddr { let port = env::args().nth(1).unwrap_or("12345".to_string()); let addr = format!("0.0.0.0:{}", &port); FromStr::from_str(&addr).unwrap() } pub fn run_server() { init_logger(); let (handler_tx, handler_rx) = channel::<HandlerParam>(); start_handler(handler_rx); start_listen(Arc::new(Mutex::new(handler_tx))); } fn start_handler(handler_rx : Receiver<HandlerParam>) { thread::spawn(move|| { info!("Start handler"); mioco::start_threads(1, move || -> io::Result<()> { let mut server_state = State::new(); loop { let (message, player) = try!(map_io_err(handler_rx.recv())); if let Err(err) = controller::handle_msg(message, player, &mut server_state) { error!("Failed handling msg {}", err); } } }).unwrap().unwrap(); }); } fn start_listen(handler_tx : Arc<Mutex<Sender<HandlerParam>>>) { mioco::start(move || -> io::Result<()> { let addr = listend_addr(); let listener = try!(TcpListener::bind(&addr)); info!("Starting tcp server on {:?}", try!(listener.local_addr())); loop { let mut conn = try!(listener.accept()); let handler_tx = handler_tx.clone(); let (tx, rx) = channel::<Arc<Message>>(); mioco::spawn(move || -> io::Result<()> { let player = Arc::new(Player::new(tx)); try!(add_player(player.clone(), &handler_tx)); if let Err(err) = controller::send(Arc::new(Message::new(MessageType::Welcome, "Welcome apprentice")), &player) { return Err(io_err(&format!("Failed sending welcome {}", err))); } let mut message_builder = MessageBuilder::new(); let mut buf = [0u8; 1024]; loop { select!( r:conn => { match try!(handle_read(&mut conn, &mut buf, message_builder, player.clone(), &handler_tx)) { Some(mb) => message_builder = mb, None => break } }, r:rx => { try!(handle_write(&mut conn, &rx)); }, ); } debug!("leaving coroutine"); Ok(()) }); } }).unwrap().unwrap(); } fn add_player(player : Arc<Player>, handler_tx : &Mutex<Sender<HandlerParam>>) -> io::Result<()> { let tx = try!(map_io_err(handler_tx.lock())); map_io_err(tx.send((HandlerMessage::AddPlayer, player))) } fn handle_write(conn : &mut MioAdapter<TcpStream>, rx: &Receiver<Arc<Message>>) -> io::Result<()> { match rx.try_recv() { Ok(msg) => { let mut header = msg.header.to_string().into_bytes(); header.push(b'\n'); try!(conn.write_all(&header)); try!(conn.write_all(&msg.body)); try!(conn.flush()); debug!("Sent {:?}", msg.header); }, Err(TryRecvError::Empty) => debug!("Write handle: empty event"), Err(TryRecvError::Disconnected) => debug!("Write handle: disconnected event"), } Ok(()) } fn handle_read( conn : &mut MioAdapter<TcpStream>, mut buf : &mut [u8], mut message_builder : MessageBuilder, player : Arc<Player>, handler_tx : &Mutex<Sender<HandlerParam>>) -> io::Result<Option<MessageBuilder>> { let size_option = try!(conn.try_read(&mut buf)); if let Some(size) = size_option { if size == 0 { info!("Left {}", player.id); let tx = try!(map_io_err(handler_tx.lock())); try!(map_io_err(tx.send((HandlerMessage::ReleasePlayer, player.clone())))); return Ok(None); } let mut slice = &buf[0..size]; loop { match message_builder.process(slice) { Ok(processed) => match processed { Right((message, offset)) => { message_builder = MessageBuilder::new(); trace!("message found {}, remaining {}", offset, slice.len()); slice = try!(check_slice(&slice, offset, slice.len())); let tx = try!(map_io_err(handler_tx.lock())); try!(map_io_err(tx.send((HandlerMessage::ClientMessage(Arc::new(message)), player.clone())))); }, Left(mb) => { trace!("process no message continuing.."); message_builder = mb; break; } }, Err(err) => { error!("Failed processing buffer {}", err); message_builder = MessageBuilder::new(); break; } } } } Ok(Some(message_builder)) } fn init_logger() { let format = |record: &LogRecord| { format!("{} - {} {} {}", time::strftime("%Y-%m-%d %H:%M:%S %Z", &time::now()).unwrap(), record.level(), record.location().module_path(), record.args()) }; let mut builder = LogBuilder::new(); builder .format(format) .filter(None, LogLevelFilter::Info); if env::var("RUST_LOG").is_ok() { builder.parse(&env::var("RUST_LOG").unwrap()); } builder.init().unwrap(); }
// 並列処理を実装。 // lib.rs から SortOrder 列挙型を読み込む。 use super::SortOrder; // rayon クレートを読み込む。 use rayon; // std::cmp から Ordering を読み込む。 use std::cmp::Ordering; // 並列処理を実行するかどうかの閾値。 const PARALLEL_THRESHOLD: usize = 4096; // pub 修飾子でモジュール (このファイル) 外から呼び出し可能となる。 // 型パラメータを <T> で導入する。ただし、大小比較ができるものに型を制限するために、 // <T: Ord + Send> としてトレイト境界に Ord と Send を指定する。 // 引数は可変な Ord と Send を持つ何らかの型の値からなるスライス (配列) の参照と、SortOrder 列挙型。 // 戻り値は、Result 型。関数成功時はユニット型 ()、エラーの場合は String 型となる。 pub fn sort<T: Ord + Send>(x: &mut [T], order: &SortOrder) -> Result<(), String> { // SortOrder 型の参照である order の参照を外してマッチングする。 // u8 型の cmp メソッドは u8 型の値を比較して、Ordering 型の値を返す。 match *order { SortOrder::Ascending => sort_by(x, &|a, b| a.cmp(b)), SortOrder::Decending => sort_by(x, &|a, b| b.cmp(a)), } } // 型パラメータ <F> はクロージャを表す。 // クロージャはすべて別の型として扱われるため、引数にとるときは必ずジェネリクスにする必要がある。 pub fn sort_by<T, F>(x: &mut [T], comparator: &F) -> Result<(), String> // where 節で T と F のトレイト境界を定義する。 // Send と Sync は並列処理時のメモリ安全を保証するためのトレイト境界。 // Fn トレイトは環境へのアクセスが読み出し専用で、何度でも呼ぶことができるもの。 // このクロージャは T 型の値の参照を 2 つ引数にとり、Ordering 型を返すものに制限する。 where T: Send, F: Sync + Fn(&T, &T) -> Ordering, { // is_power_of_two 関数で引数 x の長さが 2 のべき乗かどうかをチェックする。 if x.len().is_power_of_two() { do_sort(x, true, comparator); // 2 のべき乗の時は do_sort 関数の処理の後にユニット型 () を返す。 Ok(()) } else { // エラー時 (長さが 2 のべき乗ではない) はエラー文字列を返す。 Err(format!( "The length of x is not a power of two. (x.len(): {})", x.len() )) } } fn do_sort<T, F>(x: &mut [T], forward: bool, comparator: &F) where T: Send, F: Sync + Fn(&T, &T) -> Ordering, { if x.len() > 1 { let mid_point = x.len() / 2; // xをmid_pointを境にした2つの可変の借用に分割し first と second に束縛する。 let (mut first, mut second) = x.split_at_mut(mid_point); // x の分割後の要素数が閾値を超えていたら、rayon による並列処理を行う。 if mid_point >= PARALLEL_THRESHOLD { rayon::join( || do_sort(&mut first, true, comparator), || do_sort(&mut second, false, comparator), ); } else { do_sort(&mut first, true, comparator); do_sort(&mut second, false, comparator); } sub_sort(x, forward, comparator); } } fn sub_sort<T, F>(x: &mut [T], forward: bool, comparator: &F) where T: Send, F: Sync + Fn(&T, &T) -> Ordering, { if x.len() > 1 { compare_and_swap(x, forward, comparator); let mid_point = x.len() / 2; let (mut first, mut second) = x.split_at_mut(mid_point); // x の分割後の要素数が閾値を超えていたら、rayon による並列処理を行う。 if mid_point >= PARALLEL_THRESHOLD { rayon::join( || sub_sort(&mut first, forward, comparator), || sub_sort(&mut second, forward, comparator), ); } else { sub_sort(&mut first, forward, comparator); sub_sort(&mut second, forward, comparator); } } } fn compare_and_swap<T, F>(x: &mut [T], forward: bool, comparator: &F) where F: Fn(&T, &T) -> Ordering, { let swap_condition = if forward { Ordering::Greater } else { Ordering::Less }; let mid_point = x.len() / 2; for i in 0..mid_point { if comparator(&x[i], &x[mid_point + i]) == swap_condition { x.swap(i, mid_point + i) } } } // 単体テスト。 // このモジュールは cargo test を実行したときのみコンパイルされる。 #[cfg(test)] mod tests { // 親モジュールの sort と sort_by 関数をテストのために読み込む。 // また、SortOrder 列挙型のすべてのバリアントも読み込む。 use super::{sort, sort_by}; use crate::utils::{is_sorted, new_u32_vec}; use crate::SortOrder::*; // Student 構造体を定義する。 // derive アトリビュートで Debug および PartialEq トレイトを自動導出する。 #[derive(Debug, PartialEq)] struct Student { // Student は 3 つのフィールドを持つ。 first_name: String, last_name: String, age: u8, } // Student のを実装する。 impl Student { // 初期化のための関連関数 new を定義する。ここでは Self は Student の別名となる。 fn new(first_name: &str, last_name: &str, age: u8) -> Self { Self { first_name: first_name.to_string(), // &str を String に変換する。 last_name: last_name.to_string(), age, // フィールドと変数が同名の時はこのように省略形にできる。 } } } // #[test] の付いた関数は cargo test を実行したとき実行される。 // 整数値のソートのテストを行う。 #[test] fn sort_u32_ascending() { // x に型注釈 Vec<u32> をつける。 let mut x: Vec<u32> = vec![10, 30, 11, 20, 4, 330, 21, 110]; // &Ascending は SortOrder 列挙型のバリアントのひとつ。 // まずは sort 関数が Result 型の Ok (ユニット) を返すかどうかをチェック。 assert_eq!(sort(&mut x, &Ascending), Ok(())); // 次にソート結果が想定したものかどうかをチェックする。 assert_eq!(x, vec![4, 10, 11, 20, 21, 30, 110, 330]); } #[test] fn sort_u32_decending() { let mut x: Vec<u32> = vec![10, 30, 11, 20, 4, 330, 21, 110]; assert_eq!(sort(&mut x, &Decending), Ok(())); assert_eq!(x, vec![330, 110, 30, 21, 20, 11, 10, 4]); } // 文字列のソートのテストを行う。 #[test] fn sort_str_ascending() { let mut x = vec![ "Rust", "is", "fast", "and", "memory-efficient", "with", "no", "GC", ]; assert_eq!(sort(&mut x, &Ascending), Ok(())); assert_eq!( x, vec![ "GC", "Rust", "and", "fast", "is", "memory-efficient", "no", "with" ] ); } #[test] fn sort_str_decending() { let mut x = vec![ "Rust", "is", "fast", "and", "memory-efficient", "with", "no", "GC", ]; assert_eq!(sort(&mut x, &Decending), Ok(())); assert_eq!( x, vec![ "with", "no", "memory-efficient", "is", "fast", "and", "Rust", "GC" ] ) } // x の長さが 2 のべき乗でない場合にエラーを返すかどうかのテストを行う。 #[test] fn sort_to_fail() { let mut x = vec![10, 30, 11]; assert!(sort(&mut x, &Ascending).is_err()); } // Student の age フィールドによるソートのテストを行う。 #[test] fn sort_students_by_age_ascending() { // 4 つの Student 型のデータを作成する。 let taro = Student::new("Taro", "Yamada", 16); let hanako = Student::new("Hanako", "Yamada", 14); let kyoko = Student::new("Kyoko", "Ito", 15); let ryosuke = Student::new("Ryosuke", "Hayashi", 17); let mut x = vec![&taro, &hanako, &kyoko, &ryosuke]; let expected = vec![&hanako, &kyoko, &taro, &ryosuke]; // sort_by 関数のテスト。 assert_eq!(sort_by(&mut x, &|a, b| a.age.cmp(&b.age)), Ok(())); assert_eq!(x, expected); } #[test] fn sort_students_by_name_ascending() { let taro = Student::new("Taro", "Yamada", 16); let hanako = Student::new("Hanako", "Yamada", 14); let kyoko = Student::new("Kyoko", "Ito", 15); let ryosuke = Student::new("Ryosuke", "Hayashi", 17); let mut x = vec![&taro, &hanako, &kyoko, &ryosuke]; let expected = vec![&ryosuke, &kyoko, &hanako, &taro]; assert_eq!( sort_by(&mut x, &|a, b| a .last_name .cmp(&b.last_name) .then_with(|| a.first_name.cmp(&b.first_name))), Ok(()) ); assert_eq!(x, expected); } #[test] fn sort_u32_large() { { let mut x = new_u32_vec(65536); assert_eq!(sort(&mut x, &Ascending), Ok(())); assert!(is_sorted(&x, &Ascending)) } { let mut x = new_u32_vec(65536); assert_eq!(sort(&mut x, &Decending), Ok(())); assert!(is_sorted(&x, &Decending)) } } }
extern crate time; extern crate rustc_serialize; use rustc_serialize::base64::{FromBase64, ToBase64, Config, CharacterSet, Newline}; fn main() { let t = time::now(); println!("{:?}", t.to_timespec()); let pt = t.to_timespec().sec as i32; println!("{:?}", pt); let mut ip: *const i32 = &pt; let bp: *const u8 = ip as *const _; let bs: &[u8] = unsafe { std::slice::from_raw_parts(bp, std::mem::size_of::<i32>()) }; println!("{:?}", bs); let c = Config { char_set: CharacterSet::Standard, newline: Newline::CRLF, pad: true, line_length: None, }; let encoded = bs.to_base64(c); println!("{:?}", encoded); let decoded = &encoded[..].from_base64().unwrap(); println!("{:?}", decoded); }
extern crate gstreamer as gst; use gst::prelude::*; fn main() { gst::init().unwrap(); let main_loop = glib::MainLoop::new(None, false); let input_pipeline = gst::Pipeline::new("file-pipeline"); let output_pipeline = gst::Pipeline::new("output-pipeline"); let uri = "file:///e:/test.mp4"; let uridecodebin = gst::ElementFactory::make("uridecodebin", None).unwrap(); uridecodebin.set_property("uri", &uri).unwrap(); let videoconvert = gst::ElementFactory::make("videoconvert", None).unwrap(); let videorate = gst::ElementFactory::make("videorate", None).unwrap(); let videoscale = gst::ElementFactory::make("videoscale", None).unwrap(); let proxy_sink = gst::ElementFactory::make("proxysink", None).unwrap(); let proxy_src = gst::ElementFactory::make("proxysrc", None).unwrap(); proxy_src.set_property("proxysink", &proxy_sink).unwrap(); let videosink = gst::ElementFactory::make("autovideosink", None).unwrap(); input_pipeline.add_many(&[&uridecodebin, &videoconvert, &videorate, &videoscale, &proxy_sink]).unwrap(); gst::Element::link_many(&[&videoconvert, &videorate, &videoscale, &proxy_sink]).unwrap(); output_pipeline.add_many(&[&proxy_src, &videosink]).unwrap(); gst::Element::link_many(&[&proxy_src, &videosink]).unwrap(); let videoconvert_weak = videoconvert.downgrade(); uridecodebin.connect_pad_added(move |_, src_pad| { let new_pad_caps = src_pad .get_current_caps() .expect("Failed to get caps of new pad."); let new_pad_struct = new_pad_caps .get_structure(0) .expect("Failed to get first structure of caps."); let new_pad_type = new_pad_struct.get_name(); if new_pad_type.starts_with("video/x-raw") { let videoconvert = match videoconvert_weak.upgrade() { Some(videoconvert) => videoconvert, None => return, }; let sink_pad = videoconvert .get_static_pad("sink") .expect("Failed to get static sink pad from videoconvert"); if sink_pad.is_linked() { println!("We are already linked. Ignoring."); return; } src_pad.link(&sink_pad).unwrap(); } }); output_pipeline.set_state(gst::State::Playing).unwrap(); input_pipeline.set_state(gst::State::Playing).unwrap(); let bus = input_pipeline.get_bus().unwrap(); let input_pipeline_weak = input_pipeline.downgrade(); let mut did_cue = false; bus.add_watch(move |_, msg| { use crate::gst::MessageView; match msg.view() { MessageView::StateChanged(state_changed) => { let input_pipeline = match input_pipeline_weak.upgrade() { Some(input_pipeline) => input_pipeline, None => return glib::Continue(true), }; if state_changed .get_src() .map(|s| s == input_pipeline) .unwrap_or(false) { println!( "Pipeline state changed from {:?} to {:?}", state_changed.get_old(), state_changed.get_current() ); let new_state = state_changed.get_current(); if (new_state == gst::State::Playing && did_cue == false) { println!("DO The Cue CUE!"); input_pipeline.seek_simple( gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT, 2 * 60 * gst::SECOND).expect("Failed to seek"); did_cue = true; } } } _ => { //println!("Message: {:?}", msg); }, }; glib::Continue(true) }); main_loop.run(); }
//! This module contains all the OpenGEX structures as specified. The module tries to stay as close //! to the OpenGEX structures as possible. //! //! Some of the documentation might be subjected to copyright by Eric Lengyel. For more detailed //! documentation, please go to http://opengex.org. use std::collections::HashMap; use std::default::Default; use std::sync::Arc; use vec_map::VecMap; /// The Material structure contains information about a material. Material structures are /// referenced by geometry nodes through `Arc<Material>` structures belonging to `GeometryNode` /// structures. pub struct Material { /// Whether the material is two-sided. pub two_sided: bool, /// An optional name. pub name: Option<Name>, /// Any number of colors. pub color: HashMap<String, Color>, /// Any number of parameters. pub param: ParamMap, /// Any number of textures. pub texture: HashMap<String, Texture>, } /// A Color structure must contain an RGB or RGBA color value. pub enum Color { /// An RGB color value. Rgb(f32, f32, f32), /// An RGBA color value. Rgba(f32, f32, f32, f32) } /// The Param structure contains just a float. While the OpenGEX specification defines a Param as a /// key-value pair, this is better implemented through a HashMap. See ParamMap. pub type Param = f32; /// This is a map of different Param structures, for convenience. pub type ParamMap = HashMap<String, Param>; /// The Name structure holds the name of a node, morph target, material, or animation clip. pub type Name = String; /// The Texture structure holds information about a single texture map, and how it is accessed with /// texture coordinates. pub struct Texture { /// The index of the texture coordinate set associated with the texture. pub texcoord: u32, /// A substructure holding the file name of the texture. pub file_name: String, /// Any number of transformations that are applied to the texture coordinates of a mesh when /// they are used to fetch from the texture map. pub transformations: Vec<Transformation>, /// Any number of animation tracks that are applied to the texture coordinate transformations. pub animation: Vec<Animation> } /// Helper enum to contain all different kinds of Transformations. pub enum Transformation { /// A Transform structure. Transform(Transform), /// A Translation structure. Translation(Translation), /// A Rotation structure. Rotation(Rotation), /// A Scale structure. Scale(Scale) } /// The Transform structure holds one or more 4 x 4 transformation matrices. In the cases that a /// Transform structure is contained inside any type of node structure, a Texture structure, or a /// Skin structure, it must contain a single matrix. In the case that a Transform structure is /// contained inside a Skeleton structure, is must contain an array of matrices with one entry for /// each bone referenced by the skeleton. /// /// When contained inside a node structure, a Transform structure can be the target of a track /// stored inside an Animation structure. pub struct Transform([f32; 16]); /// The Translation structure holds a translation transformation in one of several possible /// variants. /// /// There are different variants of this type of tranformation, one for each "kind". /// /// When contained inside a node structure, a Translation structure can be the target of a track /// stored inside an Animation structure. pub enum Translation { /// The translation occurs along only the X axis. X(f32), /// The translation occurs along only the Y axis. Y(f32), /// The translation occurs along only the Z axis. Z(f32), /// The translation occurs along all three coordinate axes. Xyz(f32, f32, f32) } /// The Rotation structure represents a rotation along one of several axes. /// /// There are different variants of this type of tranformation, one for each "kind". /// /// When contained inside a node structure, a Rotation structure can be the target of a track /// stored in an Animation structure. pub enum Rotation { /// The rotation occurs about the X axis. X(f32), /// The rotation occurs about the Y axis. Y(f32), /// The rotation occurs about the Z axis. Z(f32), /// The rotation occurs about an arbitrary axis. The first entry of this structure is the angle /// of rotation. The remaining three entries are respectively the X, Y and Z components of the /// axis of rotation. Axis(f32, f32, f32, f32), /// The rotation is given by a quaternion. Please refer to the official OpenGEX documentation /// for more information. Quaternion(f32, f32, f32, f32) } /// The Scale structure represents a scale transformation in one of several possible variants. /// /// There are different variants of this type of tranformation, one for each "kind". /// /// When contained inside a node structure, a Scale structure can be the target of a strack stored /// inside an Animation structure. pub enum Scale { /// The scaling occurs along only the X axis. X(f32), /// The scaling occurs along only the Y axis. Y(f32), /// The scaling occurs along only the Z axis. Z(f32), /// The scaling occurs along all three coordinate axes. Xyz(f32, f32, f32) } /// The Animation structure contains animation data for a single node in a scene. Each animation /// structure is directly contained inside a node structure or Texture structure. Each animation /// structure contains the data needed to modify its sibling Transformation structures or sibling /// MorphWeight structures over time. /// /// More detailed information can be found in the official OpenGEX specification. pub struct Animation { /// Specifies the animation clip index. pub clip: u32, /// Specifies when the animation begins. If the property is not specifies, the begin time for /// the animation is determined by the earliest time values present in the Track structures /// belonging to this Animation. pub begin: Option<f32>, /// Specifies when the animation ends. Like with the begin property, if the property is not /// specified, the end time for the animation is determined by the latest time values present /// in the Track structures belonging to this Animation. pub end: Option<f32>, /// One or more tracks that each hold animation keys for a single target. pub tracks: Vec<Track>, } /// The Track structure contains animation key data for a single Transformation or MorphWeight /// structure. pub struct Track { /// The target transformation or MorphWeight this track applies to. pub target: TrackTarget, /// The time curve associated with this track. pub time: Time, /// The value curve associated with this track. pub value: Value } /// Enum wrapping over all possible animation track targets. pub enum TrackTarget { /// A Transformation structure. See enum to see possibilities. Transformation(Arc<Transformation>), /// A MorphWeight structure. MorphWeight(Arc<MorphWeight>) } /// The Time structure contains key time data in an animation track. /// /// There are two different kinds of this structure; one for every curve kind. /// /// The variants in this enum contain vectors. One vector item represents on key time. pub enum Time { /// The times are interpolated linearly. Linear(Vec<f32>), /// The times are interpolated on a one-dimensional Bezier curve. /// /// The times in each tuple in the vector are the "value", "-control" and "+control" values of /// the Bezier curve respectively. Bezier(Vec<(f32, f32, f32)>) } /// The Value structure contains key value data in an animation track. /// /// There are two different kinds of this structure; one for every curve kind. /// /// The variants in this enum contain vectors. One vector item represents on key value. pub enum Value { /// The values are not interpolated, but remain constant until the next key time. Constant(Vec<f32>), /// The values are interpolated linearly. Linear(Vec<f32>), /// The values are interpolated on a one-dimensional Bezier curve. /// /// The values in each tuple in the vector are the "value", "-control" and "+control" values of /// the Bezier curve respectively. Bezier(Vec<(f32, f32, f32)>), /// The values are interpolated on a tension-continuity-bias (TCB) spline. /// /// The values in each tuple in the vector are the "value", "tension", "bias" and "continuity" /// values of the TCB spline respecitvely. The data contained in these last three values are /// always scalar. Tcb(Vec<(f32, f32, f32, f32)>) } /// A MorphWeight structure holds a single morph weight for a GeometryNode structure, that /// references a GeometryObject strucure containing vertex data for multiple morph targets. /// /// A MorphWeight structure can be the target of a track stored inside an Animation structure. pub struct MorphWeight { /// Specifies the morph target index to which this morph weight applies. If the GeometryObject /// structure contains no vertex data corresponding to this target index, then this structure /// should be ignored. Each MorphWeight structure belonging to any particular GeometryNode /// structure must have a unique target index among all morph weights belonging to that /// GeometryNode. pub target_index: u32, /// The weight this MorphWeight structure represents. pub weight: f32, } /// The Atten structure specifies an attenuation function for a light object. pub struct Atten { /// The kind of attenuation. pub kind: AttenuationKind, /// The type of curve defining the attenuation. pub curve: AttenuationCurve, /// Any parameters associated with this Atten structure. /// /// For the meaning of the parameters, please refer to the official OpenGEX documentation. /// There can exist application-defined parameters. pub params: ParamMap } /// A helper enum representing different kinds of attenuation functions. pub enum AttenuationKind { /// The input to the attenuation function is the radial distance from the LightObject the /// parent Atten structure is associated with. Distance, /// The input to the attenuation function is the angle formed between the negative z-axis and /// the direction to the point being illuminated in object space. /// /// The result of this function should be raised to the power value of a potential "power" /// paramter present in the parent Atten structure. Angle, /// The input ot the attenuation function is the cosine of the angle formed between the /// negative z-axis and the direction to the point being illuminated in objet space. /// /// The result of this function should be raised to the power value of a potential "power" /// paramter present in the parent Atten structure. CosAngle } /// A helper enum representing different kinds of curves for an attenuation function. /// /// For exact formulas, please refer to the offical OpenGEX documentation. pub enum AttenuationCurve { /// The attenuation is a linear function. Linear, /// The attenuation is given by a cubic-smooth-step function. Cubic, /// The attenuation is given by the inverse function. Inverse, /// The attenuation is given by the inverse square function. InverseSquare } /// Helper enum to represent all different types of Nodes. pub enum Nodes { /// A `Node`. Node(Node), /// A `BoneNode`. BoneNode(BoneNode), /// A `GeometryNode` GeometryNode(GeometryNode), /// A `CameraNode` CameraNode(CameraNode), /// A `LightNode` LightNode(LightNode) } /// Macro to do away with the redundancy of the different kinds of Node structures. The common Node /// properties are placed at the start of the generated structure. /// /// The common properties are: /// * `name`: An optional name of the node. /// * `transformations`: A vector of local transformations to be applied to the node. /// * `animations`: A vector of animations that can be applied to the node. /// * `children`: A vector of child nodes part of this node. macro_rules! node { ( $(#[$attr:meta])* pub struct $name:ident { $($(#[$doc:meta])* pub $prop:ident : $type_:ty),* } ) => ( $(#[$attr])* pub struct $name { /// The optional name for this node. This property is generic to all types of nodes. pub name: Option<Name>, /// Any local transformations to be applied to this node. This property is generic to /// all types of nodes. pub transformations: Vec<Transformation>, /// Any animations for this node. This property is generic to all types of nodes. pub animations: Vec<Animation>, /// Any sub-nodes of this node. This property is generic to all types of nodes. pub children: Vec<Nodes>, $($(#[$doc])* pub $prop : $type_),* } ) } node! { /// A Node structure represents a single generic node in a scene, with no associated object. pub struct Node {} } node! { /// A BoneNode structure represents a single bone in a scene. The collection of bone nodes /// forming a complete skeleton for a skinned mesh is referenced by a `BoneRefArray` structure /// contained inside a `Skeleton` structrue. pub struct BoneNode {} } node! { /// A GeometryNode structure represents a single geometry node in a scene. "] pub struct GeometryNode { /// Whether this geometry is visible. Overrides the visibility of the referenced /// `GeometryObject` structure. pub visibile: Option<bool>, /// Whether this geometry casts shadows. If unset, this `GeometryNode` inherits the /// visibility of the referenced `GeometryObject` structure. pub casts_shadows: Option<bool>, /// Whether the geomery is rendered with motion blur. If unset, this `GeometryNode` /// inherits the visibility of the referenced `GeometryObject` structure. pub motion_blur: Option<bool>, /// A reference to a `GeometryObject` structure containing all of the required mesh data /// and optional skinning data. pub geometry: Arc<GeometryObject>, /// A `HashMap` with references to materials associated with this geometry. Each material's /// index in the HashMap specifies to which part of a mesh the material is applied, by /// matching it with the `material` property of each `IndexArray` structure in the mesh. pub materials: VecMap<Arc<Material>>, /// If the `GeometryObject` referenced by this node contains vertex data for multiple morph /// targets, then the node may contain one or more `MorphWeight` structures that specify /// the blending weight for each target. Each `MorphWeight` structure may be the target of /// a Track structure in the animation belonging to the node. pub morph_weights: Vec<MorphWeight> } } node! { /// A `CameraNode` structure represents a single camera node in a scene. pub struct CameraNode { /// A reference to a `CameraObject` that contains the information neccesary to construct /// the properly configured camera. pub camera: Arc<CameraObject> } } node! { /// A `LightNode` structure represents a single camera node in a scene. "] pub struct LightNode { /// Whether this light is visible. Overrides the visibility of the referenced `LightObject` /// structure. pub visibile: Option<bool>, /// A reference to a `LightObject` that contains the information neccesary to construct the /// proper type of light. pub light: Arc<LightObject> } } /// The `GeometryObject` structure contains data for a geometry object. Multiple `GeometryNode` /// structures may reference a single `GeometryObject`. This allows a scene to contain multiple /// instances of the same geometry with different transforms and materials. /// /// The `colors` and `textures` properties are for application-specfic use. pub struct GeometryObject { /// Whether this geometry is visible. Can be overriden by any `GeometryNode` structure /// referencing this geometry. pub visible: bool, /// Whether this geometry casts shadows. Can be overriden by any `GeometryNode` structure /// referencing this geometry. pub casts_shadows: bool, /// Whether this geometry is rendered with motion blur. Can be overriden by any `GeometryNode` /// structure referencing this geometry. pub motion_blur: bool, /// A mesh for every level of detail. The map is indexed by the level of detail. pub meshes: VecMap<Mesh>, /// May contain a `Morph` structure for each morph target for which vertex data exists inside /// the `Mesh` structures in `meshes`. The key of the `HashMap` is their target index. pub morphs: VecMap<Morph> } /// A `CameraObject` structure contains data for a camera object. pub struct CameraObject { /// A map of parameters associated with this camera. /// /// The OpenGEX specification defined three parameters: "fov", "near" and "far". Any other /// parameters are application-specific. pub params: ParamMap, /// A map of colors associated with this camera. The OpenGEX specification does not define any /// kinds of colors. pub colors: HashMap<String, Color>, /// A map of textures associated with this camera. The OpenGEX specification does not define /// any kinds of textures. pub textures: HashMap<String, Texture> } /// The LightObject struture contains data for a light object. Multiple LightNode structures may /// reference a single LightObject. This allows a scene to contain multiple instances of the same /// light, with different transformations. pub struct LightObject { /// The type of light emitted by this LightObject. pub light_type: LightType, /// Whether this LightObject casts shadows. This can be overiden by the LightNode referencing /// this LightObject. pub casts_shadows: bool, /// The colors associated with this LightObject. /// /// The OpenGEX specification only references one type of color: "light". This is the main /// color of light emitted by the light souArce. This defaults to an RGB value of /// (1.0, 1.0, 1.0). /// /// There can be any other number of colors in this HashMap, for application-specific kinds. pub colors: HashMap<String, Color>, /// The parameters associated with this LightObject. /// /// The OpenGEX specification only references one type of parameter: "intensity". This is the /// intensity of the light emitted by the light souArce. This defaults to 0. /// /// There can be any other number of parameters in this HashMap, for application-specific /// kinds. pub params: ParamMap, /// The textures associated with this LightObject. /// /// The OpenGEX specification only references one type of texture: "projection". This is an /// optional texture projection of this LightObject. The texture map should be oriented so that /// the right direction is aligned to the object-space positive x-axis, and the up direction is /// aligned to the object-space positive y-axis. /// /// There can be any other number of textures in this HashMap, for application-specific kinds. pub textures: HashMap<String, Texture>, /// Any number of attenuation functions to be applied to the LightObject. The values produced /// by all of them are multiplied together to determine the intensity of the light reaching /// any particular point in space. pub attenuations: Atten } /// This is an helper-enum representing all different types of lights that a LightObject can emit. pub enum LightType { /// The light souArce is to be treated as if it were infinitely far away so its rays are /// parallel. In object space, the rays point in the direction of the negative z-axis. Infinite, /// The lght souArce is a point light that radiates in all directions. Point, /// The light source is a spot light that radiates from a single points byt in a limited range /// of directions In object space, the primary direction is the negative z-axis. Spot } /// The `Morph` structure holds information about a morph target belonging to a `GeometryObject` /// structure. pub struct Morph { /// The base morph target index for a relative morph target. pub base_target_index: Option<u32>, /// An optional name for this structure. pub name: Option<Name> } /// A `Mesh` structure cotains data for a single geometric mesh. Each mesh typically contains /// several arrays of per-vertex data, and one or more index arrays. /// /// A mesh may contain vertex data for multiple morph targets. The morph target to which the vertex /// array belongs is determined by the value op its `morph` property. pub struct Mesh { /// Specifies the type of geometric primitive used by the mesh. This must be the same for each /// level of detail. See the helper-enum `GeometricPrimitive` for more details about the /// different kinds of primitives. pub primitive: GeometricPrimitive // TODO: Finish this } /// Helper enum for the `Mesh` structure, representing different geometric primitives supported by /// OpenGEX. /// /// In the documentation, `n` refers to the number of indices if an `IndexArray` structure is /// present, and otherwise, the number of vertices in every `VertexArray` structure. Primitives are /// indexed by the letter `i`, starting at zero. pub enum GeometricPrimitive { /// The mesh is composed of a set of independent points. The number of points is `n`, and point /// `i` is given by vertex `i`. Points, /// The mesh is composed of a set of independent lines. The number of lines equals `n/2`, and /// line `i` is composed of vertices `2i` and /// `2i+1`. Lines, /// The mesh is composed of one or more line strips. The number of lines equals `n-1`, and line /// `i` is composed of vertices `i` and /// `i+1`. LineStrip, /// The mesh is composed of a set of independent triangles. The number of triangles equals /// `n/3`, and triangle `i` is composed of vertices `3i`, `3i+1` and `3i+1`. Triangles, /// The mesh is composed of one or more triangle strips. /// /// When `i` is even, the triangle is composed out of vertices `i`, `i+1` and `i+2`. When `i` /// is odd, the triangle is composed out of vertices `i`, `i+2` and `i+1`. TriangleStrip, /// The mesh is composed of a set of individual quads. The number of quads equals `n/4`, and /// quad `i` is composed of vertices `4i`, `4i+1`, `4i+2` and `4i+3`. Quads } impl Default for GeometricPrimitive { fn default() -> GeometricPrimitive { GeometricPrimitive::Triangles } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Security_Authorization_AppCapabilityAccess")] pub mod AppCapabilityAccess;
use crate::codegen::module_codegen::CodeGenModule; use crate::logger; use std::collections::HashMap; use std::process; use inkwell::context::Context; pub struct Master<'a> { context: &'a Context, logger: logger::logger::Logger<'a>, modules: HashMap<&'a str, CodeGenModule<'a>>, } impl<'a> Master<'a> { pub fn new(context: &'a Context) -> Master<'a> { Master { context, modules: HashMap::new(), logger: logger::logger::Logger::new(), } } pub fn add_file(&mut self, filename: &'a str, file_contents: &'a str) { let mut code_gen_mod = CodeGenModule::new( self.context.create_module(filename), filename, file_contents, ); self.logger .add_file(filename, code_gen_mod.typecheck.parser.lexer.file_contents); match code_gen_mod.generate() { Ok(_) => {} Err(errors) => { for error in errors { self.logger.error(error); } self.logger.raise(); process::exit(1); } }; self.modules.insert(filename, code_gen_mod); } }
// script_manager.rs // // Copyright (c) 2019, Univerisity of Minnesota // // Author: Bridger Herman (herma582@umn.edu) //! Script manager use std::collections::HashMap; use std::fmt; use crate::entity::EntityId; use crate::traits::Update; use wasm_bindgen::prelude::*; #[wasm_bindgen(module = "/assets/wre.js")] extern "C" { pub type WreScript; #[wasm_bindgen(constructor)] fn new() -> WreScript; #[wasm_bindgen(method)] fn updateWrapper(this: &WreScript); } unsafe impl Send for WreScript {} unsafe impl Sync for WreScript {} impl fmt::Debug for WreScript { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "WreScript") } } #[derive(Default)] pub struct ScriptManager { entity_scripts: HashMap<EntityId, WreScript>, } impl ScriptManager { pub fn add_script(&mut self, eid: EntityId, script: WreScript) { self.entity_scripts.insert(eid, script); } } impl Update for ScriptManager { fn update(&mut self) { for (_entity, script) in self.entity_scripts.iter_mut() { script.updateWrapper(); } } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::SYSCONFIG { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct DES_SYSCONFIG_SOFTRESETR { bits: bool, } impl DES_SYSCONFIG_SOFTRESETR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _DES_SYSCONFIG_SOFTRESETW<'a> { w: &'a mut W, } impl<'a> _DES_SYSCONFIG_SOFTRESETW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = "Possible values of the field `DES_SYSCONFIG_SIDLE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DES_SYSCONFIG_SIDLER { #[doc = "Force-idle mode"] DES_SYSCONFIG_SIDLE_FORCE, #[doc = r"Reserved"] _Reserved(u8), } impl DES_SYSCONFIG_SIDLER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { DES_SYSCONFIG_SIDLER::DES_SYSCONFIG_SIDLE_FORCE => 0, DES_SYSCONFIG_SIDLER::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> DES_SYSCONFIG_SIDLER { match value { 0 => DES_SYSCONFIG_SIDLER::DES_SYSCONFIG_SIDLE_FORCE, i => DES_SYSCONFIG_SIDLER::_Reserved(i), } } #[doc = "Checks if the value of the field is `DES_SYSCONFIG_SIDLE_FORCE`"] #[inline(always)] pub fn is_des_sysconfig_sidle_force(&self) -> bool { *self == DES_SYSCONFIG_SIDLER::DES_SYSCONFIG_SIDLE_FORCE } } #[doc = "Values that can be written to the field `DES_SYSCONFIG_SIDLE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DES_SYSCONFIG_SIDLEW { #[doc = "Force-idle mode"] DES_SYSCONFIG_SIDLE_FORCE, } impl DES_SYSCONFIG_SIDLEW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { DES_SYSCONFIG_SIDLEW::DES_SYSCONFIG_SIDLE_FORCE => 0, } } } #[doc = r"Proxy"] pub struct _DES_SYSCONFIG_SIDLEW<'a> { w: &'a mut W, } impl<'a> _DES_SYSCONFIG_SIDLEW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DES_SYSCONFIG_SIDLEW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Force-idle mode"] #[inline(always)] pub fn des_sysconfig_sidle_force(self) -> &'a mut W { self.variant(DES_SYSCONFIG_SIDLEW::DES_SYSCONFIG_SIDLE_FORCE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 2); self.w.bits |= ((value as u32) & 3) << 2; self.w } } #[doc = r"Value of the field"] pub struct DES_SYSCONFIG_DMA_REQ_DATA_IN_ENR { bits: bool, } impl DES_SYSCONFIG_DMA_REQ_DATA_IN_ENR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _DES_SYSCONFIG_DMA_REQ_DATA_IN_ENW<'a> { w: &'a mut W, } impl<'a> _DES_SYSCONFIG_DMA_REQ_DATA_IN_ENW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct DES_SYSCONFIG_DMA_REQ_DATA_OUT_ENR { bits: bool, } impl DES_SYSCONFIG_DMA_REQ_DATA_OUT_ENR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _DES_SYSCONFIG_DMA_REQ_DATA_OUT_ENW<'a> { w: &'a mut W, } impl<'a> _DES_SYSCONFIG_DMA_REQ_DATA_OUT_ENW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u32) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct DES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENR { bits: bool, } impl DES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _DES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENW<'a> { w: &'a mut W, } impl<'a> _DES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 1 - Soft reset"] #[inline(always)] pub fn des_sysconfig_softreset(&self) -> DES_SYSCONFIG_SOFTRESETR { let bits = ((self.bits >> 1) & 1) != 0; DES_SYSCONFIG_SOFTRESETR { bits } } #[doc = "Bits 2:3 - Sidle mode"] #[inline(always)] pub fn des_sysconfig_sidle(&self) -> DES_SYSCONFIG_SIDLER { DES_SYSCONFIG_SIDLER::_from(((self.bits >> 2) & 3) as u8) } #[doc = "Bit 5 - DMA Request Data In Enable"] #[inline(always)] pub fn des_sysconfig_dma_req_data_in_en(&self) -> DES_SYSCONFIG_DMA_REQ_DATA_IN_ENR { let bits = ((self.bits >> 5) & 1) != 0; DES_SYSCONFIG_DMA_REQ_DATA_IN_ENR { bits } } #[doc = "Bit 6 - DMA Request Data Out Enable"] #[inline(always)] pub fn des_sysconfig_dma_req_data_out_en(&self) -> DES_SYSCONFIG_DMA_REQ_DATA_OUT_ENR { let bits = ((self.bits >> 6) & 1) != 0; DES_SYSCONFIG_DMA_REQ_DATA_OUT_ENR { bits } } #[doc = "Bit 7 - DMA Request Context In Enable"] #[inline(always)] pub fn des_sysconfig_dma_req_context_in_en(&self) -> DES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENR { let bits = ((self.bits >> 7) & 1) != 0; DES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 1 - Soft reset"] #[inline(always)] pub fn des_sysconfig_softreset(&mut self) -> _DES_SYSCONFIG_SOFTRESETW { _DES_SYSCONFIG_SOFTRESETW { w: self } } #[doc = "Bits 2:3 - Sidle mode"] #[inline(always)] pub fn des_sysconfig_sidle(&mut self) -> _DES_SYSCONFIG_SIDLEW { _DES_SYSCONFIG_SIDLEW { w: self } } #[doc = "Bit 5 - DMA Request Data In Enable"] #[inline(always)] pub fn des_sysconfig_dma_req_data_in_en(&mut self) -> _DES_SYSCONFIG_DMA_REQ_DATA_IN_ENW { _DES_SYSCONFIG_DMA_REQ_DATA_IN_ENW { w: self } } #[doc = "Bit 6 - DMA Request Data Out Enable"] #[inline(always)] pub fn des_sysconfig_dma_req_data_out_en(&mut self) -> _DES_SYSCONFIG_DMA_REQ_DATA_OUT_ENW { _DES_SYSCONFIG_DMA_REQ_DATA_OUT_ENW { w: self } } #[doc = "Bit 7 - DMA Request Context In Enable"] #[inline(always)] pub fn des_sysconfig_dma_req_context_in_en(&mut self) -> _DES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENW { _DES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENW { w: self } } }
//! The following is derived from Rust's //! library/std/src/io/mod.rs at revision //! dca3f1b786efd27be3b325ed1e01e247aa589c3b. /// Enumeration of possible methods to seek within an I/O object. /// /// It is used by the [`Seek`] trait. /// /// [`Seek`]: std::io::Seek #[derive(Copy, PartialEq, Eq, Clone, Debug)] #[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] pub enum SeekFrom { /// Sets the offset to the provided number of bytes. #[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] Start(#[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] u64), /// Sets the offset to the size of this object plus the specified number of /// bytes. /// /// It is possible to seek beyond the end of an object, but it's an error /// to seek before byte 0. #[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] End(#[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] i64), /// Sets the offset to the current position plus the specified number of /// bytes. /// /// It is possible to seek beyond the end of an object, but it's an error /// to seek before byte 0. #[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] Current(#[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] i64), /// Sets the offset to the current position plus the specified number of bytes, /// plus the distance to the next byte which is not in a hole. /// /// If the offset is in a hole at the end of the file, the seek will produce /// an `NXIO` error. #[cfg(any(freebsdlike, target_os = "linux", target_os = "solaris"))] Data(i64), /// Sets the offset to the current position plus the specified number of bytes, /// plus the distance to the next byte which is in a hole. /// /// If there is no hole past the offset, it will be set to the end of the file /// i.e. there is an implicit hole at the end of any file. #[cfg(any(freebsdlike, target_os = "linux", target_os = "solaris"))] Hole(i64), }
use failure::*; #[derive(Debug, Fail)] pub enum TransactionError { #[fail(display = "Could not load the file: {:?}", 0)] LoadError(std::io::Error), #[fail(display = "Could not load the file: {:?}", 0)] ParseError(serde_json::Error), #[fail(display = "Could not load the file: {:?}", 0)] Error(&'static str), } impl From<std::io::Error> for TransactionError { fn from(e: std::io::Error) -> Self { TransactionError::LoadError(e) } } impl From<serde_json::Error> for TransactionError { fn from(e: serde_json::Error) -> Self { TransactionError::ParseError(e) } } impl From<&'static str> for TransactionError { fn from(e: &'static str) -> Self { TransactionError::Error(e) } }
fn somma(n1: i32, n2: i32){ println!("The sum is: {}", n1+n2); } fn main() { somma(3, 5); }
use crate::{error::ClientError, network::request_async, Result}; use isahc::config::RedirectPolicy; use isahc::prelude::*; use serde::Deserialize; const API_ENDPOINT: &str = "https://api.mmoui.com/v4/game/WOW/filedetails"; const ADDON_URL: &str = "https://www.wowinterface.com/downloads/info"; /// Return the wowi API endpoint. fn api_endpoint(ids: &str) -> String { format!("{}/{}.json", API_ENDPOINT, ids) } /// Returns the addon website url. pub fn addon_url(id: &str) -> String { format!("{}{}", ADDON_URL, id) } #[serde(rename_all = "camelCase")] #[derive(Clone, Debug, Deserialize)] /// Struct for applying wowi details to an `Addon`. pub struct WowIPackage { pub id: i64, pub title: String, pub version: String, pub download_uri: String, pub last_update: i64, pub author: String, pub description: String, } /// Returns changelog url for addon. pub fn changelog_url(id: String) -> String { format!("{}{}/#changelog", ADDON_URL, id) } /// Function to fetch a remote addon package which contains /// information about the addon on the repository. pub async fn fetch_remote_packages(ids: Vec<String>) -> Result<Vec<WowIPackage>> { let client = HttpClient::builder() .redirect_policy(RedirectPolicy::Follow) .max_connections_per_host(6) .build() .unwrap(); let url = api_endpoint(&ids.join(",")); let timeout = Some(30); let mut resp = request_async(&client, &url, vec![], timeout).await?; if resp.status().is_success() { let packages = resp.json(); Ok(packages?) } else { Err(ClientError::Custom(format!( "Couldn't fetch details for addon. Server returned: {}", resp.text()? ))) } }
use super::*; struct PlayerState { step_animation: f32, } impl PlayerState { pub fn new() -> Self { Self { step_animation: 0.0, } } pub fn update(&mut self, player: &Player, delta_time: f32) { self.step_animation += player.target_velocity.len() * delta_time; } } struct UiState { geng: Rc<Geng>, assets: Rc<Assets>, volume_slider: geng::ui::Slider, volume: f64, skin_tone: f64, skin_tone_slider: geng::ui::Slider, stick: f64, stick_slider: geng::ui::Slider, hat_color: f64, hat_color_slider: geng::ui::Slider, beard: usize, beard_slider: geng::ui::Slider, ear: usize, ear_slider: geng::ui::Slider, eye: usize, eye_slider: geng::ui::Slider, hat: usize, hat_slider: geng::ui::Slider, mouth: usize, mouth_slider: geng::ui::Slider, mustache: usize, mustache_slider: geng::ui::Slider, nose: usize, nose_slider: geng::ui::Slider, customize_character: bool, changing_name: bool, leaderboard: bool, } const SOUND_RANGE: f32 = 5.0; impl UiState { fn locked(&self) -> bool { self.changing_name || self.customize_character || self.leaderboard } fn new(geng: &Rc<Geng>, assets: &Rc<Assets>, player: &Player) -> Self { let mut ui_theme = geng::ui::Theme::default(geng); ui_theme.usable_color = Color::GRAY; ui_theme.text_color = Color::BLACK; ui_theme.hover_color = Color::BLUE; let ui_theme = Rc::new(ui_theme); Self { geng: geng.clone(), assets: assets.clone(), volume_slider: geng::ui::Slider::new(&ui_theme), volume: 0.5, skin_tone: player.skin_tone, skin_tone_slider: geng::ui::Slider::new(&ui_theme), stick: player.stick, stick_slider: geng::ui::Slider::new(&ui_theme), hat_color: player.hat_color, hat_color_slider: geng::ui::Slider::new(&ui_theme), beard: player.beard, beard_slider: geng::ui::Slider::new(&ui_theme), ear: player.ear, ear_slider: geng::ui::Slider::new(&ui_theme), eye: player.eye, eye_slider: geng::ui::Slider::new(&ui_theme), hat: player.hat, hat_slider: geng::ui::Slider::new(&ui_theme), mouth: player.mouth, mouth_slider: geng::ui::Slider::new(&ui_theme), mustache: player.mustache, mustache_slider: geng::ui::Slider::new(&ui_theme), nose: player.nose, nose_slider: geng::ui::Slider::new(&ui_theme), customize_character: false, changing_name: false, leaderboard: false, } } fn ui<'a>(&'a mut self, model: &'a Model, local: bool) -> impl geng::ui::Widget + 'a { use geng::ui; use geng::ui::*; let font: &Rc<geng::Font> = &self.assets.font; let volume = &mut self.volume; let mut stack = ui::stack![ui::row![ geng::ui::Text::new("volume", font, 30.0, Color::BLACK).padding_right(30.0), self.volume_slider .ui( *volume, 0.0..=1.0, Box::new(move |new_value| *volume = new_value) ) .fixed_size(vec2(100.0, 30.0)) ] .padding_right(50.0) .padding_bottom(50.0) .align(vec2(1.0, 0.0))]; if self.leaderboard { if local { stack.push(Box::new( geng::ui::stack![ geng::ui::ColorBox::new(&self.geng, Color::rgba(1.0, 1.0, 1.0, 0.7)), geng::ui::Text::new( "This is single player world, use the train to play with other people", font, 50.0, Color::BLACK ) .uniform_padding(30.0), ] .align(vec2(0.5, 0.5)), )); } else { let mut column = ui::column(vec![]); let mut players: Vec<_> = model .leaderboard .values() .map(|player| (player.money, &player.name)) .collect(); players.sort(); players.reverse(); column.push(Box::new( ui::row![ geng::ui::Text::new("Rank", font, 30.0, Color::BLACK) .align(vec2(1.0, 0.0)) .uniform_padding(10.0) .fixed_size(vec2(100.0, 50.0)), geng::ui::Text::new("Name", font, 30.0, Color::BLACK) .align(vec2(0.0, 0.0)) .uniform_padding(10.0) .fixed_size(vec2(400.0, 50.0)), geng::ui::Text::new("Score", font, 30.0, Color::BLACK) .align(vec2(0.0, 0.0)) .uniform_padding(10.0) .fixed_size(vec2(100.0, 50.0)) ] .padding_bottom(50.0), )); for (index, (score, player)) in players.into_iter().take(10).enumerate() { column.push(Box::new(ui::stack![ geng::ui::ColorBox::new( &self.geng, Color::rgba(1.0, 1.0, 1.0, if index % 2 == 0 { 0.9 } else { 0.0 }), ), ui::row![ geng::ui::Text::new((index + 1).to_string(), font, 30.0, Color::BLACK) .align(vec2(1.0, 0.0)) .uniform_padding(10.0) .fixed_size(vec2(60.0, 50.0)), geng::ui::Text::new(player, font, 30.0, Color::BLACK) .align(vec2(0.0, 0.0)) .uniform_padding(10.0) .fixed_size(vec2(400.0, 50.0)), geng::ui::Text::new(score.to_string(), font, 30.0, Color::BLACK) .align(vec2(0.0, 0.0)) .uniform_padding(10.0) .fixed_size(vec2(100.0, 50.0)) ], ])); } stack.push(Box::new( geng::ui::stack![ geng::ui::ColorBox::new(&self.geng, Color::rgba(1.0, 1.0, 1.0, 0.7)), column.uniform_padding(30.0), ] .align(vec2(0.5, 0.5)), )); } } if self.customize_character { let mut column = ui::column(vec![]); let skin_tone = &mut self.skin_tone; column.push(Box::new(ui::row![ geng::ui::Text::new("skin tone", font, 50.0, Color::BLACK).padding_right(24.0), self.skin_tone_slider .ui( *skin_tone, 0.0..=1.0, Box::new(move |new_value| *skin_tone = new_value) ) .fixed_size(vec2(300.0, 50.0)) ])); let stick = &mut self.stick; column.push(Box::new(ui::row![ geng::ui::Text::new("pickaxe color", font, 50.0, Color::BLACK).padding_right(24.0), self.stick_slider .ui( *stick, 0.0..=1.0, Box::new(move |new_value| *stick = new_value) ) .fixed_size(vec2(300.0, 50.0)) ])); let eye = &mut self.eye; column.push(Box::new(ui::row![ geng::ui::Text::new("eye", font, 50.0, Color::BLACK).padding_right(50.0), self.eye_slider .ui( *eye as f64, 0.0..=3.0, Box::new(move |new_value| *eye = new_value.round() as usize) ) .fixed_size(vec2(300.0, 50.0)) ])); let ear = &mut self.ear; column.push(Box::new(ui::row![ geng::ui::Text::new("ear", font, 50.0, Color::BLACK).padding_right(50.0), self.ear_slider .ui( *ear as f64, 0.0..=3.0, Box::new(move |new_value| *ear = new_value.round() as usize) ) .fixed_size(vec2(300.0, 50.0)) ])); let mouth = &mut self.mouth; column.push(Box::new(ui::row![ geng::ui::Text::new("mouth", font, 50.0, Color::BLACK).padding_right(50.0), self.mouth_slider .ui( *mouth as f64, 0.0..=3.0, Box::new(move |new_value| *mouth = new_value.round() as usize) ) .fixed_size(vec2(300.0, 50.0)) ])); let nose = &mut self.nose; column.push(Box::new(ui::row![ geng::ui::Text::new("nose", font, 50.0, Color::BLACK).padding_right(50.0), self.nose_slider .ui( *nose as f64, 0.0..=3.0, Box::new(move |new_value| *nose = new_value.round() as usize) ) .fixed_size(vec2(300.0, 50.0)) ])); let mustache = &mut self.mustache; column.push(Box::new(ui::row![ geng::ui::Text::new("mustache", font, 50.0, Color::BLACK).padding_right(50.0), self.mustache_slider .ui( *mustache as f64, 0.0..=4.0, Box::new(move |new_value| *mustache = new_value.round() as usize) ) .fixed_size(vec2(300.0, 50.0)) ])); let beard = &mut self.beard; column.push(Box::new(ui::row![ geng::ui::Text::new("beard", font, 50.0, Color::BLACK).padding_right(50.0), self.beard_slider .ui( *beard as f64, 0.0..=4.0, Box::new(move |new_value| *beard = new_value.round() as usize) ) .fixed_size(vec2(300.0, 50.0)) ])); let hat = &mut self.hat; column.push(Box::new(ui::row![ geng::ui::Text::new("hat", font, 50.0, Color::BLACK).padding_right(50.0), self.hat_slider .ui( *hat as f64, 0.0..=4.0, Box::new(move |new_value| *hat = new_value.round() as usize) ) .fixed_size(vec2(300.0, 50.0)) ])); let hat_color = &mut self.hat_color; column.push(Box::new(ui::row![ geng::ui::Text::new("hat color", font, 50.0, Color::BLACK).padding_right(24.0), self.hat_color_slider .ui( *hat_color, 0.0..=1.0, Box::new(move |new_value| *hat_color = new_value) ) .fixed_size(vec2(300.0, 50.0)) ])); stack.push(Box::new( geng::ui::stack![ geng::ui::ColorBox::new(&self.geng, Color::rgba(1.0, 1.0, 1.0, 0.7)), column.uniform_padding(50.0), ] .align(vec2(0.0, 1.0)), )); } stack } fn update_player(&self, player: &mut Player) { player.skin_tone = self.skin_tone; player.stick = self.stick; player.hat_color = self.hat_color; player.beard = self.beard; player.ear = self.ear; player.eye = self.eye; player.hat = self.hat; player.mouth = self.mouth; player.mustache = self.mustache; player.nose = self.nose; } } impl Default for PlayerState { fn default() -> Self { Self::new() } } const HELPS: &[&str] = &[ "Use WASD/Arrows to move around", "Use Left Mouse Button to swing your pickaxe", "Use E to pick up items", "Use Q to drop items", "Use Right Mouse Button to place a block", "Dig deeper and deeper and you'll get more and more valuable treasure", "By the way, music is bad on purpose", "But at least ther IS music, right?", ]; pub struct GameState { geng: Rc<Geng>, assets: Rc<Assets>, opt: Rc<Opt>, camera: Camera, renderer: Renderer, model: Model, player: Player, players: HashMap<Id, PlayerState>, connection: Connection, left_click: Option<Vec2<f32>>, transition: Option<geng::Transition>, to_send: Vec<ClientMessage>, noise: noise::OpenSimplex, framebuffer_size: Vec2<f32>, ui_state: UiState, ui_controller: geng::ui::Controller, current_help: usize, music: Option<geng::SoundEffect>, } impl Drop for GameState { fn drop(&mut self) { if let Connection::Remote(connection) = &mut self.connection { connection.send(ClientMessage::Event(Event::PlayerLeft(self.player.id))); } } } impl GameState { pub fn new( geng: &Rc<Geng>, assets: &Rc<Assets>, opt: &Rc<Opt>, player: Option<Player>, welcome: WelcomeMessage, connection: Connection, ) -> Self { let player = match player { Some(mut player) => { player.id = welcome.player_id; player } None => welcome.model.players[&welcome.player_id].clone(), }; let ui_state = UiState::new(geng, assets, &player); Self { geng: geng.clone(), assets: assets.clone(), opt: opt.clone(), camera: Camera::new(10.0), renderer: Renderer::new(geng), player, players: HashMap::new(), model: welcome.model, connection, left_click: None, transition: None, to_send: Vec::new(), noise: noise::OpenSimplex::new(), framebuffer_size: vec2(1.0, 1.0), ui_state, ui_controller: geng::ui::Controller::new(), current_help: HELPS.len(), music: None, } } fn draw_player_part( &self, framebuffer: &mut ugli::Framebuffer, player: &Player, texture: &ugli::Texture, position: Vec2<f32>, flip_x: bool, rotation: f32, scale: f32, color: Color<f32>, ) { self.renderer.draw( framebuffer, &self.camera, player.matrix() * Mat4::translate(vec3(-1.0, -1.0, 0.0) + position.extend(0.0)) * Mat4::scale_uniform(3.0) * Mat4::translate(vec3(0.5, 0.5, 0.0)) * Mat4::rotate_z(rotation) * Mat4::scale(vec3(if flip_x { -1.0 } else { 1.0 }, 1.0, 1.0) * scale) * Mat4::translate(vec3(-0.5, -0.5, 0.0)), texture, color, ); } fn draw_item(&self, framebuffer: &mut ugli::Framebuffer, item: &Item) { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(item.position.extend(0.0)) * Mat4::scale_uniform(Item::SIZE) * Mat4::translate(vec3(-0.5, 0.0, 0.0)), self.assets.item_texture(item.item_type), item.item_type.color(), ); } fn draw_player(&self, framebuffer: &mut ugli::Framebuffer, player: &Player) { let state = if let Some(state) = self.players.get(&player.id) { state } else { return; }; let leg_arg = state.step_animation * f32::PI * 2.0 * 5.0; let mut leg_amp = player.target_velocity.len().min(1.0) * 0.1; let mut leg_offset = 0.0; if !player.on_ground { leg_amp = 0.0; leg_offset = -0.1; } let mut pick_position = vec2(0.0, 0.0); let mut pick_rotation = f32::PI / 4.0; if let Some(swing) = player.swing.or( if self.ui_state.customize_character && self.player.id == player.id { Some(-1.0 / 8.0) } else { None }, ) { pick_rotation = swing * f32::PI * 2.0 + f32::PI; pick_position = Vec2::rotated(vec2(1.0, 0.0), pick_rotation); } self.draw_player_part( framebuffer, player, &self.assets.stick, pick_position, false, pick_rotation - f32::PI / 4.0, 1.0, hsv(player.stick as f32, 0.5, 0.7), ); self.draw_player_part( framebuffer, player, &self.assets.pick_head, pick_position, false, pick_rotation - f32::PI / 4.0, 1.0, Color::WHITE, ); self.draw_player_part( framebuffer, player, &self.assets.leg, vec2( 0.0, (leg_arg + f32::PI).sin().max(0.0) * leg_amp + leg_offset, ), true, 0.0, 1.0, Color::GRAY, ); let skin_color = hsv( 6.0 / 255.0, 80.0 / 255.0, (50.0 + (255.0 - 50.0) * player.skin_tone as f32) / 255.0, ); self.draw_player_part( framebuffer, player, &self.assets.body, vec2(0.0, 0.0), false, 0.0, 1.0, skin_color, ); self.draw_player_part( framebuffer, player, &self.assets.leg, vec2(0.0, leg_arg.sin().max(0.0) * leg_amp + leg_offset), false, 0.0, 1.0, Color::GRAY, ); if let Some(texture) = self.assets.eye.get(player.eye) { self.draw_player_part( framebuffer, player, texture, vec2(0.0, 0.0), false, 0.0, 1.0, Color::WHITE, ); } if let Some(texture) = self.assets.mouth.get(player.mouth) { self.draw_player_part( framebuffer, player, texture, vec2(0.0, 0.0), false, 0.0, 1.0, Color::WHITE, ); } if let Some(texture) = self.assets.beard.get(player.beard) { self.draw_player_part( framebuffer, player, texture, vec2(0.0, 0.0), false, 0.0, 1.0, Color::WHITE, ); } if let Some(texture) = self.assets.hat.get(player.hat) { self.draw_player_part( framebuffer, player, texture, vec2(0.0, 0.0), false, 0.0, 1.0, hsv(player.hat_color as f32, 0.5, 0.7), ); } if let Some(texture) = self.assets.ear.get(player.ear) { self.draw_player_part( framebuffer, player, texture, vec2(0.0, 0.0), false, 0.0, 1.0, skin_color, ); } if let Some(texture) = self.assets.mustache.get(player.mustache) { self.draw_player_part( framebuffer, player, texture, vec2(0.0, 0.0), false, 0.0, 1.0, Color::WHITE, ); } if let Some(texture) = self.assets.nose.get(player.nose) { self.draw_player_part( framebuffer, player, texture, vec2(0.0, 0.0), false, 0.0, 1.0, skin_color, ); } if let Some(item) = &player.item { self.draw_player_part( framebuffer, player, self.assets.item_texture(item.item_type), vec2(0.0, 1.0), false, 0.0, 0.3, item.item_type.color(), ) } let changing_name = self.ui_state.changing_name && player.id == self.player.id; if !player.name.is_empty() || changing_name { let mut text = player.name.clone(); if changing_name { text.push('_'); } let pos = self.camera.world_to_screen( framebuffer.size().map(|x| x as f32), player.position + vec2(player.size.x / 2.0, player.size.y * 2.0), ); let font = &self.assets.font; let size = framebuffer.size().y as f32 / self.camera.fov / 3.0; let text_width = font.measure(&text, size).width(); self.geng.draw_2d().quad( framebuffer, AABB::pos_size( pos - vec2(text_width / 2.0 + 5.0, 5.0), vec2(text_width + 10.0, size + 10.0), ), Color::rgba(1.0, 1.0, 1.0, 0.7), ); font.draw_aligned(framebuffer, &text, pos, 0.5, size, Color::BLACK); } } fn draw_tile( &self, framebuffer: &mut ugli::Framebuffer, position: Vec2<i32>, texture: &ugli::Texture, color: Color<f32>, ) { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(position.map(|x| x as f32).extend(0.0)), &texture, color, ); } fn draw_random_tile( &self, framebuffer: &mut ugli::Framebuffer, position: Vec2<i32>, textures: &[ugli::Texture], color: Color<f32>, noise_offset: f64, ) { use noise::NoiseFn; let noise = self .noise .get([position.x as f64 + noise_offset, position.y as f64]); let noise = (noise / 0.544 + 1.0) / 2.0; let index = clamp( (noise * textures.len() as f64) as i32, 0..=textures.len() as i32 - 1, ) as usize; self.draw_tile(framebuffer, position, &textures[index], color); } fn update_player(&mut self, delta_time: f32) { self.ui_state.update_player(&mut self.player); self.player.target_velocity = vec2(0.0, 0.0); if !self.ui_state.locked() { if self.geng.window().is_key_pressed(geng::Key::A) || self.geng.window().is_key_pressed(geng::Key::Left) { self.player.target_velocity.x -= 1.0; } if self.geng.window().is_key_pressed(geng::Key::D) || self.geng.window().is_key_pressed(geng::Key::Right) { self.player.target_velocity.x += 1.0; } if self.geng.window().is_key_pressed(geng::Key::W) || self.geng.window().is_key_pressed(geng::Key::Up) { self.player.target_velocity.y += 1.0; } if self.geng.window().is_key_pressed(geng::Key::S) || self.geng.window().is_key_pressed(geng::Key::Down) { self.player.target_velocity.y -= 1.0; } } self.player.update(&self.model.tiles, delta_time); if let Some(position) = self.left_click { let position = position.map(|x| x.floor() as i32); match self.player.swing { None => self.player.swing = Some(0.0), Some(swing) if swing > 1.0 => { if ((self.player.position + self.player.size / 2.0) - position.map(|x| x as f32 + 0.5)) .len() < Player::RANGE { self.to_send .push(ClientMessage::Event(Event::TileBroken(position))); } self.player.swing = Some(0.0); } _ => {} } } else { self.player.swing = None; } } fn draw_impl(&mut self, framebuffer: &mut ugli::Framebuffer) { self.framebuffer_size = framebuffer.size().map(|x| x as f32); if self.ui_state.locked() { self.camera.target_position = self.player.position; self.camera.target_fov = 3.0; } else { self.camera.target_position = self.player.position; self.camera.target_fov = 10.0; } ugli::clear(framebuffer, Some(Color::rgb(0.8, 0.8, 1.0)), None); self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(self.camera.center.x * 0.8 - 8.0, 0.0, 0.0)) * Mat4::scale(vec3(16.0, 8.0, 1.0)), &self.assets.background, Color::rgba(1.0, 1.0, 1.0, 0.5), ); const VIEW_RADIUS: i32 = 12; for shop in &self.model.shops { match shop.shop_type { ShopType::Sell { needs_coin, give_item, require_item, } => { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0)) * Mat4::scale_uniform(2.0), if needs_coin { &self.assets.combine_shop } else { &self.assets.sell_shop }, Color::WHITE, ); self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0) + vec3(0.5, 1.5, 0.0)) * Mat4::scale_uniform(0.5) * Mat4::translate(vec3(-0.5, -0.5, 0.0)), self.assets.item_texture(require_item), require_item.color(), ); let give_texture = match give_item { Some(item) => self.assets.item_texture(item), None => &self.assets.coin, }; if needs_coin { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0) + vec3(1.5, 1.5, 0.0)) * Mat4::scale_uniform(0.5) * Mat4::translate(vec3(-0.5, -0.5, 0.0)), &self.assets.coin, Color::WHITE, ); self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0) + vec3(1.5, 0.5, 0.0)) * Mat4::scale_uniform(0.5) * Mat4::translate(vec3(-0.5, -0.5, 0.0)), give_texture, Color::WHITE, ); } else { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0) + vec3(1.5, 1.5, 0.0)) * Mat4::scale_uniform(0.5) * Mat4::translate(vec3(-0.5, -0.5, 0.0)), give_texture, give_item.map(|item| item.color()).unwrap_or(Color::WHITE), ); } } ShopType::House => { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0)) * Mat4::scale_uniform(2.0), &self.assets.house, Color::WHITE, ); } ShopType::Train => { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0)) * Mat4::scale_uniform(2.0), &self.assets.train, Color::WHITE, ); } ShopType::Passport => { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0)) * Mat4::scale_uniform(2.0), &self.assets.passport, Color::WHITE, ); } ShopType::LeaderBoard => { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0)) * Mat4::scale_uniform(2.0), &self.assets.leaderboard, Color::WHITE, ); } ShopType::Info => { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(shop.position, 0.0, 0.0)) * Mat4::scale_uniform(2.0), &self.assets.info, Color::WHITE, ); } } } for x in self.player.position.x as i32 - VIEW_RADIUS ..=self.player.position.x as i32 + VIEW_RADIUS { self.draw_tile(framebuffer, vec2(x, 0), &self.assets.grass, Color::WHITE); } for x in self.player.position.x as i32 - VIEW_RADIUS ..=self.player.position.x as i32 + VIEW_RADIUS { for y in self.player.position.y as i32 - VIEW_RADIUS ..=self.player.position.y as i32 + VIEW_RADIUS { let position = vec2(x, y); let mut draw_background = true; let current_tile = self.model.tiles.get(&position); if let Some(tile) = current_tile { if !tile.transparent() { draw_background = false; } } if y < 0 && draw_background { self.draw_random_tile( framebuffer, position, if y == -1 { &self.assets.dirt } else { &self.assets.stone }, Color::GRAY, 100.0, ); } if let Some(tile) = current_tile { self.draw_random_tile( framebuffer, position, self.assets.tile_textures(*tile), if *tile == Tile::Block { Color::rgb(0.8, 0.8, 0.8) } else { Color::WHITE }, 0.0, ); } } } for x in self.player.position.x as i32 - VIEW_RADIUS ..=self.player.position.x as i32 + VIEW_RADIUS { for y in self.player.position.y as i32 - VIEW_RADIUS ..=self.player.position.y as i32 + VIEW_RADIUS { let position = vec2(x, y); let current_tile = self.model.tiles.get(&position); let right_tile = self.model.tiles.get(&(position + vec2(1, 0))); let top_tile = self.model.tiles.get(&(position + vec2(0, 1))); let current_need_border = current_tile.map(|tile| tile.need_border()).unwrap_or(false); let right_need_border = right_tile.map(|tile| tile.need_border()).unwrap_or(false); let top_need_border = top_tile.map(|tile| tile.need_border()).unwrap_or(false); if current_tile != right_tile && (current_need_border || right_need_border) { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3(position.x as f32 + 0.5, position.y as f32, 0.0)), &self.assets.border, Color::BLACK, ); } if current_tile != top_tile && (current_need_border || top_need_border) { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3( position.x as f32 + 1.0, position.y as f32 + 0.5, 0.0, )) * Mat4::rotate_z(f32::PI / 2.0), &self.assets.border, Color::BLACK, ); } } } { let position = self .camera .screen_to_world( self.framebuffer_size, self.geng.window().mouse_pos().map(|x| x as f32), ) .map(|x| x.floor() as i32); if ((self.player.position + self.player.size / 2.0) - position.map(|x| x as f32 + 0.5)) .len() < Player::RANGE { if self.model.tiles.get(&position).is_some() { self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3( position.x as f32 + 0.5, position.y as f32 + 0.5, 0.0, )) * Mat4::rotate_z(f32::PI / 4.0) * Mat4::translate(vec3(-0.5, -0.5, 0.0)), &self.assets.border, Color::rgba(0.0, 0.0, 0.0, 0.5), ); self.renderer.draw( framebuffer, &self.camera, Mat4::translate(vec3( position.x as f32 + 0.5, position.y as f32 + 0.5, 0.0, )) * Mat4::rotate_z(-f32::PI / 4.0) * Mat4::translate(vec3(-0.5, -0.5, 0.0)), &self.assets.border, Color::rgba(0.0, 0.0, 0.0, 0.5), ); } } } if let Some(item) = &self.player.item { let position = self .camera .screen_to_world( self.framebuffer_size, self.geng.window().mouse_pos().map(|x| x as f32), ) .map(|x| x.floor() as i32); if !self.model.tiles.contains_key(&position) { if let Some(tile) = item.item_type.placed() { if ((self.player.position + self.player.size / 2.0) - position.map(|x| x as f32 + 0.5)) .len() < Player::RANGE { self.draw_random_tile( framebuffer, position, self.assets.tile_textures(tile), Color::rgba(1.0, 1.0, 1.0, 0.5), 0.0, ); } } } } for item in self.model.items.values() { let delta_pos = item.position - self.player.position; let distance = delta_pos.x.abs().max(delta_pos.y.abs()); if distance < VIEW_RADIUS as f32 { self.draw_item(framebuffer, item); } } self.draw_player(framebuffer, &self.player); for player in self.model.players.values() { if player.id == self.player.id { continue; } self.draw_player(framebuffer, player); } if self .geng .window() .is_button_pressed(geng::MouseButton::Left) && !self.ui_state.locked() { self.left_click = Some(self.camera.screen_to_world( framebuffer.size().map(|x| x as f32), self.geng.window().mouse_pos().map(|x| x as f32), )); } else { self.left_click = None; } let font = &self.assets.font; let text = self.player.money.to_string(); self.geng.draw_2d().quad( framebuffer, AABB::pos_size( vec2(100.0, 60.0), vec2(font.measure(&text, 100.0).width() + 60.0, 80.0), ), Color::rgba(1.0, 1.0, 1.0, 0.7), ); self.geng.draw_2d().textured_quad( framebuffer, AABB::pos_size(vec2(50.0, 50.0), vec2(100.0, 100.0)), &self.assets.coin, Color::WHITE, ); font.draw(framebuffer, &text, vec2(150.0, 50.0), 100.0, Color::BLACK); if !self.ui_state.locked() { let shop = self.model.shops.iter().find(|shop| { AABB::pos_size(vec2(shop.position, 0.0) - self.player.size, vec2(2.0, 2.0)) .contains(self.player.position) }); if let Some(shop) = shop { self.draw_text( framebuffer, vec2(shop.position + 1.0, 3.0), 40.0, shop.help(), ); if matches!(shop.shop_type, ShopType::Info) { if let Some(text) = HELPS.get(self.current_help) { self.draw_text(framebuffer, vec2(1.0 + shop.position, 2.5), 30.0, text); } } } } } fn draw_text( &self, framebuffer: &mut ugli::Framebuffer, position: Vec2<f32>, size: f32, text: &str, ) { let font = &self.assets.font; let text_width = font.measure(text, size).width(); let position = self .camera .world_to_screen(framebuffer.size().map(|x| x as f32), position); self.geng.draw_2d().quad( framebuffer, AABB::pos_size( position - vec2(text_width / 2.0 + 5.0, 5.0), vec2(text_width + 10.0, size + 10.0), ), Color::rgba(1.0, 1.0, 1.0, 0.7), ); font.draw_aligned(framebuffer, text, position, 0.5, size, Color::BLACK); } } impl geng::State for GameState { fn draw(&mut self, framebuffer: &mut ugli::Framebuffer) { self.draw_impl(framebuffer); self.ui_controller.draw( &mut self.ui_state.ui(&self.model, self.connection.is_local()), framebuffer, ); } fn update(&mut self, delta_time: f64) { if let Some(music) = &mut self.music { music.set_volume(self.ui_state.volume * 0.3); } self.camera.update(delta_time as f32); self.ui_controller.update( &mut self.ui_state.ui(&self.model, self.connection.is_local()), delta_time, ); let mut messages = Vec::new(); match &mut self.connection { Connection::Remote(connection) => messages.extend(connection.new_messages()), Connection::Local { next_tick, model } => { *next_tick -= delta_time; while *next_tick <= 0.0 { messages.push(ServerMessage::Update(model.tick())); *next_tick += 1.0 / model.ticks_per_second; } } } let mut messages_to_send = mem::replace(&mut self.to_send, Vec::new()); if !messages.is_empty() { messages_to_send.push(ClientMessage::Event(Event::PlayerUpdated( self.player.clone(), ))); } for message in messages_to_send { match &mut self.connection { Connection::Remote(connection) => connection.send(message), Connection::Local { next_tick: _, model, } => { messages.push(ServerMessage::Update( model.handle_message(self.player.id, message), )); } } } for message in messages { match message { ServerMessage::Update(events) => { for event in events { match event { Event::TilePlaced(position, ..) => { if (position.map(|x| x as f32) - self.player.position).len() < SOUND_RANGE { let mut effect = self.assets.place.effect(); effect.set_volume(self.ui_state.volume); effect.play(); } } Event::TileBroken(position, ..) if self.model.tiles.contains_key(&position) => { if (position.map(|x| x as f32) - self.player.position).len() < SOUND_RANGE { let mut effect = self.assets.dig.effect(); effect.set_volume(self.ui_state.volume); effect.play(); } } _ => {} } self.model.handle(event); } } _ => unreachable!(), } } let delta_time = delta_time as f32; self.update_player(delta_time); for player in self.model.players.values_mut() { player.update(&self.model.tiles, delta_time); } for player in self.model.players.values() { if player.id == self.player.id { continue; } self.players .entry(player.id) .or_default() .update(player, delta_time); } self.players .entry(self.player.id) .or_default() .update(&self.player, delta_time); for item in self.model.items.values_mut() { let new_pos = vec2(item.position.x, item.position.y - delta_time * 5.0); if self .model .tiles .get(&new_pos.map(|x| x.floor() as i32)) .is_none() { item.position = new_pos; } } } fn handle_event(&mut self, event: geng::Event) { self.ui_controller.handle_event( &mut self.ui_state.ui(&self.model, self.connection.is_local()), event.clone(), ); if let geng::Event::KeyDown { key, .. } = event { let c = format!("{:?}", key); if c.len() == 1 && self.ui_state.changing_name { if self.player.name.len() < 20 { self.player.name.push_str(&c); } return; } if key == geng::Key::Backspace && self.ui_state.changing_name { self.player.name.pop(); } } match event { geng::Event::KeyDown { key, .. } => match key { geng::Key::Escape | geng::Key::Enter | geng::Key::E if self.ui_state.locked() => { self.ui_state.customize_character = false; self.ui_state.changing_name = false; self.ui_state.leaderboard = false; } geng::Key::E => { let shop = self.model.shops.iter().find(|shop| { AABB::pos_size(vec2(shop.position, 0.0) - self.player.size, vec2(2.0, 2.0)) .contains(self.player.position) }); if let Some(shop) = shop { match shop.shop_type { ShopType::Train => { self.transition = Some(match self.connection { Connection::Local { .. } => { geng::Transition::Push(Box::new(ConnectingState::new( &self.geng, &self.assets, &self.opt, Some(self.player.clone()), ))) } Connection::Remote(_) => geng::Transition::Pop, }); } ShopType::House => { self.ui_state.customize_character = true; } ShopType::Passport => { self.ui_state.changing_name = true; } ShopType::LeaderBoard => { self.ui_state.leaderboard = true; } ShopType::Info => { self.current_help += 1; if self.current_help >= HELPS.len() { self.current_help = 0; } } _ => {} } } if let Some(item) = self.player.item.clone() { if let Some(&Shop { shop_type: ShopType::Sell { require_item, give_item, needs_coin, }, .. }) = shop { if require_item == item.item_type && (!needs_coin || self.player.money > 0) { if needs_coin { self.player.money -= 1; } let item_id = item.id; self.player.item = None; if let Some(item_type) = give_item { let mut effect = self.assets.change.effect(); effect.set_volume(self.ui_state.volume); effect.play(); self.player.item = Some(Item { id: item_id, position: self.player.position, item_type, value: 0, }) } else { let mut effect = self.assets.money.effect(); effect.set_volume(self.ui_state.volume); effect.play(); self.player.money += item.value; } } } } else { let closest_item = self.model.items.values().min_by_key(|item| { r32((item.position - self.player.position).len()) }); if let Some(item) = closest_item { if (item.position - self.player.position).len() < Player::RANGE { self.player.item = Some(item.clone()); self.to_send .push(ClientMessage::Event(Event::ItemRemoved(item.id))); } } } } geng::Key::Q => { if let Some(mut item) = self.player.item.take() { item.position = self.player.position; self.to_send .push(ClientMessage::Event(Event::ItemAdded(item))); } } _ => {} }, geng::Event::MouseDown { button, position, .. } => { if self.music.is_none() && self.connection.is_local() { self.music = Some({ let mut music = self.assets.music.play(); music.set_volume(0.2); music }); } let position = self .camera .screen_to_world(self.framebuffer_size, position.map(|x| x as f32)); let position = position.map(|x| x.floor() as i32); match button { geng::MouseButton::Right => { if let Some(item) = &self.player.item { if !self.model.tiles.contains_key(&position) { if let Some(tile) = item.item_type.placed() { if ((self.player.position + self.player.size / 2.0) - position.map(|x| x as f32 + 0.5)) .len() < Player::RANGE { self.to_send.push(ClientMessage::Event(Event::TilePlaced( position, tile, ))); self.player.item = None; } } } } } _ => {} } } _ => {} } } fn transition(&mut self) -> Option<geng::Transition> { self.transition.take() } }
#![recursion_limit = "512"] mod app; mod components; mod utils; use prc::hash40::{set_custom_labels, Hash40}; use wasm_bindgen::prelude::*; // This is the entry point for the web app #[wasm_bindgen] pub fn run_app() -> Result<(), JsValue> { utils::set_panic_hook(); yew::start_app::<app::App>(); Ok(()) } #[wasm_bindgen] pub fn load_labels(text: String) { let iterator = text.lines().filter_map(|line| { let mut split = line.split(','); let hash_opt = split.next(); let label_opt = split.next(); if let Some(hash_str) = hash_opt { if let Some(label) = label_opt { if let Ok(hash) = Hash40::from_hex_str(hash_str) { return Some((hash, String::from(label))); } } } None }); set_custom_labels(iterator); }
use proconio::input; use std::cmp::Reverse; use std::collections::HashSet; fn main() { input! { n: usize, st: [(String, u32); n], }; let mut ti = Vec::new(); // original let mut seen = HashSet::new(); for (i, (s, t)) in st.iter().enumerate() { if seen.contains(s) { continue; } seen.insert(s); ti.push((*t, i)); } ti.sort_by_key(|&(t, i)| (Reverse(t), i)); assert!(ti.len() >= 1); let (t, ans) = ti[0]; eprintln!("t = {}", t); println!("{}", ans + 1); }
use serde_json::{Value,Result}; use serde::{Deserialize,Serialize}; ///定义输入keystore文件格式,用于转换json格式文件 #[derive(Serialize, Deserialize)] struct KeyStore{ version:u8, id:String, address:String, crypto:Crypto, } #[derive(Serialize,Debug,Deserialize)] struct Crypto{ ciphertext:String, cipher:String, cipherparams:CipherParams, kdf:String, kdfparams:KdfParams, mac:String, } #[derive(Serialize,Debug,Deserialize)] struct CipherParams{ iv:String, } #[derive(Serialize,Debug,Deserialize)] struct KdfParams{ dklen:u8, salt:String, n:u32, r:u16, p:u16, } pub fn serde_json_test(){ let keystore = r#"{ "version": 3, "id": "80d7b778-e617-4b35-bb09-f4b224984ed6", "address": "d280b60c38bc8db9d309fa5a540ffec499f0a3e8", "crypto": { "ciphertext": "58ac20c29dd3029f4d374839508ba83fc84628ae9c3f7e4cc36b05e892bf150d", "cipherparams": { "iv": "9ab7a5f9bcc9df7d796b5022023e2d14" }, "cipher": "aes-128-ctr", "kdf": "scrypt", "kdfparams": { "dklen": 32, "salt": "63a364b8a64928843708b5e9665a79fa00890002b32833b3a9ff99eec78dbf81", "n": 262144, "r": 8, "p": 1 }, "mac": "3a38f91234b52dd95d8438172bca4b7ac1f32e6425387be4296c08d8bddb2098" } } "#; let store :KeyStore= serde_json::from_str(keystore).unwrap(); println!("{},{}",store.address,store.version); println!("{:?}",store.crypto); }
#[derive(Copy, Clone, PartialEq)] pub enum TokenType { Illegal, Eof, Comment, Quasiquote, Symbol, Keyword, Number, Float, String, RParen, LParen, Quote, Unquote, At, Mark, } impl ::std::fmt::Display for TokenType { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!( f, "{}", match self { TokenType::Illegal => "Illegal", TokenType::Eof => "Eof", TokenType::Comment => "Comment", TokenType::Quasiquote => "Quasiquote", TokenType::Symbol => "Symbol", TokenType::Keyword => "Keyword", TokenType::Number => "Number", TokenType::Float => "Float", TokenType::String => "String", TokenType::RParen => "RParen", TokenType::LParen => "LParen", TokenType::Quote => "Quote", TokenType::Unquote => "Unquote", TokenType::At => "At", TokenType::Mark => "Mark", } ) } } impl ::std::fmt::Debug for TokenType { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{}", self) } } #[derive(Clone, Debug)] pub struct Token { pub ttype: TokenType, pub literal: String, pub line: u32, pub col: u32, pub file: String, } impl Token { pub fn with_literal(t: TokenType, lit: String, line: u32, col: u32, file: &str) -> Self { Token { ttype: t, literal: lit, line, col, file: file.to_owned(), } } pub fn simple(t: TokenType, line: u32, col: u32, file: &str) -> Self { Self::with_literal(t, "".to_string(), line, col, file) } }
use crate::{alphavantage::AlphaVantage, buy::Backtest, config::Config, mysql_db::{Database}, stockplotter::StockPlotter}; pub struct StockRS { pub alphavantage: AlphaVantage, pub database: Database, pub stockplotter: StockPlotter, pub stocks: Vec<String>, pub backtest: Backtest, } impl StockRS { pub fn from_config(config: &Config) -> Self { let alphavantage = AlphaVantage::with_key(&config.key); let database = Database::from_config(config); let stockplotter = StockPlotter::from_config(config); let backtest = Backtest::from_config(config); StockRS { alphavantage, database, stockplotter, stocks: config.stocks.clone(), backtest, } } pub fn update_db(&mut self) { let stocks = &self.stocks; for i in stocks { self.database.update(&i, &self.alphavantage); } } pub fn plot(&mut self) { for i in &self.stocks { self.stockplotter.plot_timeseries(i, &mut self.database); } } pub fn backtest(&mut self) { let stocks = &self.stocks; for s in stocks { self.backtest.full_test(&mut self.database, s, self.stockplotter.start_date, self.stockplotter.end_date); } } }
use hyper_tls::HttpsConnector; use hyper::Client; use serde::{Serialize, Deserialize}; use bytes::buf::ext::BufExt; #[derive(Serialize, Deserialize, Debug)] struct Echo { args: Args, headers: Headers, url: String } #[derive(Serialize, Deserialize, Debug)] struct Args { foo1: String, foo2: String, } #[derive(Serialize, Deserialize, Debug)] struct Headers { #[serde(rename = "x-forwarded-proto")] x_forwarded_proto: Option<String>, host: Option<String>, accept: Option<String>, #[serde(rename = "accept-encoding")] accept_encoding: Option<String>, #[serde(rename = "cache-control")] cache_control: Option<String>, #[serde(rename = "postman-token")] postman_token: Option<String>, #[serde(rename = "user-agent")] user_agent: Option<String>, #[serde(rename = "x-forwarded-port")] x_forwarded_port: Option<String>, } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let https = HttpsConnector::new(); let client = Client::builder().build::<_, hyper::Body>(https); let get_echo = client.get("https://postman-echo.com/get?foo1=bar1&foo2=bar2".parse()?).await?; println!("{:?}", get_echo.status()); println!("{:?}", get_echo.body()); let echo_body = hyper::body::aggregate(get_echo).await?; let body_output: Echo = serde_json::from_reader(echo_body.reader())?; println!("{:?}", body_output); Ok(()) }
#![doc = "Peripheral access API for TM4C129X microcontrollers (generated using svd2rust v0.17.0)\n\nYou can find an overview of the API [here].\n\n[here]: https://docs.rs/svd2rust/0.17.0/svd2rust/#peripheral-api"] #![deny(const_err)] #![deny(dead_code)] #![deny(improper_ctypes)] #![deny(legacy_directory_ownership)] #![deny(missing_docs)] #![deny(no_mangle_generic_items)] #![deny(non_shorthand_field_patterns)] #![deny(overflowing_literals)] #![deny(path_statements)] #![deny(patterns_in_fns_without_body)] #![deny(plugin_as_library)] #![deny(private_in_public)] #![deny(safe_extern_statics)] #![deny(unconditional_recursion)] #![deny(unions_with_drop_fields)] #![deny(unused_allocation)] #![deny(unused_comparisons)] #![deny(unused_parens)] #![deny(while_true)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![no_std] extern crate cortex_m; #[cfg(feature = "rt")] extern crate cortex_m_rt; extern crate vcell; use core::marker::PhantomData; use core::ops::Deref; #[doc = r"Number available in the NVIC for configuring priority"] pub const NVIC_PRIO_BITS: u8 = 3; #[cfg(feature = "rt")] extern "C" { fn GPIOA(); fn GPIOB(); fn GPIOC(); fn GPIOD(); fn GPIOE(); fn UART0(); fn UART1(); fn SSI0(); fn I2C0(); fn PWM0_FAULT(); fn PWM0_0(); fn PWM0_1(); fn PWM0_2(); fn QEI0(); fn ADC0SS0(); fn ADC0SS1(); fn ADC0SS2(); fn ADC0SS3(); fn WATCHDOG(); fn TIMER0A(); fn TIMER0B(); fn TIMER1A(); fn TIMER1B(); fn TIMER2A(); fn TIMER2B(); fn COMP0(); fn COMP1(); fn COMP2(); fn SYSCTL(); fn FLASH(); fn GPIOF(); fn GPIOG(); fn GPIOH(); fn UART2(); fn SSI1(); fn TIMER3A(); fn TIMER3B(); fn I2C1(); fn CAN0(); fn CAN1(); fn EMAC0(); fn HIBERNATE(); fn USB0(); fn PWM0_3(); fn UDMA(); fn UDMAERR(); fn ADC1SS0(); fn ADC1SS1(); fn ADC1SS2(); fn ADC1SS3(); fn EPI0(); fn GPIOJ(); fn GPIOK(); fn GPIOL(); fn SSI2(); fn SSI3(); fn UART3(); fn UART4(); fn UART5(); fn UART6(); fn UART7(); fn I2C2(); fn I2C3(); fn TIMER4A(); fn TIMER4B(); fn TIMER5A(); fn TIMER5B(); fn SYSEXC(); fn I2C4(); fn I2C5(); fn GPIOM(); fn GPION(); fn TAMPER0(); fn GPIOP0(); fn GPIOP1(); fn GPIOP2(); fn GPIOP3(); fn GPIOP4(); fn GPIOP5(); fn GPIOP6(); fn GPIOP7(); fn GPIOQ0(); fn GPIOQ1(); fn GPIOQ2(); fn GPIOQ3(); fn GPIOQ4(); fn GPIOQ5(); fn GPIOQ6(); fn GPIOQ7(); fn GPIOR(); fn GPIOS(); fn SHA0(); fn AES0(); fn DES0(); fn LCD0(); fn TIMER6A(); fn TIMER6B(); fn TIMER7A(); fn TIMER7B(); fn I2C6(); fn I2C7(); fn ONEWIRE0(); fn I2C8(); fn I2C9(); fn GPIOT(); } #[doc(hidden)] pub union Vector { _handler: unsafe extern "C" fn(), _reserved: u32, } #[cfg(feature = "rt")] #[doc(hidden)] #[link_section = ".vector_table.interrupts"] #[no_mangle] pub static __INTERRUPTS: [Vector; 112] = [ Vector { _handler: GPIOA }, Vector { _handler: GPIOB }, Vector { _handler: GPIOC }, Vector { _handler: GPIOD }, Vector { _handler: GPIOE }, Vector { _handler: UART0 }, Vector { _handler: UART1 }, Vector { _handler: SSI0 }, Vector { _handler: I2C0 }, Vector { _handler: PWM0_FAULT }, Vector { _handler: PWM0_0 }, Vector { _handler: PWM0_1 }, Vector { _handler: PWM0_2 }, Vector { _handler: QEI0 }, Vector { _handler: ADC0SS0 }, Vector { _handler: ADC0SS1 }, Vector { _handler: ADC0SS2 }, Vector { _handler: ADC0SS3 }, Vector { _handler: WATCHDOG }, Vector { _handler: TIMER0A }, Vector { _handler: TIMER0B }, Vector { _handler: TIMER1A }, Vector { _handler: TIMER1B }, Vector { _handler: TIMER2A }, Vector { _handler: TIMER2B }, Vector { _handler: COMP0 }, Vector { _handler: COMP1 }, Vector { _handler: COMP2 }, Vector { _handler: SYSCTL }, Vector { _handler: FLASH }, Vector { _handler: GPIOF }, Vector { _handler: GPIOG }, Vector { _handler: GPIOH }, Vector { _handler: UART2 }, Vector { _handler: SSI1 }, Vector { _handler: TIMER3A }, Vector { _handler: TIMER3B }, Vector { _handler: I2C1 }, Vector { _handler: CAN0 }, Vector { _handler: CAN1 }, Vector { _handler: EMAC0 }, Vector { _handler: HIBERNATE }, Vector { _handler: USB0 }, Vector { _handler: PWM0_3 }, Vector { _handler: UDMA }, Vector { _handler: UDMAERR }, Vector { _handler: ADC1SS0 }, Vector { _handler: ADC1SS1 }, Vector { _handler: ADC1SS2 }, Vector { _handler: ADC1SS3 }, Vector { _handler: EPI0 }, Vector { _handler: GPIOJ }, Vector { _handler: GPIOK }, Vector { _handler: GPIOL }, Vector { _handler: SSI2 }, Vector { _handler: SSI3 }, Vector { _handler: UART3 }, Vector { _handler: UART4 }, Vector { _handler: UART5 }, Vector { _handler: UART6 }, Vector { _handler: UART7 }, Vector { _handler: I2C2 }, Vector { _handler: I2C3 }, Vector { _handler: TIMER4A }, Vector { _handler: TIMER4B }, Vector { _handler: TIMER5A }, Vector { _handler: TIMER5B }, Vector { _handler: SYSEXC }, Vector { _reserved: 0 }, Vector { _reserved: 0 }, Vector { _handler: I2C4 }, Vector { _handler: I2C5 }, Vector { _handler: GPIOM }, Vector { _handler: GPION }, Vector { _reserved: 0 }, Vector { _handler: TAMPER0 }, Vector { _handler: GPIOP0 }, Vector { _handler: GPIOP1 }, Vector { _handler: GPIOP2 }, Vector { _handler: GPIOP3 }, Vector { _handler: GPIOP4 }, Vector { _handler: GPIOP5 }, Vector { _handler: GPIOP6 }, Vector { _handler: GPIOP7 }, Vector { _handler: GPIOQ0 }, Vector { _handler: GPIOQ1 }, Vector { _handler: GPIOQ2 }, Vector { _handler: GPIOQ3 }, Vector { _handler: GPIOQ4 }, Vector { _handler: GPIOQ5 }, Vector { _handler: GPIOQ6 }, Vector { _handler: GPIOQ7 }, Vector { _handler: GPIOR }, Vector { _handler: GPIOS }, Vector { _handler: SHA0 }, Vector { _handler: AES0 }, Vector { _handler: DES0 }, Vector { _handler: LCD0 }, Vector { _handler: TIMER6A }, Vector { _handler: TIMER6B }, Vector { _handler: TIMER7A }, Vector { _handler: TIMER7B }, Vector { _handler: I2C6 }, Vector { _handler: I2C7 }, Vector { _reserved: 0 }, Vector { _handler: ONEWIRE0 }, Vector { _reserved: 0 }, Vector { _reserved: 0 }, Vector { _reserved: 0 }, Vector { _handler: I2C8 }, Vector { _handler: I2C9 }, Vector { _handler: GPIOT }, ]; #[doc = r"Enumeration of all the interrupts"] #[derive(Copy, Clone, Debug)] #[repr(u8)] pub enum Interrupt { #[doc = "0 - GPIO Port A"] GPIOA = 0, #[doc = "1 - GPIO Port B"] GPIOB = 1, #[doc = "2 - GPIO Port C"] GPIOC = 2, #[doc = "3 - GPIO Port D"] GPIOD = 3, #[doc = "4 - GPIO Port E"] GPIOE = 4, #[doc = "5 - UART0"] UART0 = 5, #[doc = "6 - UART1"] UART1 = 6, #[doc = "7 - SSI0"] SSI0 = 7, #[doc = "8 - I2C0"] I2C0 = 8, #[doc = "9 - PWM Fault"] PWM0_FAULT = 9, #[doc = "10 - PWM Generator 0"] PWM0_0 = 10, #[doc = "11 - PWM Generator 1"] PWM0_1 = 11, #[doc = "12 - PWM Generator 2"] PWM0_2 = 12, #[doc = "13 - QEI0"] QEI0 = 13, #[doc = "14 - ADC0 Sequence 0"] ADC0SS0 = 14, #[doc = "15 - ADC0 Sequence 1"] ADC0SS1 = 15, #[doc = "16 - ADC0 Sequence 2"] ADC0SS2 = 16, #[doc = "17 - ADC0 Sequence 3"] ADC0SS3 = 17, #[doc = "18 - Watchdog Timers 0 and 1"] WATCHDOG = 18, #[doc = "19 - 16/32-Bit Timer 0A"] TIMER0A = 19, #[doc = "20 - 16/32-Bit Timer 0B"] TIMER0B = 20, #[doc = "21 - 16/32-Bit Timer 1A"] TIMER1A = 21, #[doc = "22 - 16/32-Bit Timer 1B"] TIMER1B = 22, #[doc = "23 - 16/32-Bit Timer 2A"] TIMER2A = 23, #[doc = "24 - 16/32-Bit Timer 2B"] TIMER2B = 24, #[doc = "25 - Analog Comparator 0"] COMP0 = 25, #[doc = "26 - Analog Comparator 1"] COMP1 = 26, #[doc = "27 - Analog Comparator 2"] COMP2 = 27, #[doc = "28 - System Control"] SYSCTL = 28, #[doc = "29 - Flash Memory Control"] FLASH = 29, #[doc = "30 - GPIO Port F"] GPIOF = 30, #[doc = "31 - GPIO Port G"] GPIOG = 31, #[doc = "32 - GPIO Port H"] GPIOH = 32, #[doc = "33 - UART2"] UART2 = 33, #[doc = "34 - SSI1"] SSI1 = 34, #[doc = "35 - 16/32-Bit Timer 3A"] TIMER3A = 35, #[doc = "36 - 16/32-Bit Timer 3B"] TIMER3B = 36, #[doc = "37 - I2C1"] I2C1 = 37, #[doc = "38 - CAN 0"] CAN0 = 38, #[doc = "39 - CAN1"] CAN1 = 39, #[doc = "40 - Ethernet MAC"] EMAC0 = 40, #[doc = "41 - HIB (Power Island)"] HIBERNATE = 41, #[doc = "42 - USB MAC"] USB0 = 42, #[doc = "43 - PWM Generator 3"] PWM0_3 = 43, #[doc = "44 - uDMA 0 Software"] UDMA = 44, #[doc = "45 - uDMA 0 Error"] UDMAERR = 45, #[doc = "46 - ADC1 Sequence 0"] ADC1SS0 = 46, #[doc = "47 - ADC1 Sequence 1"] ADC1SS1 = 47, #[doc = "48 - ADC1 Sequence 2"] ADC1SS2 = 48, #[doc = "49 - ADC1 Sequence 3"] ADC1SS3 = 49, #[doc = "50 - EPI 0"] EPI0 = 50, #[doc = "51 - GPIO Port J"] GPIOJ = 51, #[doc = "52 - GPIO Port K"] GPIOK = 52, #[doc = "53 - GPIO Port L"] GPIOL = 53, #[doc = "54 - SSI 2"] SSI2 = 54, #[doc = "55 - SSI 3"] SSI3 = 55, #[doc = "56 - UART 3"] UART3 = 56, #[doc = "57 - UART 4"] UART4 = 57, #[doc = "58 - UART 5"] UART5 = 58, #[doc = "59 - UART 6"] UART6 = 59, #[doc = "60 - UART 7"] UART7 = 60, #[doc = "61 - I2C 2"] I2C2 = 61, #[doc = "62 - I2C 3"] I2C3 = 62, #[doc = "63 - Timer 4A"] TIMER4A = 63, #[doc = "64 - Timer 4B"] TIMER4B = 64, #[doc = "65 - Timer 5A"] TIMER5A = 65, #[doc = "66 - Timer 5B"] TIMER5B = 66, #[doc = "67 - Floating-Point Exception (imprecise)"] SYSEXC = 67, #[doc = "70 - I2C 4"] I2C4 = 70, #[doc = "71 - I2C 5"] I2C5 = 71, #[doc = "72 - GPIO Port M"] GPIOM = 72, #[doc = "73 - GPIO Port N"] GPION = 73, #[doc = "75 - Tamper"] TAMPER0 = 75, #[doc = "76 - GPIO Port P (Summary or P0)"] GPIOP0 = 76, #[doc = "77 - GPIO Port P1"] GPIOP1 = 77, #[doc = "78 - GPIO Port P2"] GPIOP2 = 78, #[doc = "79 - GPIO Port P3"] GPIOP3 = 79, #[doc = "80 - GPIO Port P4"] GPIOP4 = 80, #[doc = "81 - GPIO Port P5"] GPIOP5 = 81, #[doc = "82 - GPIO Port P6"] GPIOP6 = 82, #[doc = "83 - GPIO Port P7"] GPIOP7 = 83, #[doc = "84 - GPIO Port Q (Summary or Q0)"] GPIOQ0 = 84, #[doc = "85 - GPIO Port Q1"] GPIOQ1 = 85, #[doc = "86 - GPIO Port Q2"] GPIOQ2 = 86, #[doc = "87 - GPIO Port Q3"] GPIOQ3 = 87, #[doc = "88 - GPIO Port Q4"] GPIOQ4 = 88, #[doc = "89 - GPIO Port Q5"] GPIOQ5 = 89, #[doc = "90 - GPIO Port Q6"] GPIOQ6 = 90, #[doc = "91 - GPIO Port Q7"] GPIOQ7 = 91, #[doc = "92 - GPIO Port R"] GPIOR = 92, #[doc = "93 - GPIO Port S"] GPIOS = 93, #[doc = "94 - SHA/MD5"] SHA0 = 94, #[doc = "95 - AES"] AES0 = 95, #[doc = "96 - DES"] DES0 = 96, #[doc = "97 - LCD"] LCD0 = 97, #[doc = "98 - 16/32-Bit Timer 6A"] TIMER6A = 98, #[doc = "99 - 16/32-Bit Timer 6B"] TIMER6B = 99, #[doc = "100 - 16/32-Bit Timer 7A"] TIMER7A = 100, #[doc = "101 - 16/32-Bit Timer 7B"] TIMER7B = 101, #[doc = "102 - I2C 6"] I2C6 = 102, #[doc = "103 - I2C 7"] I2C7 = 103, #[doc = "105 - 1-Wire"] ONEWIRE0 = 105, #[doc = "109 - I2C 8"] I2C8 = 109, #[doc = "110 - I2C 9"] I2C9 = 110, #[doc = "111 - GPIO T"] GPIOT = 111, } unsafe impl cortex_m::interrupt::InterruptNumber for Interrupt { #[inline(always)] fn number(self) -> u16 { self as u16 } } #[cfg(feature = "rt")] pub use self::Interrupt as interrupt; pub use cortex_m::peripheral::Peripherals as CorePeripherals; pub use cortex_m::peripheral::{CBP, CPUID, DCB, DWT, FPB, FPU, ITM, MPU, NVIC, SCB, SYST, TPIU}; #[cfg(feature = "rt")] pub use cortex_m_rt::interrupt; #[allow(unused_imports)] use generic::*; #[doc = r"Common register and bit access and modify traits"] pub mod generic; #[doc = "Watchdog Timer register offsets"] pub struct WATCHDOG0 { _marker: PhantomData<*const ()>, } unsafe impl Send for WATCHDOG0 {} impl WATCHDOG0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const watchdog0::RegisterBlock { 0x4000_0000 as *const _ } } impl Deref for WATCHDOG0 { type Target = watchdog0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*WATCHDOG0::ptr() } } } #[doc = "Watchdog Timer register offsets"] pub mod watchdog0; #[doc = "Watchdog Timer register offsets"] pub struct WATCHDOG1 { _marker: PhantomData<*const ()>, } unsafe impl Send for WATCHDOG1 {} impl WATCHDOG1 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const watchdog0::RegisterBlock { 0x4000_1000 as *const _ } } impl Deref for WATCHDOG1 { type Target = watchdog0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*WATCHDOG1::ptr() } } } #[doc = "SSI register offsets"] pub struct SSI0 { _marker: PhantomData<*const ()>, } unsafe impl Send for SSI0 {} impl SSI0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const ssi0::RegisterBlock { 0x4000_8000 as *const _ } } impl Deref for SSI0 { type Target = ssi0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*SSI0::ptr() } } } #[doc = "SSI register offsets"] pub mod ssi0; #[doc = "SSI register offsets"] pub struct SSI1 { _marker: PhantomData<*const ()>, } unsafe impl Send for SSI1 {} impl SSI1 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const ssi0::RegisterBlock { 0x4000_9000 as *const _ } } impl Deref for SSI1 { type Target = ssi0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*SSI1::ptr() } } } #[doc = "SSI register offsets"] pub struct SSI2 { _marker: PhantomData<*const ()>, } unsafe impl Send for SSI2 {} impl SSI2 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const ssi0::RegisterBlock { 0x4000_a000 as *const _ } } impl Deref for SSI2 { type Target = ssi0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*SSI2::ptr() } } } #[doc = "SSI register offsets"] pub struct SSI3 { _marker: PhantomData<*const ()>, } unsafe impl Send for SSI3 {} impl SSI3 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const ssi0::RegisterBlock { 0x4000_b000 as *const _ } } impl Deref for SSI3 { type Target = ssi0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*SSI3::ptr() } } } #[doc = "UART register offsets"] pub struct UART0 { _marker: PhantomData<*const ()>, } unsafe impl Send for UART0 {} impl UART0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const uart0::RegisterBlock { 0x4000_c000 as *const _ } } impl Deref for UART0 { type Target = uart0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*UART0::ptr() } } } #[doc = "UART register offsets"] pub mod uart0; #[doc = "UART register offsets"] pub struct UART1 { _marker: PhantomData<*const ()>, } unsafe impl Send for UART1 {} impl UART1 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const uart0::RegisterBlock { 0x4000_d000 as *const _ } } impl Deref for UART1 { type Target = uart0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*UART1::ptr() } } } #[doc = "UART register offsets"] pub struct UART2 { _marker: PhantomData<*const ()>, } unsafe impl Send for UART2 {} impl UART2 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const uart0::RegisterBlock { 0x4000_e000 as *const _ } } impl Deref for UART2 { type Target = uart0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*UART2::ptr() } } } #[doc = "UART register offsets"] pub struct UART3 { _marker: PhantomData<*const ()>, } unsafe impl Send for UART3 {} impl UART3 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const uart0::RegisterBlock { 0x4000_f000 as *const _ } } impl Deref for UART3 { type Target = uart0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*UART3::ptr() } } } #[doc = "UART register offsets"] pub struct UART4 { _marker: PhantomData<*const ()>, } unsafe impl Send for UART4 {} impl UART4 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const uart0::RegisterBlock { 0x4001_0000 as *const _ } } impl Deref for UART4 { type Target = uart0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*UART4::ptr() } } } #[doc = "UART register offsets"] pub struct UART5 { _marker: PhantomData<*const ()>, } unsafe impl Send for UART5 {} impl UART5 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const uart0::RegisterBlock { 0x4001_1000 as *const _ } } impl Deref for UART5 { type Target = uart0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*UART5::ptr() } } } #[doc = "UART register offsets"] pub struct UART6 { _marker: PhantomData<*const ()>, } unsafe impl Send for UART6 {} impl UART6 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const uart0::RegisterBlock { 0x4001_2000 as *const _ } } impl Deref for UART6 { type Target = uart0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*UART6::ptr() } } } #[doc = "UART register offsets"] pub struct UART7 { _marker: PhantomData<*const ()>, } unsafe impl Send for UART7 {} impl UART7 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const uart0::RegisterBlock { 0x4001_3000 as *const _ } } impl Deref for UART7 { type Target = uart0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*UART7::ptr() } } } #[doc = "I2C register offsets"] pub struct I2C0 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C0 {} impl I2C0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x4002_0000 as *const _ } } impl Deref for I2C0 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C0::ptr() } } } #[doc = "I2C register offsets"] pub mod i2c0; #[doc = "I2C register offsets"] pub struct I2C1 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C1 {} impl I2C1 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x4002_1000 as *const _ } } impl Deref for I2C1 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C1::ptr() } } } #[doc = "I2C register offsets"] pub struct I2C2 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C2 {} impl I2C2 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x4002_2000 as *const _ } } impl Deref for I2C2 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C2::ptr() } } } #[doc = "I2C register offsets"] pub struct I2C3 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C3 {} impl I2C3 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x4002_3000 as *const _ } } impl Deref for I2C3 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C3::ptr() } } } #[doc = "PWM register offsets"] pub struct PWM0 { _marker: PhantomData<*const ()>, } unsafe impl Send for PWM0 {} impl PWM0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const pwm0::RegisterBlock { 0x4002_8000 as *const _ } } impl Deref for PWM0 { type Target = pwm0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*PWM0::ptr() } } } #[doc = "PWM register offsets"] pub mod pwm0; #[doc = "QEI register offsets"] pub struct QEI0 { _marker: PhantomData<*const ()>, } unsafe impl Send for QEI0 {} impl QEI0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const qei0::RegisterBlock { 0x4002_c000 as *const _ } } impl Deref for QEI0 { type Target = qei0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*QEI0::ptr() } } } #[doc = "QEI register offsets"] pub mod qei0; #[doc = "Timer register offsets"] pub struct TIMER0 { _marker: PhantomData<*const ()>, } unsafe impl Send for TIMER0 {} impl TIMER0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const timer0::RegisterBlock { 0x4003_0000 as *const _ } } impl Deref for TIMER0 { type Target = timer0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*TIMER0::ptr() } } } #[doc = "Timer register offsets"] pub mod timer0; #[doc = "Timer register offsets"] pub struct TIMER1 { _marker: PhantomData<*const ()>, } unsafe impl Send for TIMER1 {} impl TIMER1 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const timer0::RegisterBlock { 0x4003_1000 as *const _ } } impl Deref for TIMER1 { type Target = timer0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*TIMER1::ptr() } } } #[doc = "Timer register offsets"] pub struct TIMER2 { _marker: PhantomData<*const ()>, } unsafe impl Send for TIMER2 {} impl TIMER2 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const timer0::RegisterBlock { 0x4003_2000 as *const _ } } impl Deref for TIMER2 { type Target = timer0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*TIMER2::ptr() } } } #[doc = "Timer register offsets"] pub struct TIMER3 { _marker: PhantomData<*const ()>, } unsafe impl Send for TIMER3 {} impl TIMER3 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const timer0::RegisterBlock { 0x4003_3000 as *const _ } } impl Deref for TIMER3 { type Target = timer0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*TIMER3::ptr() } } } #[doc = "Timer register offsets"] pub struct TIMER4 { _marker: PhantomData<*const ()>, } unsafe impl Send for TIMER4 {} impl TIMER4 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const timer0::RegisterBlock { 0x4003_4000 as *const _ } } impl Deref for TIMER4 { type Target = timer0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*TIMER4::ptr() } } } #[doc = "Timer register offsets"] pub struct TIMER5 { _marker: PhantomData<*const ()>, } unsafe impl Send for TIMER5 {} impl TIMER5 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const timer0::RegisterBlock { 0x4003_5000 as *const _ } } impl Deref for TIMER5 { type Target = timer0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*TIMER5::ptr() } } } #[doc = "ADC register offsets"] pub struct ADC0 { _marker: PhantomData<*const ()>, } unsafe impl Send for ADC0 {} impl ADC0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const adc0::RegisterBlock { 0x4003_8000 as *const _ } } impl Deref for ADC0 { type Target = adc0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*ADC0::ptr() } } } #[doc = "ADC register offsets"] pub mod adc0; #[doc = "ADC register offsets"] pub struct ADC1 { _marker: PhantomData<*const ()>, } unsafe impl Send for ADC1 {} impl ADC1 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const adc0::RegisterBlock { 0x4003_9000 as *const _ } } impl Deref for ADC1 { type Target = adc0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*ADC1::ptr() } } } #[doc = "Comparator register offsets"] pub struct COMP { _marker: PhantomData<*const ()>, } unsafe impl Send for COMP {} impl COMP { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const comp::RegisterBlock { 0x4003_c000 as *const _ } } impl Deref for COMP { type Target = comp::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*COMP::ptr() } } } #[doc = "Comparator register offsets"] pub mod comp; #[doc = "CAN register offsets"] pub struct CAN0 { _marker: PhantomData<*const ()>, } unsafe impl Send for CAN0 {} impl CAN0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const can0::RegisterBlock { 0x4004_0000 as *const _ } } impl Deref for CAN0 { type Target = can0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*CAN0::ptr() } } } #[doc = "CAN register offsets"] pub mod can0; #[doc = "CAN register offsets"] pub struct CAN1 { _marker: PhantomData<*const ()>, } unsafe impl Send for CAN1 {} impl CAN1 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const can0::RegisterBlock { 0x4004_1000 as *const _ } } impl Deref for CAN1 { type Target = can0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*CAN1::ptr() } } } #[doc = "Univeral Serial Bus register offsets"] pub struct USB0 { _marker: PhantomData<*const ()>, } unsafe impl Send for USB0 {} impl USB0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const usb0::RegisterBlock { 0x4005_0000 as *const _ } } impl Deref for USB0 { type Target = usb0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*USB0::ptr() } } } #[doc = "Univeral Serial Bus register offsets"] pub mod usb0; #[doc = "GPIO register offsets"] pub struct GPIO_PORTA_AHB { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTA_AHB {} impl GPIO_PORTA_AHB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4005_8000 as *const _ } } impl Deref for GPIO_PORTA_AHB { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTA_AHB::ptr() } } } #[doc = "GPIO register offsets"] pub mod gpio_porta_ahb; #[doc = "GPIO register offsets"] pub struct GPIO_PORTB_AHB { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTB_AHB {} impl GPIO_PORTB_AHB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4005_9000 as *const _ } } impl Deref for GPIO_PORTB_AHB { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTB_AHB::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTC_AHB { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTC_AHB {} impl GPIO_PORTC_AHB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4005_a000 as *const _ } } impl Deref for GPIO_PORTC_AHB { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTC_AHB::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTD_AHB { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTD_AHB {} impl GPIO_PORTD_AHB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4005_b000 as *const _ } } impl Deref for GPIO_PORTD_AHB { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTD_AHB::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTE_AHB { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTE_AHB {} impl GPIO_PORTE_AHB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4005_c000 as *const _ } } impl Deref for GPIO_PORTE_AHB { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTE_AHB::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTF_AHB { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTF_AHB {} impl GPIO_PORTF_AHB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4005_d000 as *const _ } } impl Deref for GPIO_PORTF_AHB { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTF_AHB::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTG_AHB { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTG_AHB {} impl GPIO_PORTG_AHB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4005_e000 as *const _ } } impl Deref for GPIO_PORTG_AHB { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTG_AHB::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTH_AHB { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTH_AHB {} impl GPIO_PORTH_AHB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4005_f000 as *const _ } } impl Deref for GPIO_PORTH_AHB { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTH_AHB::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTJ_AHB { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTJ_AHB {} impl GPIO_PORTJ_AHB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4006_0000 as *const _ } } impl Deref for GPIO_PORTJ_AHB { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTJ_AHB::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTK { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTK {} impl GPIO_PORTK { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4006_1000 as *const _ } } impl Deref for GPIO_PORTK { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTK::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTL { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTL {} impl GPIO_PORTL { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4006_2000 as *const _ } } impl Deref for GPIO_PORTL { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTL::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTM { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTM {} impl GPIO_PORTM { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4006_3000 as *const _ } } impl Deref for GPIO_PORTM { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTM::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTN { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTN {} impl GPIO_PORTN { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4006_4000 as *const _ } } impl Deref for GPIO_PORTN { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTN::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTP { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTP {} impl GPIO_PORTP { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4006_5000 as *const _ } } impl Deref for GPIO_PORTP { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTP::ptr() } } } #[doc = "GPIO register offsets"] pub struct GPIO_PORTQ { _marker: PhantomData<*const ()>, } unsafe impl Send for GPIO_PORTQ {} impl GPIO_PORTQ { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const gpio_porta_ahb::RegisterBlock { 0x4006_6000 as *const _ } } impl Deref for GPIO_PORTQ { type Target = gpio_porta_ahb::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*GPIO_PORTQ::ptr() } } } #[doc = "EEPROM register offsets"] pub struct EEPROM { _marker: PhantomData<*const ()>, } unsafe impl Send for EEPROM {} impl EEPROM { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const eeprom::RegisterBlock { 0x400a_f000 as *const _ } } impl Deref for EEPROM { type Target = eeprom::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*EEPROM::ptr() } } } #[doc = "EEPROM register offsets"] pub mod eeprom; #[doc = "I2C register offsets"] pub struct I2C8 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C8 {} impl I2C8 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x400b_8000 as *const _ } } impl Deref for I2C8 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C8::ptr() } } } #[doc = "I2C register offsets"] pub struct I2C9 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C9 {} impl I2C9 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x400b_9000 as *const _ } } impl Deref for I2C9 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C9::ptr() } } } #[doc = "I2C register offsets"] pub struct I2C4 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C4 {} impl I2C4 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x400c_0000 as *const _ } } impl Deref for I2C4 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C4::ptr() } } } #[doc = "I2C register offsets"] pub struct I2C5 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C5 {} impl I2C5 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x400c_1000 as *const _ } } impl Deref for I2C5 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C5::ptr() } } } #[doc = "I2C register offsets"] pub struct I2C6 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C6 {} impl I2C6 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x400c_2000 as *const _ } } impl Deref for I2C6 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C6::ptr() } } } #[doc = "I2C register offsets"] pub struct I2C7 { _marker: PhantomData<*const ()>, } unsafe impl Send for I2C7 {} impl I2C7 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const i2c0::RegisterBlock { 0x400c_3000 as *const _ } } impl Deref for I2C7 { type Target = i2c0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*I2C7::ptr() } } } #[doc = "External Peripheral Interface register offsets"] pub struct EPI0 { _marker: PhantomData<*const ()>, } unsafe impl Send for EPI0 {} impl EPI0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const epi0::RegisterBlock { 0x400d_0000 as *const _ } } impl Deref for EPI0 { type Target = epi0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*EPI0::ptr() } } } #[doc = "External Peripheral Interface register offsets"] pub mod epi0; #[doc = "Timer register offsets"] pub struct TIMER6 { _marker: PhantomData<*const ()>, } unsafe impl Send for TIMER6 {} impl TIMER6 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const timer0::RegisterBlock { 0x400e_0000 as *const _ } } impl Deref for TIMER6 { type Target = timer0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*TIMER6::ptr() } } } #[doc = "Timer register offsets"] pub struct TIMER7 { _marker: PhantomData<*const ()>, } unsafe impl Send for TIMER7 {} impl TIMER7 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const timer0::RegisterBlock { 0x400e_1000 as *const _ } } impl Deref for TIMER7 { type Target = timer0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*TIMER7::ptr() } } } #[doc = "EMAC register offsets"] pub struct EMAC0 { _marker: PhantomData<*const ()>, } unsafe impl Send for EMAC0 {} impl EMAC0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const emac0::RegisterBlock { 0x400e_c000 as *const _ } } impl Deref for EMAC0 { type Target = emac0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*EMAC0::ptr() } } } #[doc = "EMAC register offsets"] pub mod emac0; #[doc = "System Exception Module register addresses"] pub struct SYSEXC { _marker: PhantomData<*const ()>, } unsafe impl Send for SYSEXC {} impl SYSEXC { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const sysexc::RegisterBlock { 0x400f_9000 as *const _ } } impl Deref for SYSEXC { type Target = sysexc::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*SYSEXC::ptr() } } } #[doc = "System Exception Module register addresses"] pub mod sysexc; #[doc = "Hibernation module register addresses"] pub struct HIB { _marker: PhantomData<*const ()>, } unsafe impl Send for HIB {} impl HIB { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const hib::RegisterBlock { 0x400f_c000 as *const _ } } impl Deref for HIB { type Target = hib::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*HIB::ptr() } } } #[doc = "Hibernation module register addresses"] pub mod hib; #[doc = "FLASH register offsets"] pub struct FLASH_CTRL { _marker: PhantomData<*const ()>, } unsafe impl Send for FLASH_CTRL {} impl FLASH_CTRL { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const flash_ctrl::RegisterBlock { 0x400f_d000 as *const _ } } impl Deref for FLASH_CTRL { type Target = flash_ctrl::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*FLASH_CTRL::ptr() } } } #[doc = "FLASH register offsets"] pub mod flash_ctrl; #[doc = "System Control register addresses"] pub struct SYSCTL { _marker: PhantomData<*const ()>, } unsafe impl Send for SYSCTL {} impl SYSCTL { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const sysctl::RegisterBlock { 0x400f_e000 as *const _ } } impl Deref for SYSCTL { type Target = sysctl::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*SYSCTL::ptr() } } } #[doc = "System Control register addresses"] pub mod sysctl; #[doc = "Micro Direct Memory Access register addresses"] pub struct UDMA { _marker: PhantomData<*const ()>, } unsafe impl Send for UDMA {} impl UDMA { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const udma::RegisterBlock { 0x400f_f000 as *const _ } } impl Deref for UDMA { type Target = udma::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*UDMA::ptr() } } } #[doc = "Micro Direct Memory Access register addresses"] pub mod udma; #[doc = "EC register offsets"] pub struct CCM0 { _marker: PhantomData<*const ()>, } unsafe impl Send for CCM0 {} impl CCM0 { #[doc = r"Returns a pointer to the register block"] #[inline(always)] pub const fn ptr() -> *const ccm0::RegisterBlock { 0x4403_0000 as *const _ } } impl Deref for CCM0 { type Target = ccm0::RegisterBlock; #[inline(always)] fn deref(&self) -> &Self::Target { unsafe { &*CCM0::ptr() } } } #[doc = "EC register offsets"] pub mod ccm0; #[no_mangle] static mut DEVICE_PERIPHERALS: bool = false; #[doc = r"All the peripherals"] #[allow(non_snake_case)] pub struct Peripherals { #[doc = "WATCHDOG0"] pub WATCHDOG0: WATCHDOG0, #[doc = "WATCHDOG1"] pub WATCHDOG1: WATCHDOG1, #[doc = "SSI0"] pub SSI0: SSI0, #[doc = "SSI1"] pub SSI1: SSI1, #[doc = "SSI2"] pub SSI2: SSI2, #[doc = "SSI3"] pub SSI3: SSI3, #[doc = "UART0"] pub UART0: UART0, #[doc = "UART1"] pub UART1: UART1, #[doc = "UART2"] pub UART2: UART2, #[doc = "UART3"] pub UART3: UART3, #[doc = "UART4"] pub UART4: UART4, #[doc = "UART5"] pub UART5: UART5, #[doc = "UART6"] pub UART6: UART6, #[doc = "UART7"] pub UART7: UART7, #[doc = "I2C0"] pub I2C0: I2C0, #[doc = "I2C1"] pub I2C1: I2C1, #[doc = "I2C2"] pub I2C2: I2C2, #[doc = "I2C3"] pub I2C3: I2C3, #[doc = "PWM0"] pub PWM0: PWM0, #[doc = "QEI0"] pub QEI0: QEI0, #[doc = "TIMER0"] pub TIMER0: TIMER0, #[doc = "TIMER1"] pub TIMER1: TIMER1, #[doc = "TIMER2"] pub TIMER2: TIMER2, #[doc = "TIMER3"] pub TIMER3: TIMER3, #[doc = "TIMER4"] pub TIMER4: TIMER4, #[doc = "TIMER5"] pub TIMER5: TIMER5, #[doc = "ADC0"] pub ADC0: ADC0, #[doc = "ADC1"] pub ADC1: ADC1, #[doc = "COMP"] pub COMP: COMP, #[doc = "CAN0"] pub CAN0: CAN0, #[doc = "CAN1"] pub CAN1: CAN1, #[doc = "USB0"] pub USB0: USB0, #[doc = "GPIO_PORTA_AHB"] pub GPIO_PORTA_AHB: GPIO_PORTA_AHB, #[doc = "GPIO_PORTB_AHB"] pub GPIO_PORTB_AHB: GPIO_PORTB_AHB, #[doc = "GPIO_PORTC_AHB"] pub GPIO_PORTC_AHB: GPIO_PORTC_AHB, #[doc = "GPIO_PORTD_AHB"] pub GPIO_PORTD_AHB: GPIO_PORTD_AHB, #[doc = "GPIO_PORTE_AHB"] pub GPIO_PORTE_AHB: GPIO_PORTE_AHB, #[doc = "GPIO_PORTF_AHB"] pub GPIO_PORTF_AHB: GPIO_PORTF_AHB, #[doc = "GPIO_PORTG_AHB"] pub GPIO_PORTG_AHB: GPIO_PORTG_AHB, #[doc = "GPIO_PORTH_AHB"] pub GPIO_PORTH_AHB: GPIO_PORTH_AHB, #[doc = "GPIO_PORTJ_AHB"] pub GPIO_PORTJ_AHB: GPIO_PORTJ_AHB, #[doc = "GPIO_PORTK"] pub GPIO_PORTK: GPIO_PORTK, #[doc = "GPIO_PORTL"] pub GPIO_PORTL: GPIO_PORTL, #[doc = "GPIO_PORTM"] pub GPIO_PORTM: GPIO_PORTM, #[doc = "GPIO_PORTN"] pub GPIO_PORTN: GPIO_PORTN, #[doc = "GPIO_PORTP"] pub GPIO_PORTP: GPIO_PORTP, #[doc = "GPIO_PORTQ"] pub GPIO_PORTQ: GPIO_PORTQ, #[doc = "EEPROM"] pub EEPROM: EEPROM, #[doc = "I2C8"] pub I2C8: I2C8, #[doc = "I2C9"] pub I2C9: I2C9, #[doc = "I2C4"] pub I2C4: I2C4, #[doc = "I2C5"] pub I2C5: I2C5, #[doc = "I2C6"] pub I2C6: I2C6, #[doc = "I2C7"] pub I2C7: I2C7, #[doc = "EPI0"] pub EPI0: EPI0, #[doc = "TIMER6"] pub TIMER6: TIMER6, #[doc = "TIMER7"] pub TIMER7: TIMER7, #[doc = "EMAC0"] pub EMAC0: EMAC0, #[doc = "SYSEXC"] pub SYSEXC: SYSEXC, #[doc = "HIB"] pub HIB: HIB, #[doc = "FLASH_CTRL"] pub FLASH_CTRL: FLASH_CTRL, #[doc = "SYSCTL"] pub SYSCTL: SYSCTL, #[doc = "UDMA"] pub UDMA: UDMA, #[doc = "CCM0"] pub CCM0: CCM0, } impl Peripherals { #[doc = r"Returns all the peripherals *once*"] #[inline] pub fn take() -> Option<Self> { cortex_m::interrupt::free(|_| if unsafe { DEVICE_PERIPHERALS } { None } else { Some(unsafe { Peripherals::steal() }) }) } #[doc = r"Unchecked version of `Peripherals::take`"] #[inline] pub unsafe fn steal() -> Self { DEVICE_PERIPHERALS = true; Peripherals { WATCHDOG0: WATCHDOG0 { _marker: PhantomData }, WATCHDOG1: WATCHDOG1 { _marker: PhantomData }, SSI0: SSI0 { _marker: PhantomData }, SSI1: SSI1 { _marker: PhantomData }, SSI2: SSI2 { _marker: PhantomData }, SSI3: SSI3 { _marker: PhantomData }, UART0: UART0 { _marker: PhantomData }, UART1: UART1 { _marker: PhantomData }, UART2: UART2 { _marker: PhantomData }, UART3: UART3 { _marker: PhantomData }, UART4: UART4 { _marker: PhantomData }, UART5: UART5 { _marker: PhantomData }, UART6: UART6 { _marker: PhantomData }, UART7: UART7 { _marker: PhantomData }, I2C0: I2C0 { _marker: PhantomData }, I2C1: I2C1 { _marker: PhantomData }, I2C2: I2C2 { _marker: PhantomData }, I2C3: I2C3 { _marker: PhantomData }, PWM0: PWM0 { _marker: PhantomData }, QEI0: QEI0 { _marker: PhantomData }, TIMER0: TIMER0 { _marker: PhantomData }, TIMER1: TIMER1 { _marker: PhantomData }, TIMER2: TIMER2 { _marker: PhantomData }, TIMER3: TIMER3 { _marker: PhantomData }, TIMER4: TIMER4 { _marker: PhantomData }, TIMER5: TIMER5 { _marker: PhantomData }, ADC0: ADC0 { _marker: PhantomData }, ADC1: ADC1 { _marker: PhantomData }, COMP: COMP { _marker: PhantomData }, CAN0: CAN0 { _marker: PhantomData }, CAN1: CAN1 { _marker: PhantomData }, USB0: USB0 { _marker: PhantomData }, GPIO_PORTA_AHB: GPIO_PORTA_AHB { _marker: PhantomData }, GPIO_PORTB_AHB: GPIO_PORTB_AHB { _marker: PhantomData }, GPIO_PORTC_AHB: GPIO_PORTC_AHB { _marker: PhantomData }, GPIO_PORTD_AHB: GPIO_PORTD_AHB { _marker: PhantomData }, GPIO_PORTE_AHB: GPIO_PORTE_AHB { _marker: PhantomData }, GPIO_PORTF_AHB: GPIO_PORTF_AHB { _marker: PhantomData }, GPIO_PORTG_AHB: GPIO_PORTG_AHB { _marker: PhantomData }, GPIO_PORTH_AHB: GPIO_PORTH_AHB { _marker: PhantomData }, GPIO_PORTJ_AHB: GPIO_PORTJ_AHB { _marker: PhantomData }, GPIO_PORTK: GPIO_PORTK { _marker: PhantomData }, GPIO_PORTL: GPIO_PORTL { _marker: PhantomData }, GPIO_PORTM: GPIO_PORTM { _marker: PhantomData }, GPIO_PORTN: GPIO_PORTN { _marker: PhantomData }, GPIO_PORTP: GPIO_PORTP { _marker: PhantomData }, GPIO_PORTQ: GPIO_PORTQ { _marker: PhantomData }, EEPROM: EEPROM { _marker: PhantomData }, I2C8: I2C8 { _marker: PhantomData }, I2C9: I2C9 { _marker: PhantomData }, I2C4: I2C4 { _marker: PhantomData }, I2C5: I2C5 { _marker: PhantomData }, I2C6: I2C6 { _marker: PhantomData }, I2C7: I2C7 { _marker: PhantomData }, EPI0: EPI0 { _marker: PhantomData }, TIMER6: TIMER6 { _marker: PhantomData }, TIMER7: TIMER7 { _marker: PhantomData }, EMAC0: EMAC0 { _marker: PhantomData }, SYSEXC: SYSEXC { _marker: PhantomData }, HIB: HIB { _marker: PhantomData }, FLASH_CTRL: FLASH_CTRL { _marker: PhantomData }, SYSCTL: SYSCTL { _marker: PhantomData }, UDMA: UDMA { _marker: PhantomData }, CCM0: CCM0 { _marker: PhantomData }, } } }
#[doc = "Reader of register AFRH"] pub type R = crate::R<u32, super::AFRH>; #[doc = "Writer for register AFRH"] pub type W = crate::W<u32, super::AFRH>; #[doc = "Register AFRH `reset()`'s with value 0"] impl crate::ResetValue for super::AFRH { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Alternate function selection for port x pin y (y = 8..15)\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum AFSEL15_A { #[doc = "0: AF0"] AF0 = 0, #[doc = "1: AF1"] AF1 = 1, #[doc = "2: AF2"] AF2 = 2, #[doc = "3: AF3"] AF3 = 3, #[doc = "4: AF4"] AF4 = 4, #[doc = "5: AF5"] AF5 = 5, #[doc = "6: AF6"] AF6 = 6, #[doc = "7: AF7"] AF7 = 7, #[doc = "8: AF8"] AF8 = 8, #[doc = "9: AF9"] AF9 = 9, #[doc = "10: AF10"] AF10 = 10, #[doc = "11: AF11"] AF11 = 11, #[doc = "12: AF12"] AF12 = 12, #[doc = "13: AF13"] AF13 = 13, #[doc = "14: AF14"] AF14 = 14, #[doc = "15: AF15"] AF15 = 15, } impl From<AFSEL15_A> for u8 { #[inline(always)] fn from(variant: AFSEL15_A) -> Self { variant as _ } } #[doc = "Reader of field `AFSEL15`"] pub type AFSEL15_R = crate::R<u8, AFSEL15_A>; impl AFSEL15_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> AFSEL15_A { match self.bits { 0 => AFSEL15_A::AF0, 1 => AFSEL15_A::AF1, 2 => AFSEL15_A::AF2, 3 => AFSEL15_A::AF3, 4 => AFSEL15_A::AF4, 5 => AFSEL15_A::AF5, 6 => AFSEL15_A::AF6, 7 => AFSEL15_A::AF7, 8 => AFSEL15_A::AF8, 9 => AFSEL15_A::AF9, 10 => AFSEL15_A::AF10, 11 => AFSEL15_A::AF11, 12 => AFSEL15_A::AF12, 13 => AFSEL15_A::AF13, 14 => AFSEL15_A::AF14, 15 => AFSEL15_A::AF15, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `AF0`"] #[inline(always)] pub fn is_af0(&self) -> bool { *self == AFSEL15_A::AF0 } #[doc = "Checks if the value of the field is `AF1`"] #[inline(always)] pub fn is_af1(&self) -> bool { *self == AFSEL15_A::AF1 } #[doc = "Checks if the value of the field is `AF2`"] #[inline(always)] pub fn is_af2(&self) -> bool { *self == AFSEL15_A::AF2 } #[doc = "Checks if the value of the field is `AF3`"] #[inline(always)] pub fn is_af3(&self) -> bool { *self == AFSEL15_A::AF3 } #[doc = "Checks if the value of the field is `AF4`"] #[inline(always)] pub fn is_af4(&self) -> bool { *self == AFSEL15_A::AF4 } #[doc = "Checks if the value of the field is `AF5`"] #[inline(always)] pub fn is_af5(&self) -> bool { *self == AFSEL15_A::AF5 } #[doc = "Checks if the value of the field is `AF6`"] #[inline(always)] pub fn is_af6(&self) -> bool { *self == AFSEL15_A::AF6 } #[doc = "Checks if the value of the field is `AF7`"] #[inline(always)] pub fn is_af7(&self) -> bool { *self == AFSEL15_A::AF7 } #[doc = "Checks if the value of the field is `AF8`"] #[inline(always)] pub fn is_af8(&self) -> bool { *self == AFSEL15_A::AF8 } #[doc = "Checks if the value of the field is `AF9`"] #[inline(always)] pub fn is_af9(&self) -> bool { *self == AFSEL15_A::AF9 } #[doc = "Checks if the value of the field is `AF10`"] #[inline(always)] pub fn is_af10(&self) -> bool { *self == AFSEL15_A::AF10 } #[doc = "Checks if the value of the field is `AF11`"] #[inline(always)] pub fn is_af11(&self) -> bool { *self == AFSEL15_A::AF11 } #[doc = "Checks if the value of the field is `AF12`"] #[inline(always)] pub fn is_af12(&self) -> bool { *self == AFSEL15_A::AF12 } #[doc = "Checks if the value of the field is `AF13`"] #[inline(always)] pub fn is_af13(&self) -> bool { *self == AFSEL15_A::AF13 } #[doc = "Checks if the value of the field is `AF14`"] #[inline(always)] pub fn is_af14(&self) -> bool { *self == AFSEL15_A::AF14 } #[doc = "Checks if the value of the field is `AF15`"] #[inline(always)] pub fn is_af15(&self) -> bool { *self == AFSEL15_A::AF15 } } #[doc = "Write proxy for field `AFSEL15`"] pub struct AFSEL15_W<'a> { w: &'a mut W, } impl<'a> AFSEL15_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AFSEL15_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "AF0"] #[inline(always)] pub fn af0(self) -> &'a mut W { self.variant(AFSEL15_A::AF0) } #[doc = "AF1"] #[inline(always)] pub fn af1(self) -> &'a mut W { self.variant(AFSEL15_A::AF1) } #[doc = "AF2"] #[inline(always)] pub fn af2(self) -> &'a mut W { self.variant(AFSEL15_A::AF2) } #[doc = "AF3"] #[inline(always)] pub fn af3(self) -> &'a mut W { self.variant(AFSEL15_A::AF3) } #[doc = "AF4"] #[inline(always)] pub fn af4(self) -> &'a mut W { self.variant(AFSEL15_A::AF4) } #[doc = "AF5"] #[inline(always)] pub fn af5(self) -> &'a mut W { self.variant(AFSEL15_A::AF5) } #[doc = "AF6"] #[inline(always)] pub fn af6(self) -> &'a mut W { self.variant(AFSEL15_A::AF6) } #[doc = "AF7"] #[inline(always)] pub fn af7(self) -> &'a mut W { self.variant(AFSEL15_A::AF7) } #[doc = "AF8"] #[inline(always)] pub fn af8(self) -> &'a mut W { self.variant(AFSEL15_A::AF8) } #[doc = "AF9"] #[inline(always)] pub fn af9(self) -> &'a mut W { self.variant(AFSEL15_A::AF9) } #[doc = "AF10"] #[inline(always)] pub fn af10(self) -> &'a mut W { self.variant(AFSEL15_A::AF10) } #[doc = "AF11"] #[inline(always)] pub fn af11(self) -> &'a mut W { self.variant(AFSEL15_A::AF11) } #[doc = "AF12"] #[inline(always)] pub fn af12(self) -> &'a mut W { self.variant(AFSEL15_A::AF12) } #[doc = "AF13"] #[inline(always)] pub fn af13(self) -> &'a mut W { self.variant(AFSEL15_A::AF13) } #[doc = "AF14"] #[inline(always)] pub fn af14(self) -> &'a mut W { self.variant(AFSEL15_A::AF14) } #[doc = "AF15"] #[inline(always)] pub fn af15(self) -> &'a mut W { self.variant(AFSEL15_A::AF15) } #[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 << 28)) | (((value as u32) & 0x0f) << 28); self.w } } #[doc = "Alternate function selection for port x pin y (y = 8..15)"] pub type AFSEL14_A = AFSEL15_A; #[doc = "Reader of field `AFSEL14`"] pub type AFSEL14_R = crate::R<u8, AFSEL15_A>; #[doc = "Write proxy for field `AFSEL14`"] pub struct AFSEL14_W<'a> { w: &'a mut W, } impl<'a> AFSEL14_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AFSEL14_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "AF0"] #[inline(always)] pub fn af0(self) -> &'a mut W { self.variant(AFSEL15_A::AF0) } #[doc = "AF1"] #[inline(always)] pub fn af1(self) -> &'a mut W { self.variant(AFSEL15_A::AF1) } #[doc = "AF2"] #[inline(always)] pub fn af2(self) -> &'a mut W { self.variant(AFSEL15_A::AF2) } #[doc = "AF3"] #[inline(always)] pub fn af3(self) -> &'a mut W { self.variant(AFSEL15_A::AF3) } #[doc = "AF4"] #[inline(always)] pub fn af4(self) -> &'a mut W { self.variant(AFSEL15_A::AF4) } #[doc = "AF5"] #[inline(always)] pub fn af5(self) -> &'a mut W { self.variant(AFSEL15_A::AF5) } #[doc = "AF6"] #[inline(always)] pub fn af6(self) -> &'a mut W { self.variant(AFSEL15_A::AF6) } #[doc = "AF7"] #[inline(always)] pub fn af7(self) -> &'a mut W { self.variant(AFSEL15_A::AF7) } #[doc = "AF8"] #[inline(always)] pub fn af8(self) -> &'a mut W { self.variant(AFSEL15_A::AF8) } #[doc = "AF9"] #[inline(always)] pub fn af9(self) -> &'a mut W { self.variant(AFSEL15_A::AF9) } #[doc = "AF10"] #[inline(always)] pub fn af10(self) -> &'a mut W { self.variant(AFSEL15_A::AF10) } #[doc = "AF11"] #[inline(always)] pub fn af11(self) -> &'a mut W { self.variant(AFSEL15_A::AF11) } #[doc = "AF12"] #[inline(always)] pub fn af12(self) -> &'a mut W { self.variant(AFSEL15_A::AF12) } #[doc = "AF13"] #[inline(always)] pub fn af13(self) -> &'a mut W { self.variant(AFSEL15_A::AF13) } #[doc = "AF14"] #[inline(always)] pub fn af14(self) -> &'a mut W { self.variant(AFSEL15_A::AF14) } #[doc = "AF15"] #[inline(always)] pub fn af15(self) -> &'a mut W { self.variant(AFSEL15_A::AF15) } #[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 << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "Alternate function selection for port x pin y (y = 8..15)"] pub type AFSEL13_A = AFSEL15_A; #[doc = "Reader of field `AFSEL13`"] pub type AFSEL13_R = crate::R<u8, AFSEL15_A>; #[doc = "Write proxy for field `AFSEL13`"] pub struct AFSEL13_W<'a> { w: &'a mut W, } impl<'a> AFSEL13_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AFSEL13_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "AF0"] #[inline(always)] pub fn af0(self) -> &'a mut W { self.variant(AFSEL15_A::AF0) } #[doc = "AF1"] #[inline(always)] pub fn af1(self) -> &'a mut W { self.variant(AFSEL15_A::AF1) } #[doc = "AF2"] #[inline(always)] pub fn af2(self) -> &'a mut W { self.variant(AFSEL15_A::AF2) } #[doc = "AF3"] #[inline(always)] pub fn af3(self) -> &'a mut W { self.variant(AFSEL15_A::AF3) } #[doc = "AF4"] #[inline(always)] pub fn af4(self) -> &'a mut W { self.variant(AFSEL15_A::AF4) } #[doc = "AF5"] #[inline(always)] pub fn af5(self) -> &'a mut W { self.variant(AFSEL15_A::AF5) } #[doc = "AF6"] #[inline(always)] pub fn af6(self) -> &'a mut W { self.variant(AFSEL15_A::AF6) } #[doc = "AF7"] #[inline(always)] pub fn af7(self) -> &'a mut W { self.variant(AFSEL15_A::AF7) } #[doc = "AF8"] #[inline(always)] pub fn af8(self) -> &'a mut W { self.variant(AFSEL15_A::AF8) } #[doc = "AF9"] #[inline(always)] pub fn af9(self) -> &'a mut W { self.variant(AFSEL15_A::AF9) } #[doc = "AF10"] #[inline(always)] pub fn af10(self) -> &'a mut W { self.variant(AFSEL15_A::AF10) } #[doc = "AF11"] #[inline(always)] pub fn af11(self) -> &'a mut W { self.variant(AFSEL15_A::AF11) } #[doc = "AF12"] #[inline(always)] pub fn af12(self) -> &'a mut W { self.variant(AFSEL15_A::AF12) } #[doc = "AF13"] #[inline(always)] pub fn af13(self) -> &'a mut W { self.variant(AFSEL15_A::AF13) } #[doc = "AF14"] #[inline(always)] pub fn af14(self) -> &'a mut W { self.variant(AFSEL15_A::AF14) } #[doc = "AF15"] #[inline(always)] pub fn af15(self) -> &'a mut W { self.variant(AFSEL15_A::AF15) } #[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 << 20)) | (((value as u32) & 0x0f) << 20); self.w } } #[doc = "Alternate function selection for port x pin y (y = 8..15)"] pub type AFSEL12_A = AFSEL15_A; #[doc = "Reader of field `AFSEL12`"] pub type AFSEL12_R = crate::R<u8, AFSEL15_A>; #[doc = "Write proxy for field `AFSEL12`"] pub struct AFSEL12_W<'a> { w: &'a mut W, } impl<'a> AFSEL12_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AFSEL12_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "AF0"] #[inline(always)] pub fn af0(self) -> &'a mut W { self.variant(AFSEL15_A::AF0) } #[doc = "AF1"] #[inline(always)] pub fn af1(self) -> &'a mut W { self.variant(AFSEL15_A::AF1) } #[doc = "AF2"] #[inline(always)] pub fn af2(self) -> &'a mut W { self.variant(AFSEL15_A::AF2) } #[doc = "AF3"] #[inline(always)] pub fn af3(self) -> &'a mut W { self.variant(AFSEL15_A::AF3) } #[doc = "AF4"] #[inline(always)] pub fn af4(self) -> &'a mut W { self.variant(AFSEL15_A::AF4) } #[doc = "AF5"] #[inline(always)] pub fn af5(self) -> &'a mut W { self.variant(AFSEL15_A::AF5) } #[doc = "AF6"] #[inline(always)] pub fn af6(self) -> &'a mut W { self.variant(AFSEL15_A::AF6) } #[doc = "AF7"] #[inline(always)] pub fn af7(self) -> &'a mut W { self.variant(AFSEL15_A::AF7) } #[doc = "AF8"] #[inline(always)] pub fn af8(self) -> &'a mut W { self.variant(AFSEL15_A::AF8) } #[doc = "AF9"] #[inline(always)] pub fn af9(self) -> &'a mut W { self.variant(AFSEL15_A::AF9) } #[doc = "AF10"] #[inline(always)] pub fn af10(self) -> &'a mut W { self.variant(AFSEL15_A::AF10) } #[doc = "AF11"] #[inline(always)] pub fn af11(self) -> &'a mut W { self.variant(AFSEL15_A::AF11) } #[doc = "AF12"] #[inline(always)] pub fn af12(self) -> &'a mut W { self.variant(AFSEL15_A::AF12) } #[doc = "AF13"] #[inline(always)] pub fn af13(self) -> &'a mut W { self.variant(AFSEL15_A::AF13) } #[doc = "AF14"] #[inline(always)] pub fn af14(self) -> &'a mut W { self.variant(AFSEL15_A::AF14) } #[doc = "AF15"] #[inline(always)] pub fn af15(self) -> &'a mut W { self.variant(AFSEL15_A::AF15) } #[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 << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Alternate function selection for port x pin y (y = 8..15)"] pub type AFSEL11_A = AFSEL15_A; #[doc = "Reader of field `AFSEL11`"] pub type AFSEL11_R = crate::R<u8, AFSEL15_A>; #[doc = "Write proxy for field `AFSEL11`"] pub struct AFSEL11_W<'a> { w: &'a mut W, } impl<'a> AFSEL11_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AFSEL11_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "AF0"] #[inline(always)] pub fn af0(self) -> &'a mut W { self.variant(AFSEL15_A::AF0) } #[doc = "AF1"] #[inline(always)] pub fn af1(self) -> &'a mut W { self.variant(AFSEL15_A::AF1) } #[doc = "AF2"] #[inline(always)] pub fn af2(self) -> &'a mut W { self.variant(AFSEL15_A::AF2) } #[doc = "AF3"] #[inline(always)] pub fn af3(self) -> &'a mut W { self.variant(AFSEL15_A::AF3) } #[doc = "AF4"] #[inline(always)] pub fn af4(self) -> &'a mut W { self.variant(AFSEL15_A::AF4) } #[doc = "AF5"] #[inline(always)] pub fn af5(self) -> &'a mut W { self.variant(AFSEL15_A::AF5) } #[doc = "AF6"] #[inline(always)] pub fn af6(self) -> &'a mut W { self.variant(AFSEL15_A::AF6) } #[doc = "AF7"] #[inline(always)] pub fn af7(self) -> &'a mut W { self.variant(AFSEL15_A::AF7) } #[doc = "AF8"] #[inline(always)] pub fn af8(self) -> &'a mut W { self.variant(AFSEL15_A::AF8) } #[doc = "AF9"] #[inline(always)] pub fn af9(self) -> &'a mut W { self.variant(AFSEL15_A::AF9) } #[doc = "AF10"] #[inline(always)] pub fn af10(self) -> &'a mut W { self.variant(AFSEL15_A::AF10) } #[doc = "AF11"] #[inline(always)] pub fn af11(self) -> &'a mut W { self.variant(AFSEL15_A::AF11) } #[doc = "AF12"] #[inline(always)] pub fn af12(self) -> &'a mut W { self.variant(AFSEL15_A::AF12) } #[doc = "AF13"] #[inline(always)] pub fn af13(self) -> &'a mut W { self.variant(AFSEL15_A::AF13) } #[doc = "AF14"] #[inline(always)] pub fn af14(self) -> &'a mut W { self.variant(AFSEL15_A::AF14) } #[doc = "AF15"] #[inline(always)] pub fn af15(self) -> &'a mut W { self.variant(AFSEL15_A::AF15) } #[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 << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "Alternate function selection for port x pin y (y = 8..15)"] pub type AFSEL10_A = AFSEL15_A; #[doc = "Reader of field `AFSEL10`"] pub type AFSEL10_R = crate::R<u8, AFSEL15_A>; #[doc = "Write proxy for field `AFSEL10`"] pub struct AFSEL10_W<'a> { w: &'a mut W, } impl<'a> AFSEL10_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AFSEL10_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "AF0"] #[inline(always)] pub fn af0(self) -> &'a mut W { self.variant(AFSEL15_A::AF0) } #[doc = "AF1"] #[inline(always)] pub fn af1(self) -> &'a mut W { self.variant(AFSEL15_A::AF1) } #[doc = "AF2"] #[inline(always)] pub fn af2(self) -> &'a mut W { self.variant(AFSEL15_A::AF2) } #[doc = "AF3"] #[inline(always)] pub fn af3(self) -> &'a mut W { self.variant(AFSEL15_A::AF3) } #[doc = "AF4"] #[inline(always)] pub fn af4(self) -> &'a mut W { self.variant(AFSEL15_A::AF4) } #[doc = "AF5"] #[inline(always)] pub fn af5(self) -> &'a mut W { self.variant(AFSEL15_A::AF5) } #[doc = "AF6"] #[inline(always)] pub fn af6(self) -> &'a mut W { self.variant(AFSEL15_A::AF6) } #[doc = "AF7"] #[inline(always)] pub fn af7(self) -> &'a mut W { self.variant(AFSEL15_A::AF7) } #[doc = "AF8"] #[inline(always)] pub fn af8(self) -> &'a mut W { self.variant(AFSEL15_A::AF8) } #[doc = "AF9"] #[inline(always)] pub fn af9(self) -> &'a mut W { self.variant(AFSEL15_A::AF9) } #[doc = "AF10"] #[inline(always)] pub fn af10(self) -> &'a mut W { self.variant(AFSEL15_A::AF10) } #[doc = "AF11"] #[inline(always)] pub fn af11(self) -> &'a mut W { self.variant(AFSEL15_A::AF11) } #[doc = "AF12"] #[inline(always)] pub fn af12(self) -> &'a mut W { self.variant(AFSEL15_A::AF12) } #[doc = "AF13"] #[inline(always)] pub fn af13(self) -> &'a mut W { self.variant(AFSEL15_A::AF13) } #[doc = "AF14"] #[inline(always)] pub fn af14(self) -> &'a mut W { self.variant(AFSEL15_A::AF14) } #[doc = "AF15"] #[inline(always)] pub fn af15(self) -> &'a mut W { self.variant(AFSEL15_A::AF15) } #[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 << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Alternate function selection for port x pin y (y = 8..15)"] pub type AFSEL9_A = AFSEL15_A; #[doc = "Reader of field `AFSEL9`"] pub type AFSEL9_R = crate::R<u8, AFSEL15_A>; #[doc = "Write proxy for field `AFSEL9`"] pub struct AFSEL9_W<'a> { w: &'a mut W, } impl<'a> AFSEL9_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AFSEL9_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "AF0"] #[inline(always)] pub fn af0(self) -> &'a mut W { self.variant(AFSEL15_A::AF0) } #[doc = "AF1"] #[inline(always)] pub fn af1(self) -> &'a mut W { self.variant(AFSEL15_A::AF1) } #[doc = "AF2"] #[inline(always)] pub fn af2(self) -> &'a mut W { self.variant(AFSEL15_A::AF2) } #[doc = "AF3"] #[inline(always)] pub fn af3(self) -> &'a mut W { self.variant(AFSEL15_A::AF3) } #[doc = "AF4"] #[inline(always)] pub fn af4(self) -> &'a mut W { self.variant(AFSEL15_A::AF4) } #[doc = "AF5"] #[inline(always)] pub fn af5(self) -> &'a mut W { self.variant(AFSEL15_A::AF5) } #[doc = "AF6"] #[inline(always)] pub fn af6(self) -> &'a mut W { self.variant(AFSEL15_A::AF6) } #[doc = "AF7"] #[inline(always)] pub fn af7(self) -> &'a mut W { self.variant(AFSEL15_A::AF7) } #[doc = "AF8"] #[inline(always)] pub fn af8(self) -> &'a mut W { self.variant(AFSEL15_A::AF8) } #[doc = "AF9"] #[inline(always)] pub fn af9(self) -> &'a mut W { self.variant(AFSEL15_A::AF9) } #[doc = "AF10"] #[inline(always)] pub fn af10(self) -> &'a mut W { self.variant(AFSEL15_A::AF10) } #[doc = "AF11"] #[inline(always)] pub fn af11(self) -> &'a mut W { self.variant(AFSEL15_A::AF11) } #[doc = "AF12"] #[inline(always)] pub fn af12(self) -> &'a mut W { self.variant(AFSEL15_A::AF12) } #[doc = "AF13"] #[inline(always)] pub fn af13(self) -> &'a mut W { self.variant(AFSEL15_A::AF13) } #[doc = "AF14"] #[inline(always)] pub fn af14(self) -> &'a mut W { self.variant(AFSEL15_A::AF14) } #[doc = "AF15"] #[inline(always)] pub fn af15(self) -> &'a mut W { self.variant(AFSEL15_A::AF15) } #[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 << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Alternate function selection for port x pin y (y = 8..15)"] pub type AFSEL8_A = AFSEL15_A; #[doc = "Reader of field `AFSEL8`"] pub type AFSEL8_R = crate::R<u8, AFSEL15_A>; #[doc = "Write proxy for field `AFSEL8`"] pub struct AFSEL8_W<'a> { w: &'a mut W, } impl<'a> AFSEL8_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AFSEL8_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "AF0"] #[inline(always)] pub fn af0(self) -> &'a mut W { self.variant(AFSEL15_A::AF0) } #[doc = "AF1"] #[inline(always)] pub fn af1(self) -> &'a mut W { self.variant(AFSEL15_A::AF1) } #[doc = "AF2"] #[inline(always)] pub fn af2(self) -> &'a mut W { self.variant(AFSEL15_A::AF2) } #[doc = "AF3"] #[inline(always)] pub fn af3(self) -> &'a mut W { self.variant(AFSEL15_A::AF3) } #[doc = "AF4"] #[inline(always)] pub fn af4(self) -> &'a mut W { self.variant(AFSEL15_A::AF4) } #[doc = "AF5"] #[inline(always)] pub fn af5(self) -> &'a mut W { self.variant(AFSEL15_A::AF5) } #[doc = "AF6"] #[inline(always)] pub fn af6(self) -> &'a mut W { self.variant(AFSEL15_A::AF6) } #[doc = "AF7"] #[inline(always)] pub fn af7(self) -> &'a mut W { self.variant(AFSEL15_A::AF7) } #[doc = "AF8"] #[inline(always)] pub fn af8(self) -> &'a mut W { self.variant(AFSEL15_A::AF8) } #[doc = "AF9"] #[inline(always)] pub fn af9(self) -> &'a mut W { self.variant(AFSEL15_A::AF9) } #[doc = "AF10"] #[inline(always)] pub fn af10(self) -> &'a mut W { self.variant(AFSEL15_A::AF10) } #[doc = "AF11"] #[inline(always)] pub fn af11(self) -> &'a mut W { self.variant(AFSEL15_A::AF11) } #[doc = "AF12"] #[inline(always)] pub fn af12(self) -> &'a mut W { self.variant(AFSEL15_A::AF12) } #[doc = "AF13"] #[inline(always)] pub fn af13(self) -> &'a mut W { self.variant(AFSEL15_A::AF13) } #[doc = "AF14"] #[inline(always)] pub fn af14(self) -> &'a mut W { self.variant(AFSEL15_A::AF14) } #[doc = "AF15"] #[inline(always)] pub fn af15(self) -> &'a mut W { self.variant(AFSEL15_A::AF15) } #[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 28:31 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel15(&self) -> AFSEL15_R { AFSEL15_R::new(((self.bits >> 28) & 0x0f) as u8) } #[doc = "Bits 24:27 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel14(&self) -> AFSEL14_R { AFSEL14_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 20:23 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel13(&self) -> AFSEL13_R { AFSEL13_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 16:19 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel12(&self) -> AFSEL12_R { AFSEL12_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 12:15 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel11(&self) -> AFSEL11_R { AFSEL11_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 8:11 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel10(&self) -> AFSEL10_R { AFSEL10_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 4:7 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel9(&self) -> AFSEL9_R { AFSEL9_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 0:3 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel8(&self) -> AFSEL8_R { AFSEL8_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bits 28:31 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel15(&mut self) -> AFSEL15_W { AFSEL15_W { w: self } } #[doc = "Bits 24:27 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel14(&mut self) -> AFSEL14_W { AFSEL14_W { w: self } } #[doc = "Bits 20:23 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel13(&mut self) -> AFSEL13_W { AFSEL13_W { w: self } } #[doc = "Bits 16:19 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel12(&mut self) -> AFSEL12_W { AFSEL12_W { w: self } } #[doc = "Bits 12:15 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel11(&mut self) -> AFSEL11_W { AFSEL11_W { w: self } } #[doc = "Bits 8:11 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel10(&mut self) -> AFSEL10_W { AFSEL10_W { w: self } } #[doc = "Bits 4:7 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel9(&mut self) -> AFSEL9_W { AFSEL9_W { w: self } } #[doc = "Bits 0:3 - Alternate function selection for port x pin y (y = 8..15)"] #[inline(always)] pub fn afsel8(&mut self) -> AFSEL8_W { AFSEL8_W { w: self } } }
use wasm_bindgen::JsValue; use wasm_bindgen_test::*; use js_sys::*; #[wasm_bindgen_test] fn length() { fn test(s: &str) { assert_eq!(JsString::from(s).length(), s.len() as u32); } test("Mozilla"); test(""); } #[wasm_bindgen_test] fn char_at() { let s = JsString::from("Brave new world"); assert_eq!(JsValue::from(s.char_at(0)), "B"); assert_eq!(JsValue::from(s.char_at(999)), ""); } #[wasm_bindgen_test] fn char_code_at() { let s = "Brave new world"; let js = JsString::from(s); for (i, b) in s.char_indices() { assert_eq!(js.char_code_at(i as u32), b as u32 as f64); } assert!(js.char_code_at(s.len() as u32).is_nan()); } #[wasm_bindgen_test] fn code_point_at() { assert_eq!(JsString::from("ABC").code_point_at(1), b'B'); assert!(JsString::from("ABC").code_point_at(42).is_undefined()); } #[wasm_bindgen_test] fn concat() { // TODO: Implement ability to receive multiple optional arguments let s = JsString::from("Hello ").concat(&"World".into()); assert_eq!(JsValue::from(s), "Hello World"); let foo = JsString::from("foo"); assert_eq!(JsValue::from(foo.concat(&Object::new().into())), "foo[object Object]"); assert_eq!(JsValue::from(foo.concat(&Array::new().into())), "foo"); assert_eq!(JsValue::from(foo.concat(&JsValue::null())), "foonull"); assert_eq!(JsValue::from(foo.concat(&true.into())), "footrue"); assert_eq!(JsValue::from(foo.concat(&1234.into())), "foo1234"); } #[wasm_bindgen_test] fn ends_with() { let s = "To be, or not to be, that is the question."; let js = JsString::from(s); // TODO: remove third parameter once we have optional parameters assert_eq!(js.ends_with("question.", s.len() as i32), true); assert_eq!(js.ends_with("to be", s.len() as i32), false); assert_eq!(js.ends_with("to be", 19), true); } #[wasm_bindgen_test] fn includes() { let str = JsString::from("Blue Whale"); // TODO: remove second parameter once we have optional parameters assert_eq!(str.includes("Blue", 0), true); assert_eq!(str.includes("Blute", 0), false); assert_eq!(str.includes("Whale", 0), true); assert_eq!(str.includes("Whale", 5), true); assert_eq!(str.includes("Whale", 7), false); assert_eq!(str.includes("", 0), true); assert_eq!(str.includes("", 16), true); } #[wasm_bindgen_test] fn index_of() { let str = JsString::from("Blue Whale"); // TODO: remove second parameter once we have optional parameters assert_eq!(str.index_of("Blue", 0), 0); // TODO: remove second parameter once we have optional parameters assert_eq!(str.index_of("Blute", 0), -1); assert_eq!(str.index_of("Whale", 0), 5); assert_eq!(str.index_of("Whale", 5), 5); assert_eq!(str.index_of("Whale", 7), -1); // TODO: remove second parameter once we have optional parameters assert_eq!(str.index_of("", 0), 0); assert_eq!(str.index_of("", 9), 9); assert_eq!(str.index_of("", 10), 10); assert_eq!(str.index_of("", 11), 10); } #[wasm_bindgen_test] fn last_index_of() { let js = JsString::from("canal"); let len = js.length() as i32; // TODO: remove second parameter once we have optional parameters assert_eq!(js.last_index_of("a", len), 3); assert_eq!(js.last_index_of("a", 2), 1); assert_eq!(js.last_index_of("a", 0), -1); // TODO: remove second parameter once we have optional parameters assert_eq!(js.last_index_of("x", len), -1); assert_eq!(js.last_index_of("c", -5), 0); assert_eq!(js.last_index_of("c", 0), 0); // TODO: remove second parameter once we have optional parameters assert_eq!(js.last_index_of("", len), 5); assert_eq!(js.last_index_of("", 2), 2); } #[wasm_bindgen_test] fn normalize() { let js = JsString::from("\u{1E9B}\u{0323}"); // TODO: Handle undefined assert_eq!(JsValue::from(js.normalize("NFC")), "\u{1E9B}\u{0323}"); assert_eq!(JsValue::from(js.normalize("NFD")), "\u{017F}\u{0323}\u{0307}"); assert_eq!(JsValue::from(js.normalize("NFKC")), "\u{1E69}"); assert_eq!(JsValue::from(js.normalize("NFKD")), "\u{0073}\u{0323}\u{0307}"); } #[wasm_bindgen_test] fn pad_end() { let js = JsString::from("abc"); // TODO: remove second parameter once we have optional parameters assert_eq!(JsValue::from(js.pad_end(10, " ")), "abc "); // TODO: remove second parameter once we have optional parameters assert_eq!(JsValue::from(js.pad_end(10, " ")), "abc "); assert_eq!(JsValue::from(js.pad_end(10, "foo")), "abcfoofoof"); assert_eq!(JsValue::from(js.pad_end(6, "123456")), "abc123"); // TODO: remove second parameter once we have optional parameters assert_eq!(JsValue::from(js.pad_end(1, " ")), "abc"); } #[wasm_bindgen_test] fn pad_start() { let js = JsString::from("abc"); // TODO: remove second parameter once we have optional parameters assert_eq!(js.pad_start(10, " "), " abc"); assert_eq!(js.pad_start(10, "foo"), "foofoofabc"); assert_eq!(js.pad_start(6, "123465"), "123abc"); assert_eq!(js.pad_start(8, "0"), "00000abc"); // TODO: remove second parameter once we have optional parameters assert_eq!(js.pad_start(1, " "), "abc"); } #[wasm_bindgen_test] fn repeat() { assert_eq!(JsString::from("test").repeat(3), "testtesttest"); } #[wasm_bindgen_test] fn slice() { let characters = JsString::from("acxn18"); assert_eq!(characters.slice(1, 3), "cx"); } #[wasm_bindgen_test] fn starts_with() { let js = JsString::from("To be, or not to be, that is the question."); // TODO: remove second parameter for both assertions once we have optional parameters assert!(js.starts_with("To be", 0)); assert!(!js.starts_with("not to be", 0)); assert!(js.starts_with("not to be", 10)); } #[wasm_bindgen_test] fn substring() { let js = JsString::from("Mozilla"); assert_eq!(js.substring(0, 1), "M"); assert_eq!(js.substring(1, 0), "M"); assert_eq!(js.substring(0, 6), "Mozill"); // TODO: Add test once we have optional parameters // assert_eq!(js.substring(4), "lla"); assert_eq!(js.substring(4, 7), "lla"); assert_eq!(js.substring(7, 4), "lla"); assert_eq!(js.substring(0, 7), "Mozilla"); assert_eq!(js.substring(0, 10), "Mozilla"); } #[wasm_bindgen_test] fn substr() { let js = JsString::from("Mozilla"); assert_eq!(js.substr(0, 1), "M"); assert_eq!(js.substr(1, 0), ""); assert_eq!(js.substr(-1, 1), "a"); assert_eq!(js.substr(1, -1), ""); // TODO: Uncomment and test these assertions, once we have support for optional parameters // assert_eq!(js.substr(-3), "lla"); // assert_eq!(js.substr(1), "ozilla"); assert_eq!(js.substr(-20, 2), "Mo"); assert_eq!(js.substr(20, 2), ""); } #[wasm_bindgen_test] fn to_locale_lower_case() { let js = JsString::from("Mozilla"); assert_eq!(js.to_locale_lower_case(None), "mozilla"); let s = JsString::from("\u{0130}"); assert_eq!(s.to_locale_lower_case(Some("tr".into())), "i"); assert_ne!(s.to_locale_lower_case(Some("en-US".into())), "i"); } #[wasm_bindgen_test] fn to_locale_upper_case() { let js = JsString::from("mozilla"); assert_eq!(js.to_locale_upper_case(None), "MOZILLA"); let s = JsString::from("i\u{0307}"); assert_eq!(s.to_locale_upper_case(Some("lt".into())), "I"); assert_ne!(s.to_locale_upper_case(Some("en-US".into())), "I"); } #[wasm_bindgen_test] fn to_lower_case() { assert_eq!(JsString::from("Mozilla").to_lower_case(), "mozilla"); } #[wasm_bindgen_test] fn to_string() { assert_eq!(JsString::from("foo").to_string(), "foo"); } #[wasm_bindgen_test] fn to_upper_case() { assert_eq!(JsString::from("Mozilla").to_upper_case(), "MOZILLA"); } #[wasm_bindgen_test] fn trim() { assert_eq!(JsString::from(" foo ").trim(), "foo"); // Another example of .trim() removing whitespace from just one side. assert_eq!(JsString::from("foo ").trim(), "foo"); } #[wasm_bindgen_test] fn trim_end_and_trim_right() { let greeting = JsString::from(" Hello world! "); let trimmed = " Hello world!"; assert_eq!(greeting.trim_end(), trimmed); assert_eq!(greeting.trim_right(), trimmed); } #[wasm_bindgen_test] fn trim_start_and_trim_left() { let greeting = JsString::from(" Hello world! "); let trimmed = "Hello world! "; assert_eq!(greeting.trim_start(), trimmed); assert_eq!(greeting.trim_left(), trimmed); } #[wasm_bindgen_test] fn value_of() { let greeting = JsString::from("Hello world!"); assert_eq!(greeting.value_of(), "Hello world!"); }
pub fn square_of_sum(n: i64) -> i64 { let sum = (1..(n+1)).fold(0, |acc, x| acc + x); sum * sum } pub fn sum_of_squares(n: i64) -> i64 { (1..(n+1)).map(|x| x * x).fold(0, |acc, x| acc + x) } pub fn difference(n: i64) -> i64 { square_of_sum(n) - sum_of_squares(n) }
use itertools::Itertools; use std::cmp; use std::fmt; use std::path::Display; #[derive(Debug, Clone, Copy, PartialEq)] struct Vec2 { x: i64, y: i64, } #[derive(Copy, Clone, PartialEq, Debug)] enum State { Floor, Empty, Occupied, } #[derive(Clone, Copy, PartialEq)] struct Tile { prev_state: State, new_state: State, pos: Vec2, } impl Tile { fn reset(&mut self) { self.prev_state = self.new_state; } } impl fmt::Display for State { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { State::Floor => write!(f, "."), State::Empty => write!(f, "L"), State::Occupied => write!(f, "#"), } } } struct FloorGrid { tiles: Vec<Tile>, size: Vec2, } impl FloorGrid { fn iter(&self) -> impl Iterator<Item = Tile> + '_ { self.tiles.iter().copied() } } impl FloorGrid { fn index(&self, pos: Vec2) -> Option<usize> { if (0..self.size.x).contains(&pos.x) && (0..self.size.y).contains(&pos.y) { Some((pos.y + pos.x * self.size.y) as _) } else { None } } fn set(&mut self, pos: Vec2, state: State) { // println!("SETTING {} {} {}", pos.x, pos.y, state); if let Some(index) = self.index(pos) { // self.tiles[index].prev_state = self.tiles[index].new_state; self.tiles[index].new_state = state; } } fn reset_state(&mut self, pos: Vec2, _state: State) { if let Some(index) = self.index(pos) { self.tiles[index].prev_state = self.tiles[index].new_state; } } fn neighbor_positions(pos: Vec2) -> impl Iterator<Item = Vec2> { (-1..=1) .cartesian_product(-1..=1) .filter(|&(x, y)| !(x == 0 && y == 0)) .map(move |(dx, dy)| Vec2 { x: pos.x + dx, y: pos.y + dy, }) } fn get(&self, pos: Vec2) -> Option<Tile> { self.index(pos).map(|index| self.tiles[index]) } // Here, we define the sequence using `.curr` and `.next`. // The return type is `Option<T>`: // * When the `Iterator` is finished, `None` is returned. // * Otherwise, the next value is wrapped in `Some` and returned. fn applyRules(&mut self) -> (usize, usize) { let mut occuppied: usize = 0; let copied_vec = self.tiles.to_vec(); let num_changes = copied_vec .iter() .map(|tile| { let occupied_neighbours = FloorGrid::neighbor_positions(tile.pos) .map(|pos| self.get(pos)) .filter_map(|t| t) .filter(|t| t.prev_state == State::Occupied) .count(); let after = match tile.prev_state { State::Empty => { if occupied_neighbours == 0 { occuppied = occuppied + 1; State::Occupied } else { State::Empty } } State::Occupied => { if occupied_neighbours >= 4 { State::Empty } else { occuppied = occuppied + 1; State::Occupied } } State::Floor => State::Floor, }; let changed = if after != tile.prev_state { 1 } else { 0 }; self.set(tile.pos, after); // println!( // "{} {} {} --> {}", // tile.pos.x, tile.pos.y, tile.prev_state, after // ); changed }) .sum(); self.tiles.iter_mut().for_each(|mut t| { t.reset(); }); println!("num_changes {}", num_changes); (num_changes, occuppied) } } impl fmt::Display for FloorGrid { // This trait requires `fmt` with this exact signature. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for i in 0..self.size.x { // println!("{} ", i); for j in 0..self.size.y { let tile = self.get(Vec2 { x: i, y: j }).unwrap(); match tile.prev_state { State::Floor => write!(f, "."), State::Occupied => write!(f, "#"), State::Empty => write!(f, "L"), }; } write!(f, "\n"); } write!(f, "") } } fn read(txt: &str) -> FloorGrid { // let mut grid: Vec<State> = Vec::new(); let mut columns: i64 = 0; let mut rows: i64 = 0; let mut d: Vec<Tile> = Vec::new(); let tiles = txt .chars() .filter_map(|c| { if c == '\n' { rows += 1; columns = 0; None } else { let state = match c { '.' => State::Floor, 'L' => State::Empty, '#' => State::Occupied, _ => State::Empty, }; let tile = Some(Tile { prev_state: state, new_state: state, pos: Vec2 { x: rows, y: columns, }, }); // println!("{} {}", rows, columns); columns += 1; tile } }) .collect(); // txt.split("\n").for_each(|row| { // rows = rows + 1; // cols = 0; // d.push( // row.chars() // .map(|c| { // cols = cols + 1; // match c { // '.' => State::Floor, // 'L' => State::Empty, // '#' => State::Occupied, // _ => State::Empty, // } // }) // .collect(), // ) // }); println!("rows {}", rows); println!("cols {}", columns); FloorGrid { size: Vec2 { x: rows + 1, y: columns, }, tiles, } } pub fn day_eleven() { let mut grid = read(include_str!("../day11.txt")); // println!("{}", grid.into_iter()); // loop { let (num_changes, occupied) = grid.applyRules(); println!("num_changes {} occupied {} ", num_changes, occupied); if num_changes == 0 { break; } } // for (i, state) in grid // .into_iter() // .map(|pos| match pos.0 { // State::Empty => { // if pos.1 == 0 { // State::Occupied // } else { // State::Empty // } // } // State::Occupied => { // if pos.1 >= 4 { // State::Empty // } else { // State::Occupied // } // } // State::Floor => State::Floor, // }) // .enumerate() // { // if i % rows == 0 { // println!(); // } else { // print!("{}", state); // } // } // print!("{}", a); } #[cfg(test)] mod tests { use super::*; #[test] fn test_0() { println!("AAA"); let mut grid = read(include_str!("../day11_test.txt")); let tile = grid.get(Vec2 { x: 0, y: 0 }).unwrap(); assert_eq!(tile.pos.x, 0); assert_eq!(tile.pos.y, 0); assert_eq!(tile.prev_state, State::Empty); println!("{}", grid); // // println!("{}", grid.into_iter().next().unwrap()); let (num_changes, occupied) = grid.applyRules(); println!("{}", grid); assert_eq!( grid.to_string(), include_str!("../day11_test_expected_1.txt").to_owned() ); } #[test] fn test_1() { println!("AAA"); let mut grid = read(include_str!("../day11_test.txt")); println!("{}", grid); // println!("BBBB"); // // println!("{}", grid.into_iter().next().unwrap()); let (num_changes, occupied) = grid.applyRules(); grid.applyRules(); assert_eq!( grid.to_string(), include_str!("../day11_test_expected_2.txt").to_owned() ); } // #[test] // fn test_3() { // vec![1i32, 0, -1i32] // .iter() // .tuple_combinations() // .for_each(|pos| println!("{:?}", pos)) // } // #[test] // fn test_3() { // vec![1i32, 0, -1i32] // .iter() // .tuple_combinations() // .for_each(|pos| println!("{:?}", pos)) // } }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. /// A Start of Authority (SOA) resource record footer. #[repr(C, packed)] #[doc(allow_missing)] pub struct StartOfAuthorityFooter { /// `SERIAL`. /// /// Serial number of the zone file that is incremented each time a change is made. /// /// Best practice is to use `YYYYMMDDnn`, where `YYYY` is the year, `MM` is the month, `DD` is the day, and `nn` is the revision number within the day. pub serial: SerialNumber, /// `REFRESH`. /// /// Refresh interval /// /// Time in seconds that a secondary name server should wait between zone file update checks. /// /// A typical value is between 30 minutes (1,800 seconds) and 2 hours (7,200 seconds). pub refresh_interval: TimeInSeconds, /// `RETRY`. /// /// Retry interval. /// /// Time in seconds that a secondary name server should wait before trying to contact the primary name server again after a failed attempt to check for a zone file update. /// /// A typical value is between 10 minutes (600 seconds) and 1 hour (3,600 seconds), and should take be ***less*** than the `refresh_interval`. pub retry_interval: TimeInSeconds, /// `EXPIRE`. /// /// Expiry interval. /// /// Time in seconds that a secondary name server will treat its zone file as valid when the primary name server cannot be contacted. /// /// A typical value is between 2 weeks (1,209,600 seconds) and 4 weeks (2,419,200 seconds). pub expire_interval: TimeInSeconds, /// `MINIMUM`. /// /// Negative caching time to live. /// /// RFC 2308 redefines this as the time in seconds that any name server or resolver should cache a negative response. pub negative_caching_time_to_live: TimeToLiveInSeconds, }
const CRC_TABLE: [u16; 16] = [ 0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400]; pub fn crc_16(crc: u16, byte: &u8) -> u16 { // compute checksum of lower four bits of byte let mut tmp = CRC_TABLE[(crc & 0x0Fu16) as usize]; let mut out = (crc >> 4) & 0x0FFFu16; out = out ^ tmp ^ CRC_TABLE[(byte & 0x0Fu8) as usize]; // now compute checksum of upper four bits of byte tmp = CRC_TABLE[(out & 0x0Fu16) as usize]; out = (out >> 4) & 0x0FFFu16; out = out ^ tmp ^ CRC_TABLE[((byte >> 4) & 0x0Fu8) as usize]; return out; }
use crate::proto::helloworld::{HelloReply, HelloRequest}; use crate::proto::helloworld_grpc::{Greeter, GreeterServer}; use grpc; pub struct GreeterService; impl Greeter for GreeterService { fn say_hello( &self, _: grpc::RequestOptions, req: HelloRequest, ) -> grpc::SingleResponse<HelloReply> { let mut reply = HelloReply::default(); let name = if req.get_name().is_empty() { "world" } else { req.get_name() }; println!("greeting request from {}", name); reply.set_message(format!("Hello {}", name)); grpc::SingleResponse::completed(reply) } } impl GreeterService { pub fn new() -> grpc::rt::ServerServiceDefinition { GreeterServer::new_service_def(GreeterService) } }
mod btree; use btree::Btree; fn main() { let tfp = "chicchai.db"; let wal = "chicchai.log"; let mut btree = match Btree::<String, String>::new(&tfp.to_string(), &wal.to_string(), 100, 100) { Ok(v) => v, Err(e) => { println!("err {}", e.description()); return; } }; if let Err(e) = btree.insert("hello".to_string(), "world".to_string()) { println!("err {}", e.description()); return; } if let Some(v) = btree.get("hello".to_string()) { println!("value: {}", v); } if let Err(e) = btree.close() { println!("err {}", e); return; } println!("good bye!") }
use std::str::from_utf8; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use crate::decode::Decode; use crate::encode::Encode; use crate::mysql::protocol::TypeId; use crate::mysql::type_info::MySqlTypeInfo; use crate::mysql::{MySql, MySqlData, MySqlValue}; use crate::types::Type; use crate::Error; impl Type<MySql> for i8 { fn type_info() -> MySqlTypeInfo { MySqlTypeInfo::new(TypeId::TINY_INT) } } impl Encode<MySql> for i8 { fn encode(&self, buf: &mut Vec<u8>) { let _ = buf.write_i8(*self); } } impl<'de> Decode<'de, MySql> for i8 { fn decode(value: MySqlValue<'de>) -> crate::Result<Self> { match value.try_get()? { MySqlData::Binary(mut buf) => buf.read_i8().map_err(Into::into), MySqlData::Text(s) => from_utf8(s) .map_err(Error::decode)? .parse() .map_err(Error::decode), } } } impl Type<MySql> for i16 { fn type_info() -> MySqlTypeInfo { MySqlTypeInfo::new(TypeId::SMALL_INT) } } impl Encode<MySql> for i16 { fn encode(&self, buf: &mut Vec<u8>) { let _ = buf.write_i16::<LittleEndian>(*self); } } impl<'de> Decode<'de, MySql> for i16 { fn decode(value: MySqlValue<'de>) -> crate::Result<Self> { match value.try_get()? { MySqlData::Binary(mut buf) => buf.read_i16::<LittleEndian>().map_err(Into::into), MySqlData::Text(s) => from_utf8(s) .map_err(Error::decode)? .parse() .map_err(Error::decode), } } } impl Type<MySql> for i32 { fn type_info() -> MySqlTypeInfo { MySqlTypeInfo::new(TypeId::INT) } } impl Encode<MySql> for i32 { fn encode(&self, buf: &mut Vec<u8>) { let _ = buf.write_i32::<LittleEndian>(*self); } } impl<'de> Decode<'de, MySql> for i32 { fn decode(value: MySqlValue<'de>) -> crate::Result<Self> { match value.try_get()? { MySqlData::Binary(mut buf) => buf.read_i32::<LittleEndian>().map_err(Into::into), MySqlData::Text(s) => from_utf8(s) .map_err(Error::decode)? .parse() .map_err(Error::decode), } } } impl Type<MySql> for i64 { fn type_info() -> MySqlTypeInfo { MySqlTypeInfo::new(TypeId::BIG_INT) } } impl Encode<MySql> for i64 { fn encode(&self, buf: &mut Vec<u8>) { let _ = buf.write_i64::<LittleEndian>(*self); } } impl<'de> Decode<'de, MySql> for i64 { fn decode(value: MySqlValue<'de>) -> crate::Result<Self> { match value.try_get()? { MySqlData::Binary(mut buf) => buf.read_i64::<LittleEndian>().map_err(Into::into), MySqlData::Text(s) => from_utf8(s) .map_err(Error::decode)? .parse() .map_err(Error::decode), } } }
use proc_macro2::TokenStream as TokenStream2; use proc_macro2::{Ident, Span}; use proc_macro_error::{abort, ResultExt}; use syn::{self, ext::IdentExt, spanned::Spanned, Field, Lit, Meta, MetaNameValue, Visibility}; use self::GenMode::*; use super::parse_attr; pub struct GenParams { pub mode: GenMode, pub global_attr: Option<Meta>, } #[derive(PartialEq, Eq, Copy, Clone)] pub enum GenMode { Get, GetCopy, Set, GetMut, } impl GenMode { pub fn name(self) -> &'static str { match self { Get => "get", GetCopy => "get_copy", Set => "set", GetMut => "get_mut", } } pub fn prefix(self) -> &'static str { match self { Get | GetCopy | GetMut => "", Set => "set_", } } pub fn suffix(self) -> &'static str { match self { Get | GetCopy | Set => "", GetMut => "_mut", } } fn is_get(self) -> bool { match self { GenMode::Get | GenMode::GetCopy | GenMode::GetMut => true, GenMode::Set => false, } } } pub fn parse_visibility(attr: Option<&Meta>, meta_name: &str) -> Option<Visibility> { match attr { // `#[get = "pub"]` or `#[set = "pub"]` Some(Meta::NameValue(MetaNameValue { lit: Lit::Str(ref s), path, .. })) => { if path.is_ident(meta_name) { s.value().split(' ').find(|v| *v != "with_prefix").map(|v| { syn::parse_str(v) .map_err(|e| syn::Error::new(s.span(), e)) .expect_or_abort("invalid visibility found") }) } else { None } } _ => None, } } /// Some users want legacy/compatability. /// (Getters are often prefixed with `get_`) fn has_prefix_attr(f: &Field, params: &GenParams) -> bool { let inner = f .attrs .iter() .filter_map(|v| parse_attr(v, params.mode)) .filter(|meta| { ["get", "get_copy"] .iter() .any(|ident| meta.path().is_ident(ident)) }) .last(); // Check it the attr includes `with_prefix` let wants_prefix = |possible_meta: &Option<Meta>| -> bool { match possible_meta { Some(Meta::NameValue(meta)) => { if let Lit::Str(lit_str) = &meta.lit { // Naive tokenization to avoid a possible visibility mod named `with_prefix`. lit_str.value().split(' ').any(|v| v == "with_prefix") } else { false } } _ => false, } }; // `with_prefix` can either be on the local or global attr wants_prefix(&inner) || wants_prefix(&params.global_attr) } pub fn implement(field: &Field, params: &GenParams) -> TokenStream2 { let field_name = field .clone() .ident .unwrap_or_else(|| abort!(field.span(), "Expected the field to have a name")); let fn_name = if !has_prefix_attr(field, params) && (params.mode.is_get()) && params.mode.suffix().is_empty() && field_name.to_string().starts_with("r#") { field_name.clone() } else { Ident::new( &format!( "{}{}{}{}", if has_prefix_attr(field, params) && (params.mode.is_get()) { "get_" } else { "" }, params.mode.prefix(), field_name.unraw(), params.mode.suffix() ), Span::call_site(), ) }; let ty = field.ty.clone(); let doc = field.attrs.iter().filter(|v| { v.parse_meta() .map(|meta| meta.path().is_ident("doc")) .unwrap_or(false) }); let attr = field .attrs .iter() .filter_map(|v| parse_attr(v, params.mode)) .last() .or_else(|| params.global_attr.clone()); let visibility = parse_visibility(attr.as_ref(), params.mode.name()); match attr { // Generate nothing for skipped field. Some(meta) if meta.path().is_ident("skip") => quote! {}, Some(_) => match params.mode { GenMode::Get => { quote! { #(#doc)* #[inline(always)] #visibility fn #fn_name(&self) -> &#ty { &self.#field_name } } } GenMode::GetCopy => { quote! { #(#doc)* #[inline(always)] #visibility fn #fn_name(&self) -> #ty { self.#field_name } } } GenMode::Set => { quote! { #(#doc)* #[inline(always)] #visibility fn #fn_name(&mut self, val: #ty) -> &mut Self { self.#field_name = val; self } } } GenMode::GetMut => { quote! { #(#doc)* #[inline(always)] #visibility fn #fn_name(&mut self) -> &mut #ty { &mut self.#field_name } } } }, // Don't need to do anything. None => quote! {}, } }
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //! Corrections for atmospheric refraction use angle; use std::f64::consts::PI; /** Computes the refraction term for true altitudes greater than 15 degrees # Returns * `refrac_term`: The refraction term *| in radians*, that needs to be subtracted from the apparent altitude to get the true altitude # Arguments * `apprnt_alt`: Apparent altitude *| in radians* **/ pub fn refrac_frm_apprnt_alt_15(apprnt_alt: f64) -> f64 { let x = angle::deg_frm_dms(0, 0, 0.0668).to_radians() * (PI - apprnt_alt).tan(); angle::deg_frm_dms(0, 0, 58.294).to_radians() * (PI - apprnt_alt).tan() - x * x * x } /** Computes the refraction term for apparent altitudes greater than 15 degrees # Returns * `refrac_term`: The refraction term *| in radians*, that needs to be added to the true altitude to get the apparent altitude # Arguments * `true_alt`: True altitude *| in radians* **/ pub fn refrac_frm_true_alt_15(true_alt: f64) -> f64 { let x = angle::deg_frm_dms(0, 0, 0.0824).to_radians() * (PI - true_alt).tan(); angle::deg_frm_dms(0, 0, 58.276).to_radians() * (PI - true_alt).tan() - x * x * x } /** Computes the refraction term for true altitude # Returns * `refrac_term`: The refraction term *| in radians*, that needs to be subtracted from the apparent altitude to get the rue altitude The accuracy of `refrac_term` is upto 0.07 arcminutes. # Arguments * `apprnt_alt`: Apparent altitude *| in radians* **/ pub fn refrac_frm_apprnt_alt(apprnt_alt: f64) -> f64 { if apprnt_alt == PI { 0.0 } else { let apprnt_alt_deg = apprnt_alt.to_degrees(); let a = apprnt_alt_deg + 7.31/(apprnt_alt_deg + 4.4); let R = 1.0 / a.to_radians().tan(); (R / 60.0).to_radians() } } /** Computes the refraction term for apparent altitude This function is consistent with `refrac_frm_apprnt_alt()` to within 4 arcseconds. # Returns * `refrac_term`: The refraction term *| in radians*, that needs to be added to the true altitude to get the apparent altitude # Arguments * `true_alt`: True altitude *| in radians* **/ pub fn refrac_frm_true_alt(true_alt: f64) -> f64 { if true_alt == PI { 0.0 } else { let true_alt_deg = true_alt.to_degrees(); let a = true_alt_deg + 10.3/(true_alt_deg + 5.11); let R = 1.02 / a.to_radians().tan(); (R / 60.0).to_radians() } } /** Computes the refraction term modifier for local pressure # Returns * `refrac_term_modifier`: The value that needs to be multiplied by the refraction term to account for local pressure # Arguments * `pressure`: Local pressure *| in millibars* **/ #[inline(always)] pub fn refrac_by_pressr(pressure: f64) -> f64 { pressure / 1010.0 } /** Computes the refraction term modifier for local temperature # Returns * `refrac_term_modifier`: The value that needs to be multiplied by the refraction term to account for local temperature # Arguments * `temp`: Local temperature *| in kelvins* **/ #[inline(always)] pub fn refrac_by_temp(temp: f64) -> f64 { 283.0 / temp }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![warn(missing_docs)] //! `timekeeper` is responsible for external time synchronization in Fuchsia. mod diagnostics; mod network; mod rtc; use { crate::{ diagnostics::{CobaltDiagnostics, CobaltDiagnosticsImpl, InspectDiagnostics}, network::wait_for_network_available, rtc::{Rtc, RtcImpl}, }, anyhow::{Context as _, Error}, chrono::prelude::*, fidl_fuchsia_deprecatedtimezone as ftz, fidl_fuchsia_netstack as fnetstack, fidl_fuchsia_time as ftime, fuchsia_async::{self as fasync, DurationExt}, fuchsia_component::{ client::{launch, launcher}, server::ServiceFs, }, fuchsia_zircon as zx, futures::StreamExt, log::{debug, error, info, warn}, parking_lot::Mutex, std::cmp, std::sync::Arc, time_metrics_registry::{ self, RealTimeClockEventsMetricDimensionEventType as RtcEventType, TimekeeperLifecycleEventsMetricDimensionEventType as LifecycleEventType, }, }; /// URL of the time source. In the future, this value belongs in a config file. const NETWORK_TIME_SERVICE: &str = "fuchsia-pkg://fuchsia.com/network-time-service#meta/network_time_service.cmx"; #[fasync::run_singlethreaded] async fn main() -> Result<(), Error> { fuchsia_syslog::init_with_tags(&["time"]).context("initializing logging").unwrap(); fuchsia_syslog::set_severity(fuchsia_syslog::levels::INFO); info!("retrieving UTC clock handle"); let time_maintainer = fuchsia_component::client::connect_to_service::<ftime::MaintenanceMarker>().unwrap(); let utc_clock = Arc::new(zx::Clock::from( time_maintainer .get_writable_utc_clock() .await .context("failed to get UTC clock from maintainer")?, )); let mut inspect = InspectDiagnostics::new(diagnostics::INSPECTOR.root(), Arc::clone(&utc_clock)); let mut fs = ServiceFs::new(); info!("diagnostics initialized, serving on servicefs"); diagnostics::INSPECTOR.serve(&mut fs)?; info!("initializing Cobalt"); let mut cobalt = CobaltDiagnosticsImpl::new(); let source = initial_utc_source(&*utc_clock); let notifier = Notifier::new(source); info!("connecting to real time clock"); let optional_rtc = RtcImpl::only_device() .map_err(|err| { warn!("failed to connect to RTC: {}", err); let cobalt_err = err.into(); cobalt.log_rtc_event(cobalt_err); inspect.rtc_initialize(cobalt_err, None); }) .ok(); info!("connecting to external update service"); let launcher = launcher().context("starting launcher")?; let time_app = launch(&launcher, NETWORK_TIME_SERVICE.to_string(), None) .context("launching time service")?; let time_service = time_app.connect_to_service::<ftz::TimeServiceMarker>().unwrap(); let netstack_service = fuchsia_component::client::connect_to_service::<fnetstack::NetstackMarker>().unwrap(); let notifier_clone = notifier.clone(); fasync::Task::spawn(async move { // Keep time_app in the same scope as time_service so the app is not stopped while // we are still using it let _time_app = time_app; maintain_utc( utc_clock, optional_rtc, notifier_clone, time_service, netstack_service, inspect, cobalt, ) .await; }) .detach(); info!("serving notifier on servicefs"); fs.dir("svc").add_fidl_service(move |requests: ftime::UtcRequestStream| { notifier.handle_request_stream(requests); }); fs.take_and_serve_directory_handle()?; Ok(fs.collect().await) } fn initial_utc_source(utc_clock: &zx::Clock) -> ftime::UtcSource { let clock_details = utc_clock.get_details().expect("failed to get UTC clock details"); // When the clock is first initialized to the backstop time, its synthetic offset should // be identical. Once the clock is updated, this is no longer true. if clock_details.backstop.into_nanos() == clock_details.ticks_to_synthetic.synthetic_offset { ftime::UtcSource::Backstop } else { ftime::UtcSource::External } } /// The top-level control loop for time synchronization. /// /// Checks for network connectivity before attempting any time updates. /// /// Actual updates are performed by calls to `fuchsia.deprecatedtimezone.TimeService` which we /// plan to deprecate. async fn maintain_utc<C: CobaltDiagnostics, R: Rtc>( utc_clock: Arc<zx::Clock>, optional_rtc: Option<R>, notifs: Notifier, time_service: ftz::TimeServiceProxy, netstack_service: fnetstack::NetstackProxy, mut inspect: InspectDiagnostics, mut cobalt: C, ) { info!("record the state at initialization."); match initial_utc_source(&*utc_clock) { ftime::UtcSource::Backstop => { cobalt.log_lifecycle_event(LifecycleEventType::InitializedBeforeUtcStart) } ftime::UtcSource::External => { cobalt.log_lifecycle_event(LifecycleEventType::InitializedAfterUtcStart) } } if let Some(rtc) = optional_rtc { info!("reading initial RTC time."); match rtc.get().await { Err(err) => { warn!("failed to read RTC time: {}", err); inspect.rtc_initialize(RtcEventType::ReadFailed, None); cobalt.log_rtc_event(RtcEventType::ReadFailed); } Ok(time) => { info!("initial RTC time: {}", Utc.timestamp_nanos(time.into_nanos())); let backstop = utc_clock.get_details().expect("failed to get UTC clock details").backstop; let status = if time < backstop { RtcEventType::ReadInvalidBeforeBackstop } else { RtcEventType::ReadSucceeded }; inspect.rtc_initialize(status, Some(time)); cobalt.log_rtc_event(status); } } } info!("waiting for network connectivity before attempting network time sync..."); match wait_for_network_available(netstack_service.take_event_stream()).await { Ok(_) => inspect.network_available(), Err(why) => warn!("failed to wait for network, attempted to sync time anyway: {:?}", why), } for i in 0.. { info!("requesting roughtime service update the system time..."); match time_service.update(1).await { Ok(Some(updated_time)) => { let updated_time = zx::Time::from_nanos(updated_time.utc_time); if let Err(status) = utc_clock.update(zx::ClockUpdate::new().value(updated_time)) { error!("failed to update UTC clock to time {:?}: {}", updated_time, status); } inspect.update_clock(); info!("adjusted UTC time to {}", Utc.timestamp_nanos(updated_time.into_nanos())); let monotonic_before = zx::Time::get(zx::ClockId::Monotonic).into_nanos(); let utc_now = Utc::now().timestamp_nanos(); let monotonic_after = zx::Time::get(zx::ClockId::Monotonic).into_nanos(); info!( "CF-884:monotonic_before={}:utc={}:monotonic_after={}", monotonic_before, utc_now, monotonic_after, ); if notifs.0.lock().set_source(ftime::UtcSource::External, monotonic_before) { cobalt.log_lifecycle_event(LifecycleEventType::StartedUtcFromTimeSource); } break; } Ok(None) => { debug!( "failed to update time, probably a network error. retrying in {}s.", backoff_duration(i).into_seconds() ); } Err(why) => { error!("couldn't make request to update time: {:?}", why); } } fasync::Timer::new(backoff_duration(i).after_now()).await; } } /// Returns the duration for which time synchronization should wait after failing to synchronize /// time. `attempt_index` is a zero-based index of the failed attempt, i.e. after the third failed /// attempt `attempt_index` = 2. fn backoff_duration(attempt_index: u32) -> zx::Duration { // We make three tries at each interval before doubling, but never exceed 8 seconds (ie 2^3). const TRIES_PER_EXPONENT: u32 = 3; const MAX_EXPONENT: u32 = 3; let exponent = cmp::min(attempt_index / TRIES_PER_EXPONENT, MAX_EXPONENT); zx::Duration::from_seconds(2i64.pow(exponent)) } /// Notifies waiting clients when the clock has been updated, wrapped in a lock to allow /// sharing between tasks. #[derive(Clone, Debug)] struct Notifier(Arc<Mutex<NotifyInner>>); impl Notifier { fn new(source: ftime::UtcSource) -> Self { Notifier(Arc::new(Mutex::new(NotifyInner { source, clients: Vec::new() }))) } /// Spawns an async task to handle requests on this channel. fn handle_request_stream(&self, requests: ftime::UtcRequestStream) { let notifier = self.clone(); fasync::Task::spawn(async move { let mut counted_requests = requests.enumerate(); let mut last_seen_state = notifier.0.lock().source; while let Some((request_count, Ok(ftime::UtcRequest::WatchState { responder }))) = counted_requests.next().await { let mut n = notifier.0.lock(); // we return immediately if this is the first request on this channel, or if there // has been a new update since the last request. if request_count == 0 || last_seen_state != n.source { n.reply(responder, zx::Time::get(zx::ClockId::Monotonic).into_nanos()); } else { n.register(responder); } last_seen_state = n.source; } }) .detach(); } } /// Notifies waiting clients when the clock has been updated. #[derive(Debug)] struct NotifyInner { /// The current source for our UTC approximation. source: ftime::UtcSource, /// All clients waiting for an update to UTC's time. clients: Vec<ftime::UtcWatchStateResponder>, } impl NotifyInner { /// Reply to a client with the current UtcState. fn reply(&self, responder: ftime::UtcWatchStateResponder, update_time: i64) { if let Err(why) = responder .send(ftime::UtcState { timestamp: Some(update_time), source: Some(self.source) }) { warn!("failed to notify a client of an update: {:?}", why); } } /// Registers a client to be later notified that a clock update has occurred. fn register(&mut self, responder: ftime::UtcWatchStateResponder) { info!("registering a client for notifications"); self.clients.push(responder); } /// Increases the revision counter by 1 and notifies any clients waiting on updates from /// previous revisions, returning true iff the source changed as a result of the call. fn set_source(&mut self, source: ftime::UtcSource, update_time: i64) -> bool { if self.source != source { self.source = source; let clients = std::mem::replace(&mut self.clients, vec![]); info!("UTC source changed to {:?}, notifying {} clients", source, clients.len()); for responder in clients { self.reply(responder, update_time); } true } else { info!("received UTC source update but the actual source didn't change."); false } } } #[cfg(test)] mod tests { use { super::*, crate::rtc::FakeRtc, fuchsia_inspect::Inspector, fuchsia_zircon as zx, lazy_static::lazy_static, matches::assert_matches, std::{ future::Future, task::{Context, Poll}, }, }; lazy_static! { static ref BACKSTOP_TIME: zx::Time = zx::Time::from_nanos(111111); static ref RTC_TIME: zx::Time = zx::Time::from_nanos(222222); static ref UPDATE_TIME: zx::Time = zx::Time::from_nanos(333333); } #[fasync::run_singlethreaded(test)] async fn single_client() { let clock = Arc::new(zx::Clock::create(zx::ClockOpts::empty(), Some(*BACKSTOP_TIME)).unwrap()); clock.update(zx::ClockUpdate::new().value(*BACKSTOP_TIME)).unwrap(); let initial_update_ticks = clock.get_details().unwrap().last_value_update_ticks; let inspector = Inspector::new(); let inspect_diagnostics = diagnostics::InspectDiagnostics::new(inspector.root(), Arc::clone(&clock)); let (cobalt_diagnostics, mut cobalt_monitor) = diagnostics::FakeCobaltDiagnostics::new(); info!("starting single notification test"); let (utc, utc_requests) = fidl::endpoints::create_proxy_and_stream::<ftime::UtcMarker>().unwrap(); let (time_service, mut time_requests) = fidl::endpoints::create_proxy_and_stream::<ftz::TimeServiceMarker>().unwrap(); let netstack_service = network::create_event_service_with_valid_interface(); let notifier = Notifier::new(ftime::UtcSource::Backstop); let (mut allow_update, mut wait_for_update) = futures::channel::mpsc::channel(1); info!("spawning test notifier"); notifier.handle_request_stream(utc_requests); fasync::Task::spawn(maintain_utc( Arc::clone(&clock), Some(FakeRtc::valid(*RTC_TIME)), notifier.clone(), time_service, netstack_service, inspect_diagnostics, cobalt_diagnostics, )) .detach(); fasync::Task::spawn(async move { while let Some(Ok(ftz::TimeServiceRequest::Update { responder, .. })) = time_requests.next().await { let () = wait_for_update.next().await.unwrap(); responder .send(Some(&mut ftz::UpdatedTime { utc_time: UPDATE_TIME.into_nanos() })) .unwrap(); } }) .detach(); info!("checking that the time source has not been externally initialized yet"); assert_eq!(utc.watch_state().await.unwrap().source.unwrap(), ftime::UtcSource::Backstop); info!("checking that the clock has not been updated yet"); assert_eq!(initial_update_ticks, clock.get_details().unwrap().last_value_update_ticks); info!("checking that the initial state was logged to Cobalt"); cobalt_monitor.assert_lifecycle_events(&[LifecycleEventType::InitializedBeforeUtcStart]); cobalt_monitor.reset(); let task_waker = futures::future::poll_fn(|cx| Poll::Ready(cx.waker().clone())).await; let mut cx = Context::from_waker(&task_waker); let mut hanging = Box::pin(utc.watch_state()); assert!( hanging.as_mut().poll(&mut cx).is_pending(), "hanging get should not return before time updated event has been emitted" ); info!("sending network update event"); allow_update.try_send(()).unwrap(); info!("waiting for time source update"); assert_eq!(hanging.await.unwrap().source.unwrap(), ftime::UtcSource::External); assert!(clock.get_details().unwrap().last_value_update_ticks > initial_update_ticks); info!("checking that the started clock was logged to Cobalt"); cobalt_monitor.assert_lifecycle_events(&[LifecycleEventType::StartedUtcFromTimeSource]); } #[fasync::run_singlethreaded(test)] async fn initial_utc_source_initialized() { let clock = zx::Clock::create(zx::ClockOpts::empty(), Some(zx::Time::from_nanos(1_000))).unwrap(); // The clock must be started with an initial value. clock.update(zx::ClockUpdate::new().value(zx::Time::from_nanos(1_000))).unwrap(); let source = initial_utc_source(&clock); assert_matches!(source, ftime::UtcSource::Backstop); // Update the clock, which is already running. clock.update(zx::ClockUpdate::new().value(zx::Time::from_nanos(1_000_000))).unwrap(); let source = initial_utc_source(&clock); assert_matches!(source, ftime::UtcSource::External); } #[test] fn backoff_sequence_matches_expectation() { let expectation = vec![1, 1, 1, 2, 2, 2, 4, 4, 4, 8, 8, 8, 8, 8]; for i in 0..expectation.len() { let expected = zx::Duration::from_seconds(expectation[i]); let actual = backoff_duration(i as u32); assert_eq!( actual, expected, "backoff after iteration {} should be {:?} but was {:?}", i, expected, actual ); } } }
// 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. //! AccountManager manages the overall state of Fuchsia accounts and personae on //! a Fuchsia device, installation of the AuthProviders that are used to obtain //! authentication tokens for these accounts, and access to TokenManagers for //! these accounts. //! //! The AccountManager is the most powerful interface in the authentication //! system and is intended only for use by the most trusted parts of the system. #![deny(warnings)] #![deny(missing_docs)] #![feature(async_await, await_macro, futures_api)] mod account_handler_connection; mod account_handler_context; mod account_manager; use crate::account_manager::AccountManager; use failure::{Error, ResultExt}; use fidl::endpoints::{RequestStream, ServiceMarker}; use fidl_fuchsia_auth_account::{AccountManagerMarker, AccountManagerRequestStream}; use fuchsia_app::server::ServicesServer; use fuchsia_async as fasync; use log::{error, info}; use std::sync::Arc; // Default accounts directory const ACCOUNT_DIR_PARENT: &str = "/data/account"; fn main() -> Result<(), Error> { fuchsia_syslog::init_with_tags(&["auth"]).expect("Can't init logger"); info!("Starting account manager"); let mut executor = fasync::Executor::new().context("Error creating executor")?; // TODO(dnorsdtrom): Add CLI arg for making the path configurable, to support test isolation let account_manager = AccountManager::new(ACCOUNT_DIR_PARENT).map_err(|e| { error!("Error initializing AccountManager {:?}", e); e })?; let account_manager = Arc::new(account_manager); let fut = ServicesServer::new() .add_service((AccountManagerMarker::NAME, move |chan| { let account_manager_clone = Arc::clone(&account_manager); fasync::spawn( async move { let stream = AccountManagerRequestStream::from_channel(chan); await!(account_manager_clone.handle_requests_from_stream(stream)) .unwrap_or_else(|e| error!("Error handling AccountManager channel {:?}", e)) }, ); })) .start() .context("Error starting AccountManager server")?; executor.run_singlethreaded(fut).context("Failed to execute AccountManager future")?; info!("Stopping account manager"); Ok(()) }
// This file is Copyright its original authors, visible in version control // history. // // This file is 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. // You may not use this file except in accordance with one or both of these // licenses. use std::{fs, io}; use bitcoin::Network; use serde::{Deserialize, Serialize}; use serde_json::Value; #[derive(Clone)] pub enum P2PConfig { Local, Remote(String, String), RapidGossipSync(String), } #[derive(Clone, Serialize, Deserialize)] pub struct SenseiConfig { #[serde(skip)] pub path: String, pub bitcoind_rpc_host: String, pub bitcoind_rpc_port: u16, pub bitcoind_rpc_username: String, pub bitcoind_rpc_password: String, pub network: Network, pub api_host: String, pub api_port: u16, pub port_range_min: u16, pub port_range_max: u16, pub database_url: String, pub remote_p2p_host: Option<String>, pub remote_p2p_token: Option<String>, pub remote_chain_host: Option<String>, pub remote_chain_token: Option<String>, pub gossip_peers: String, pub instance_name: String, pub http_notifier_url: Option<String>, pub http_notifier_token: Option<String>, pub region: Option<String>, pub poll_for_chain_updates: bool, pub rapid_gossip_sync_server_host: Option<String>, } impl Default for SenseiConfig { fn default() -> Self { let home_dir = dirs::home_dir().unwrap_or_else(|| ".".into()); let path = format!("{}/.sensei/config.json", home_dir.to_str().unwrap()); Self { path, bitcoind_rpc_host: String::from("127.0.0.1"), bitcoind_rpc_port: 8133, bitcoind_rpc_username: String::from("bitcoin"), bitcoind_rpc_password: String::from("bitcoin"), network: Network::Bitcoin, api_host: String::from("127.0.0.1"), api_port: 5401, port_range_min: 10000, port_range_max: 65535, database_url: String::from("sensei.db"), remote_p2p_host: None, remote_p2p_token: None, remote_chain_host: None, remote_chain_token: None, gossip_peers: String::from(""), instance_name: String::from("sensei"), http_notifier_url: None, http_notifier_token: None, region: None, poll_for_chain_updates: true, rapid_gossip_sync_server_host: None, } } } impl SenseiConfig { pub fn from_file(path: String, merge_with: Option<SenseiConfig>) -> Self { let mut merge_config = merge_with.unwrap_or_default(); merge_config.path = path.clone(); match fs::read_to_string(path.clone()) { Ok(config_str) => { let mut merge_config_value = serde_json::to_value(merge_config).unwrap(); let merge_config_map = merge_config_value.as_object_mut().unwrap(); let mut config_value: Value = serde_json::from_str(&config_str).expect("failed to parse configuration file"); let config_map = config_value .as_object_mut() .expect("failed to parse configuration file"); merge_config_map.append(config_map); serde_json::from_value(merge_config_value).unwrap() } Err(e) => match e.kind() { io::ErrorKind::NotFound => { fs::write( path, serde_json::to_string(&merge_config) .expect("failed to serialize default config"), ) .expect("failed to write default config"); // write merge_config to path merge_config } _ => { panic!("failed to read configuration file"); } }, } } pub fn set_network(&mut self, network: Network) { self.network = network; } pub fn save(&mut self) { fs::write( self.path.clone(), serde_json::to_string(&self).expect("failed to serialize config"), ) .expect("failed to write config"); } pub fn get_p2p_config(&self) -> P2PConfig { if self.remote_p2p_configured() { P2PConfig::Remote( self.remote_p2p_host.as_ref().unwrap().clone(), self.remote_p2p_token.as_ref().unwrap().clone(), ) } else if self.rapid_gossip_sync_configured() { P2PConfig::RapidGossipSync(self.rapid_gossip_sync_server_host.as_ref().unwrap().clone()) } else { P2PConfig::Local } } pub fn remote_p2p_configured(&self) -> bool { self.remote_p2p_host.is_some() && self.remote_p2p_token.is_some() } pub fn rapid_gossip_sync_configured(&self) -> bool { self.rapid_gossip_sync_server_host.is_some() } }
use std::convert::TryInto; use std::io; fn main() { let mut buf = String::new(); let stdin = io::stdin(); stdin .read_line(&mut buf) .expect("Failed to read first line."); buf.clear(); stdin .read_line(&mut buf) .expect("Failed to read paper list."); let mut papers: Vec<u8> = buf.split_whitespace().map(|x| x.parse().unwrap()).collect(); println!("{}", max_expected_rpi(&mut papers)); } fn max_expected_rpi(papers: &mut Vec<u8>) -> f64 { papers.sort_unstable(); papers.reverse(); eprintln!("D: {:?}", papers); let mut max_rpi: f64 = 0.0; for s in 1..papers.len() + 1 { let rpi: f64 = expected_rpi(papers, s); eprintln!("D: expected_rpi={} for s={}", rpi, s); if rpi <= max_rpi { eprintln!("D: Breaking due to {} <= {}", rpi, max_rpi); break; } max_rpi = rpi; } return max_rpi; } fn expected_rpi(papers: &Vec<u8>, n: usize) -> f64 { eprintln!("D: Getting expected_rpi for s={}", n); let mut weighted_rpi: f64 = 0.0; for k in 1..n + 1 { let p: f64 = prob_k(papers, n, k); let rpik = rpi(k.try_into().unwrap(), n.try_into().unwrap()); eprintln!("D: | p={} and rpi={} for k={}", p, rpik, k); weighted_rpi += p * rpik; } return weighted_rpi; } fn prob_k(papers: &Vec<u8>, n: usize, k: usize) -> f64 { return prob_ki(papers, n, k, 0); } fn prob_ki(papers: &Vec<u8>, n: usize, k: usize, i: usize) -> f64 { let mut p: f64 = 1.0; // It's impossible to achieve this. if k > n - i { return 0.0; } // None can be true. if k == 0 { for j in i..n { p *= 1.0 - papers[j] as f64 / 100.0; } return p; } // All have to be true. if k == n - i { for j in i..n { p *= papers[j] as f64 / 100.0; } return p; } let p1: f64 = papers[i] as f64 / 100.0; let p0: f64 = 1.0 - p1; return p0 * prob_ki(papers, n, k, i + 1) + p1 * prob_ki(papers, n, k - 1, i + 1); } fn rpi(a: u32, s: u32) -> f64 { if a == 0 { return 0.0; } let a = f64::from(a); let s = f64::from(s); return a.powf(a / s); }
//! Human-readable logging and statuses. // TODO: Sort the tags while converting `&[&TagParam]` to `Vec<Tag>`. use chrono::{Local, TimeZone, Utc}; use chrono::format::DelayedFormat; use chrono::format::strftime::StrftimeItems; use crossbeam::queue::SegQueue; use serde_json::{Value as Json}; use std::cell::RefCell; use std::collections::VecDeque; use std::default::Default; use std::fs; use std::fmt; use std::fmt::Write as WriteFmt; use std::io::{Seek, SeekFrom, Write}; use std::mem::swap; use std::os::raw::c_char; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard}; use std::thread; use super::{now_ms, writeln}; #[cfg(feature = "native")] lazy_static! { static ref PRINTF_LOCK: Mutex<()> = Mutex::new(()); /// If this C callback is present then all the logging output should happen through it /// (and leaving stdout untouched). /// The *gravity* logging still gets a copy in order for the log-based tests to work. pub static ref LOG_OUTPUT: Mutex<Option<extern fn (line: *const c_char)>> = Mutex::new (None); } /// Initialized and used when there's a need to chute the logging into a given thread. struct Gravity { /// The center of gravity, the thread where the logging should reach the `println!` output. target_thread_id: thread::ThreadId, /// Log chunks received from satellite threads. landing: SegQueue<String>, /// Keeps a portiong of a recently flushed gravity log in RAM for inspection by the unit tests. tail: Mutex<VecDeque<String>> } impl Gravity { /// Files a log chunk to be logged from the center of gravity thread. #[cfg(feature = "native")] fn chunk2log (&self, chunk: String) { self.landing.push (chunk); if thread::current().id() == self.target_thread_id { self.flush() } } #[cfg(not(feature = "native"))] fn chunk2log (&self, chunk: String) { writeln (&chunk); self.landing.push (chunk); } /// Prints the collected log chunks. /// `println!` is used for compatibility with unit test stdout capturing. #[cfg(feature = "native")] fn flush (&self) { let mut tail = self.tail.lock(); while let Ok (chunk) = self.landing.pop() { let logged_with_log_output = LOG_OUTPUT.lock().map (|l| l.is_some()) .unwrap_or (false); if !logged_with_log_output { writeln (&chunk) } if let Ok (ref mut tail) = tail { if tail.len() == tail.capacity() {let _ = tail.pop_front();} tail.push_back (chunk) } } } #[cfg(not(feature = "native"))] fn flush (&self) {} } thread_local! { /// If set, pulls the `chunk2log` (aka `log!`) invocations into the gravity of another thread. static GRAVITY: RefCell<Option<Arc<Gravity>>> = RefCell::new (None) } #[cfg(feature = "native")] #[doc(hidden)] pub fn chunk2log (mut chunk: String) { let used_log_output = if let Ok (log_output) = LOG_OUTPUT.lock() { if let Some (log_cb) = *log_output { chunk.push ('\0'); log_cb (chunk.as_ptr() as *const c_char); true } else {false} } else {false}; // NB: Using gravity even in the non-capturing tests in order to give the tests access to the gravity tail. let rc = GRAVITY.try_with (|gravity| { if let Some (ref gravity) = *gravity.borrow() { let mut chunkʹ = String::new(); swap (&mut chunk, &mut chunkʹ); gravity.chunk2log (chunkʹ); true } else { false } }); match rc {Ok (true) => return, _ => ()} if used_log_output {return} writeln (&chunk) } #[cfg(not(feature = "native"))] #[doc(hidden)] pub fn chunk2log (chunk: String) { writeln (&chunk) } #[doc(hidden)] pub fn short_log_time() -> DelayedFormat<StrftimeItems<'static>> { // NB: Given that the debugging logs are targeted at the developers and not the users // I think it's better to output the time in UTC here // in order for the developers to more easily match the events between the various parts of the peer-to-peer system. let time = Utc.timestamp_millis (now_ms() as i64); time.format ("%d %H:%M:%S") } /// Debug logging. /// /// This logging SHOULD be human-readable but it is not intended for the end users specifically. /// Rather, it's being used as debugging and testing tool. /// /// (As such it doesn't have to be a text paragraph, the capital letters and end marks are not necessary). /// /// For the user-targeted logging use the `LogState::log` instead. /// /// On Windows the Rust standard output and the standard output of the MM1 C library are not compatible, /// they will overlap and overwrite each other if used togather. /// In order to avoid it, all logging MUST be done through this macros and NOT through `println!` or `eprintln!`. #[macro_export] macro_rules! log { ($($args: tt)+) => {{ use std::fmt::Write; // We can optimize this with a stack-allocated SmallVec from https://github.com/arcnmx/stack-rs, // though it doesn't worth the trouble at the moment. let mut buf = String::new(); unwrap! (wite! (&mut buf, ($crate::log::short_log_time()) if cfg! (feature = "native") {", "} else {"ʷ "} (::gstuff::filename (file!())) ':' (line!()) "] " $($args)+) ); $crate::log::chunk2log (buf) }} } pub trait TagParam<'a> { fn key (&self) -> String; fn val (&self) -> Option<String>; } impl<'a> TagParam<'a> for &'a str { fn key (&self) -> String {String::from (&self[..])} fn val (&self) -> Option<String> {None} } impl<'a> TagParam<'a> for String { fn key (&self) -> String {self.clone()} fn val (&self) -> Option<String> {None} } impl<'a> TagParam<'a> for (&'a str, &'a str) { fn key (&self) -> String {String::from (self.0)} fn val (&self) -> Option<String> {Some (String::from (self.1))} } impl<'a> TagParam<'a> for (String, &'a str) { fn key (&self) -> String { self.0.clone() } fn val (&self) -> Option<String> {Some (String::from (self.1))} } impl<'a> TagParam<'a> for (&'a str, i32) { fn key (&self) -> String {String::from (self.0)} fn val (&self) -> Option<String> {Some (fomat! ((self.1)))} } #[derive(Clone, Eq, PartialEq)] pub struct Tag { pub key: String, pub val: Option<String> } impl Tag { /// Returns the tag's value or the empty string if there is no value. pub fn val_s (&self) -> &str { match self.val { Some (ref s) => &s[..], None => "" } } } impl fmt::Debug for Tag { fn fmt (&self, ft: &mut fmt::Formatter) -> fmt::Result { ft.write_str (&self.key) ?; if let Some (ref val) = self.val { ft.write_str ("=") ?; ft.write_str (val) ?; } Ok(()) } } /// The status entry kept in the dashboard. #[derive(Clone)] pub struct Status { pub tags: Vec<Tag>, pub line: String, // Might contain the previous versions of the status. pub trail: Vec<Status> } #[derive(Clone)] pub struct LogEntry { pub time: u64, pub emotion: String, pub tags: Vec<Tag>, pub line: String, /// If the log entry represents a finished `Status` then `trail` might contain the previous versions of that `Status`. pub trail: Vec<Status> } impl Default for LogEntry { fn default() -> Self { LogEntry { time: now_ms(), emotion: Default::default(), tags: Default::default(), line: Default::default(), trail: Default::default(), } } } impl LogEntry { pub fn format (&self, buf: &mut String) -> Result<(), fmt::Error> { let time = Local.timestamp_millis (self.time as i64); wite! (buf, if self.emotion.is_empty() {'·'} else {(self.emotion)} ' ' (time.format ("%Y-%m-%d %H:%M:%S %z")) ' ' // TODO: JSON-escape the keys and values when necessary. '[' for t in &self.tags {(t.key) if let Some (ref v) = t.val {'=' (v)}} separated {' '} "] " (self.line) for tr in self.trail.iter().rev() { "\n " (tr.line) } ) } } /// Tracks the status of an ongoing operation, allowing us to inform the user of the status updates. /// /// Dropping the handle tells us that the operation was "finished" and that we can dump the final status into the log. pub struct StatusHandle<'a> { log: &'a LogState, status: Option<Arc<Mutex<Status>>> } impl<'a> StatusHandle<'a> { /// Creates the status or rewrites it. /// /// The `tags` can be changed as well: /// with `StatusHandle` the status line is directly identified by the handle and doesn't use the tags to lookup the status line. pub fn status<'b> (&mut self, tags: &[&dyn TagParam], line: &str) { let mut stack_status = Status { tags: tags.iter().map (|t| Tag {key: t.key(), val: t.val()}) .collect(), line: line.into(), trail: Vec::new() }; if let Some (ref status) = self.status { { let mut shared_status = unwrap! (status.lock(), "Can't lock the status"); // Skip a status update if it is equal to the previous update. if shared_status.line == stack_status.line && shared_status.tags == stack_status.tags {return} swap (&mut stack_status, &mut shared_status); swap (&mut stack_status.trail, &mut shared_status.trail); // Move the existing `trail` back to the `shared_status`. shared_status.trail.push (stack_status); } self.log.updated (status); } else { let status = Arc::new (Mutex::new (stack_status)); self.status = Some (status.clone()); self.log.started (status); } } /// Adds new text into the status line. /// Does nothing if the status handle is empty (if the status wasn't created yet). pub fn append (&self, suffix: &str) { if let Some (ref status) = self.status { { let mut status = unwrap! (status.lock(), "Can't lock the status"); status.line.push_str (suffix) } self.log.updated (status); } } /// Detach the handle from the status, allowing the status to remain in the dashboard when the handle is dropped. /// /// The code should later manually finish the status (finding it with `LogState::find_status`). pub fn detach (&mut self) -> &mut Self { self.status = None; self } } impl<'a> Drop for StatusHandle<'a> { fn drop (&mut self) { if let Some (ref status) = self.status { self.log.finished (status) } } } /// Generates a MM dashboard file path from the MM log file path. pub fn dashboard_path (log_path: &Path) -> Result<PathBuf, String> { let log_path = try_s! (log_path.to_str().ok_or ("Non-unicode log_path?")); Ok (format! ("{}.dashboard", log_path) .into()) } /// The shared log state of a MarketMaker instance. /// Carried around by the MarketMaker state, `MmCtx`. /// Keeps track of the log file and the status dashboard. pub struct LogState { dashboard: Mutex<Vec<Arc<Mutex<Status>>>>, /// Keeps recent log entries in memory in case we need them for debugging. /// Should allow us to examine the log from withing the unit tests, core dumps and live debugging sessions. tail: Mutex<VecDeque<LogEntry>>, /// Initialized when we need the logging to happen through a certain thread /// (this thread becomes a center of gravity for the other registered threads). /// In the future we might also use `gravity` to log into a file. gravity: Mutex<Option<Arc<Gravity>>>, /// Dashboard is dumped here, allowing us to easily observe it from a command-line or the tests. /// No dumping if `None`. dashboard_file: Option<Mutex<fs::File>> } impl LogState { /// Log into memory, for unit testing. pub fn in_memory() -> LogState { LogState { dashboard: Mutex::new (Vec::new()), tail: Mutex::new (VecDeque::with_capacity (64)), gravity: Mutex::new (None), dashboard_file: None } } /// Initialize according to the MM command-line configuration. pub fn mm (conf: &Json) -> LogState { let dashboard_file = match conf["log"] { Json::Null => None, Json::String (ref path) => { let dashboard_path = unwrap! (dashboard_path (Path::new (&path))); let dashboard_file = unwrap! ( fs::OpenOptions::new().write (true) .create (true) .open (&dashboard_path), "Can't open dashboard file {:?}", dashboard_path ); Some (Mutex::new (dashboard_file)) }, ref x => panic! ("The 'log' is not a string: {:?}", x) }; LogState { dashboard: Mutex::new (Vec::new()), tail: Mutex::new (VecDeque::with_capacity (64)), gravity: Mutex::new (None), dashboard_file } } /// The operation is considered "in progress" while the `StatusHandle` exists. /// /// When the `StatusHandle` is dropped the operation is considered "finished" (possibly with a failure) /// and the status summary is dumped into the log. pub fn status_handle (&self) -> StatusHandle { StatusHandle { log: self, status: None } } fn dump_dashboard (&self, dashboard: MutexGuard<Vec<Arc<Mutex<Status>>>>) { if dashboard.len() == 0 {return} let df = match self.dashboard_file {Some (ref df) => df, None => return}; let mut buf = String::with_capacity (dashboard.len() * 256); let mut locked = Vec::new(); for status in dashboard.iter() { if let Ok (status) = status.try_lock() { let _ = writeln! (&mut buf, "{:?} {}", status.tags, status.line); } else { locked.push (status.clone()) } } drop (dashboard); // Unlock the dashboard. for status in locked { if let Ok (status) = status.lock() { let _ = writeln! (&mut buf, "{:?} {}", status.tags, status.line); } else { log! ("dump_dashboard] Can't lock a status") } } let mut df = match df.lock() {Ok (lock) => lock, Err (err) => {log! ({"dump_dashboard] Can't lock the file: {}", err}); return}}; if let Err (err) = df.seek (SeekFrom::Start (0)) {log! ({"dump_dashboard] Can't seek the file: {}", err}); return} if let Err (err) = df.write_all (buf.as_bytes()) {log! ({"dump_dashboard] Can't write the file: {}", err}); return} if let Err (err) = df.set_len (buf.len() as u64) {log! ({"dump_dashboard] Can't truncate the file: {}", err}); return} } /// Invoked when the `StatusHandle` gets the first status. fn started (&self, status: Arc<Mutex<Status>>) { match self.dashboard.lock() { Ok (mut dashboard) => { dashboard.push (status); self.dump_dashboard (dashboard) }, Err (err) => log! ({"log] Can't lock the dashboard: {}", err}) } } /// Invoked when the `StatusHandle` updates the status. fn updated (&self, _status: &Arc<Mutex<Status>>) { match self.dashboard.lock() { Ok (dashboard) => self.dump_dashboard (dashboard), Err (err) => log! ({"log] Can't lock the dashboard: {}", err}) } } /// Invoked when the `StatusHandle` is dropped, marking the status as finished. fn finished (&self, status: &Arc<Mutex<Status>>) { match self.dashboard.lock() { Ok (mut dashboard) => { if let Some (idx) = dashboard.iter().position (|e| Arc::ptr_eq (e, status)) { dashboard.swap_remove (idx); self.dump_dashboard (dashboard) } else { log! ("log] Warning, a finished StatusHandle was missing from the dashboard."); } }, Err (err) => log! ({"log] Can't lock the dashboard: {}", err}) } let mut status = match status.lock() { Ok (status) => status, Err (err) => { log! ({"log] Can't lock the status: {}", err}); return } }; let chunk = match self.tail.lock() { Ok (mut tail) => { if tail.len() == tail.capacity() {let _ = tail.pop_front();} let mut log = LogEntry::default(); swap (&mut log.tags, &mut status.tags); swap (&mut log.line, &mut status.line); swap (&mut log.trail, &mut status.trail); let mut chunk = String::with_capacity (256); if let Err (err) = log.format (&mut chunk) { log! ({"log] Error formatting log entry: {}", err}); } tail.push_back (log); Some (chunk) }, Err (err) => { log! ({"log] Can't lock the tail: {}", err}); None } }; if let Some (chunk) = chunk {self.chunk2log (chunk)} } /// Read-only access to the status dashboard. pub fn with_dashboard (&self, cb: &mut dyn FnMut (&[Arc<Mutex<Status>>])) { let dashboard = unwrap! (self.dashboard.lock(), "Can't lock the dashboard"); cb (&dashboard[..]) } pub fn with_tail (&self, cb: &mut dyn FnMut (&VecDeque<LogEntry>)) { let tail = unwrap! (self.tail.lock(), "Can't lock the tail"); cb (&*tail) } pub fn with_gravity_tail (&self, cb: &mut dyn FnMut (&VecDeque<String>)) { let gravity = unwrap! (self.gravity.lock(), "Can't lock the gravity"); if let Some (ref gravity) = *gravity { gravity.flush(); let tail = unwrap! (gravity.tail.lock(), "Can't lock the tail"); cb (&*tail) } } /// Creates the status or rewrites it if the tags match. pub fn status<'b> (&self, tags: &[&dyn TagParam], line: &str) -> StatusHandle { let mut status = self.claim_status (tags) .unwrap_or (self.status_handle()); status.status (tags, line); status } /// Search dashboard for status matching the tags. /// /// Note that returned status handle represent an ownership of the status and on the `drop` will mark the status as finished. pub fn claim_status (&self, tags: &[&dyn TagParam]) -> Option<StatusHandle> { let mut found = Vec::new(); let mut locked = Vec::new(); let tags: Vec<Tag> = tags.iter().map (|t| Tag {key: t.key(), val: t.val()}) .collect(); let dashboard = unwrap! (self.dashboard.lock(), "Can't lock the dashboard"); for status_arc in &*dashboard { if let Ok (ref status) = status_arc.try_lock() { if status.tags == tags {found.push (StatusHandle { log: self, status: Some (status_arc.clone()) })} } else { locked.push (status_arc.clone()) } } drop (dashboard); // Unlock the dashboard before lock-waiting on statuses, avoiding a chance of deadlock. for status_arc in locked { let matches = unwrap! (status_arc.lock(), "Can't lock a status") .tags == tags; if matches {found.push (StatusHandle { log: self, status: Some (status_arc) })} } if found.len() > 1 {log! ("log] Dashboard tags not unique!")} found.pop() } /// Returns `true` if there are recent log entries exactly matching the tags. pub fn tail_any (&self, tags: &[&dyn TagParam]) -> bool { let tags: Vec<Tag> = tags.iter().map (|t| Tag {key: t.key(), val: t.val()}) .collect(); let tail = match self.tail.lock() {Ok (l) => l, _ => return false}; for en in tail.iter() { if en.tags == tags { return true } } return false } /// Creates a new human-readable log entry. /// /// This is a bit different from the `println!` logging /// (https://www.reddit.com/r/rust/comments/9hpk65/which_tools_are_you_using_to_debug_rust_projects/e6dkciz/) /// as the information here is intended for the end users /// (and to be shared through the GUI), /// explaining what's going on with MM. /// /// Since the focus here is on human-readability, the log entry SHOULD be treated /// as a text paragraph, namely starting with a capital letter and ending with an end mark. /// /// * `emotion` - We might use a unicode smiley here /// (https://unicode.org/emoji/charts/full-emoji-list.html) /// to emotionally color the event (the good, the bad and the ugly) /// or enrich it with infographics. /// * `tags` - Parsable part of the log, /// representing subsystems and sharing concrete values. /// GUI might use it to get some useful information from the log. /// * `line` - The human-readable description of the event, /// we have no intention to make it parsable. pub fn log (&self, emotion: &str, tags: &[&dyn TagParam], line: &str) { let entry = LogEntry { time: now_ms(), emotion: emotion.into(), tags: tags.iter().map (|t| Tag {key: t.key(), val: t.val()}) .collect(), line: line.into(), trail: Vec::new() }; let mut chunk = String::with_capacity (256); if let Err (err) = entry.format (&mut chunk) { log! ({"log] Error formatting log entry: {}", err}); return } match self.tail.lock() { Ok (mut tail) => { if tail.len() == tail.capacity() {let _ = tail.pop_front();} tail.push_back (entry) }, Err (err) => log! ({"log] Can't lock the tail: {}", err}) } self.chunk2log (chunk) } fn chunk2log (&self, chunk: String) { self::chunk2log (chunk) /* match self.log_file { Some (ref f) => match f.lock() { Ok (mut f) => { if let Err (err) = f.write (chunk.as_bytes()) { eprintln! ("log] Can't write to the log: {}", err); println! ("{}", chunk); } }, Err (err) => { eprintln! ("log] Can't lock the log: {}", err); println! ("{}", chunk) } }, None => println! ("{}", chunk) } */ } /// Writes into the *raw* portion of the log, the one not shared with the UI. pub fn rawln (&self, mut line: String) { line.push ('\n'); self.chunk2log (line); } /// Binds the logger to the current thread, /// creating a gravity anomaly that would pull log entries made on other threads into this thread. /// Useful for unit tests, since they can only capture the output made from the initial test thread /// (https://github.com/rust-lang/rust/issues/12309, /// https://github.com/rust-lang/rust/issues/50297#issuecomment-388988381). #[cfg(feature = "native")] pub fn thread_gravity_on (&self) -> Result<(), String> { let mut gravity = try_s! (self.gravity.lock()); if let Some (ref gravity) = *gravity { if gravity.target_thread_id == thread::current().id() { Ok(()) } else { ERR! ("Gravity already enabled and for a different thread") } } else { *gravity = Some (Arc::new (Gravity { target_thread_id: thread::current().id(), landing: SegQueue::new(), tail: Mutex::new (VecDeque::with_capacity (64)) })); Ok(()) } } #[cfg(not(feature = "native"))] pub fn thread_gravity_on (&self) -> Result<(), String> {Ok(())} /// Start intercepting the `log!` invocations happening on the current thread. #[cfg(feature = "native")] pub fn register_my_thread (&self) -> Result<(), String> { let gravity = try_s! (self.gravity.lock()); if let Some (ref gravity) = *gravity { try_s! (GRAVITY.try_with (|thread_local_gravity| { thread_local_gravity.replace (Some (gravity.clone())) })); } else { // If no gravity thread is registered then `register_my_thread` is currently a no-op. // In the future we might implement a version of `Gravity` that pulls log entries into a file // (but we might want to get rid of C logging first). } Ok(()) } #[cfg(not(feature = "native"))] pub fn register_my_thread (&self) -> Result<(), String> {Ok(())} } #[cfg(feature = "native")] impl Drop for LogState { fn drop (&mut self) { // Make sure to log the chunks received from the satellite threads. // NB: The `drop` might happen in a thread that is not the center of gravity, // resulting in log chunks escaping the unit test capture. // One way to fight this might be adding a flushing RAII struct into a unit test. // NB: The `drop` will not be happening if some of the satellite threads still hold to the context. let mut gravity_arc = None; // Variable is used in order not to hold two locks. if let Ok (gravity) = self.gravity.lock() { if let Some (ref gravity) = *gravity { gravity_arc = Some (gravity.clone()) } } if let Some (gravity) = gravity_arc { gravity.flush() } let dashboard_copy = { let dashboard = match self.dashboard.lock() { Ok (d) => d, Err (err) => {log! ({"LogState::drop] Can't lock `dashboard`: {}", err}); return} }; dashboard.clone() }; if dashboard_copy.len() > 0 { log! ("--- LogState] Bye! Remaining status entries. ---"); for status in &*dashboard_copy {self.finished (status)} } else { log! ("LogState] Bye!"); } } } #[doc(hidden)] pub mod tests { use super::LogState; pub fn test_status() { let log = LogState::in_memory(); log.with_dashboard (&mut |dashboard| assert_eq! (dashboard.len(), 0)); let mut handle = log.status_handle(); for n in 1..=3 { handle.status (&[&"tag1", &"tag2"], &format! ("line {}", n)); log.with_dashboard (&mut |dashboard| { assert_eq! (dashboard.len(), 1); let status = unwrap! (dashboard[0].lock()); assert! (status.tags.iter().any (|tag| tag.key == "tag1")); assert! (status.tags.iter().any (|tag| tag.key == "tag2")); assert_eq! (status.tags.len(), 2); assert_eq! (status.line, format! ("line {}", n)); }); } drop (handle); log.with_dashboard (&mut |dashboard| assert_eq! (dashboard.len(), 0)); // The status was dumped into the log. log.with_tail (&mut |tail| { assert_eq! (tail.len(), 1); assert_eq! (tail[0].line, "line 3"); assert! (tail[0].trail.iter().any (|status| status.line == "line 2")); assert! (tail[0].trail.iter().any (|status| status.line == "line 1")); assert! (tail[0].tags.iter().any (|tag| tag.key == "tag1")); assert! (tail[0].tags.iter().any (|tag| tag.key == "tag2")); assert_eq! (tail[0].tags.len(), 2); }) } }
mod task; use sea_orm::*; use std::env; use task::Entity as Task; type Error = Box<dyn std::error::Error>; #[async_std::main] async fn main() -> Result<(), Error> { let db_url = env::var("DB_URL")?; let db = Database::connect(db_url).await?; let rows = Task::find().all(&db).await?; println!("{:?}", rows); Ok(()) }
// Creates a basic neuron with 3 inputs. // Associated YT NNFS tutorial: https://www.youtube.com/watch?v=Wo5dMEP_BbI fn main() { let inputs = vec![1.0, 2.0, 3.0]; let weights = vec![3.1, 2.1, 8.7]; let bias = 3.0; let output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias; println!("{}", output); }
mod separable_sss; pub use separable_sss::*; mod ssss_utils; pub use ssss_utils::*;
use audio_core::ReadBuf; use audio_core::Translate as _; use audio_device::alsa; use audio_generator::{self as gen, Generator as _}; fn generate_audio() -> anyhow::Result<()> { let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; let config = pcm.configure::<i16>().install()?; let mut writer = pcm.writer::<i16>()?; dbg!(config); let sample_rate = config.rate as f32; let channels = config.channels as usize; let mut a = gen::Sine::new(261.63, sample_rate); let mut b = gen::Sine::new(329.63, sample_rate); let mut c = gen::Sine::new(440.00, sample_rate); let mut buf = [0i16; 16 * 1024]; loop { for o in (0..buf.len()).step_by(channels) { let s = i16::translate((a.sample() + b.sample() + c.sample()) * 0.01); for c in 0..channels { buf[o + c] = s; } } let mut buf = audio::wrap::interleaved(&buf[..], channels); while buf.has_remaining() { writer.write_interleaved(&mut buf)?; } } } fn main() -> anyhow::Result<()> { let bg = ste::spawn(); bg.submit(generate_audio)?; bg.join(); Ok(()) }
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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. // Test that we do not leak when the arg pattern must drop part of the // argument (in this case, the `y` field). #![feature(box_syntax)] struct Foo { x: Box<usize>, y: Box<usize>, } fn foo(Foo {x, ..}: Foo) -> *const usize { let addr: *const usize = &*x; addr } pub fn main() { let obj: Box<_> = box 1; let objptr: *const usize = &*obj; let f = Foo {x: obj, y: box 2}; let xptr = foo(f); assert_eq!(objptr, xptr); }
pub mod flight_provider; pub mod flight_provider_request; mod raw_models;
use super::*; use nix::{ioctl_none, ioctl_readwrite, ioctl_write_ptr}; pub type nvme_admin_cmd = nvme_passthru_cmd; // #define NVME_IOCTL_ID _IO('N', 0x40) // #define NVME_IOCTL_ADMIN_CMD _IOWR('N', 0x41, struct nvme_admin_cmd) // #define NVME_IOCTL_SUBMIT_IO _IOW('N', 0x42, struct nvme_user_io) // #define NVME_IOCTL_IO_CMD _IOWR('N', 0x43, struct nvme_passthru_cmd) // #define NVME_IOCTL_RESET _IO('N', 0x44) // #define NVME_IOCTL_SUBSYS_RESET _IO('N', 0x45) // #define NVME_IOCTL_RESCAN _IO('N', 0x46) ioctl_none!(nvme_ioctl_id, b'N', 0x40); ioctl_readwrite!(nvme_ioctl_admin_cmd, b'N', 0x41, nvme_admin_cmd); ioctl_write_ptr!(nvme_ioctl_submit_io, b'N', 0x42, nvme_user_io); ioctl_readwrite!(nvme_ioctl_io_cmd, b'N', 0x43, nvme_passthru_cmd); ioctl_none!(nvme_ioctl_reset, b'N', 0x44); ioctl_none!(nvme_ioctl_subsys_reset, b'N', 0x45); ioctl_none!(nvme_ioctl_rescan, b'N', 0x46);
use crate::chunked::ChunkedDecoder; use async_dup::{Arc, Mutex}; use async_std::io::{BufReader, Read, Take}; use async_std::task::{Context, Poll}; use std::{fmt::Debug, io, pin::Pin}; pub enum BodyReader<IO: Read + Unpin> { Chunked(Arc<Mutex<ChunkedDecoder<BufReader<IO>>>>), Fixed(Arc<Mutex<Take<BufReader<IO>>>>), None, } impl<IO: Read + Unpin> Debug for BodyReader<IO> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { BodyReader::Chunked(_) => f.write_str("BodyReader::Chunked"), BodyReader::Fixed(_) => f.write_str("BodyReader::Fixed"), BodyReader::None => f.write_str("BodyReader::None"), } } } impl<IO: Read + Unpin> Read for BodyReader<IO> { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { match &*self { BodyReader::Chunked(r) => Pin::new(&mut *r.lock()).poll_read(cx, buf), BodyReader::Fixed(r) => Pin::new(&mut *r.lock()).poll_read(cx, buf), BodyReader::None => Poll::Ready(Ok(0)), } } }
//! This module provides unified diff functionality. //! //! It is available for as long as the `text` feature is enabled which //! is enabled by default: //! //! ```rust //! use similar::TextDiff; //! # let old_text = ""; //! # let new_text = ""; //! let text_diff = TextDiff::from_lines(old_text, new_text); //! print!("{}", text_diff //! .unified_diff() //! .context_radius(10) //! .header("old_file", "new_file")); //! ``` //! //! # Unicode vs Bytes //! //! The [`UnifiedDiff`] type supports both unicode and byte diffs for all //! types compatible with [`DiffableStr`]. You can pick between the two //! versions by using the [`Display`](std::fmt::Display) implementation or //! [`UnifiedDiff`] or [`UnifiedDiff::to_writer`]. //! //! The former uses [`DiffableStr::to_string_lossy`], the latter uses //! [`DiffableStr::as_bytes`] for each line. #[cfg(feature = "text")] use std::{fmt, io}; use crate::iter::AllChangesIter; use crate::text::{DiffableStr, TextDiff}; use crate::types::{Algorithm, DiffOp}; struct MissingNewlineHint(bool); impl fmt::Display for MissingNewlineHint { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.0 { write!(f, "\n\\ No newline at end of file")?; } Ok(()) } } #[derive(Copy, Clone, Debug)] struct UnifiedDiffHunkRange(usize, usize); impl UnifiedDiffHunkRange { fn start(&self) -> usize { self.0 } fn end(&self) -> usize { self.1 } } impl fmt::Display for UnifiedDiffHunkRange { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut beginning = self.start() + 1; let len = self.end().saturating_sub(self.start()); if len == 1 { write!(f, "{}", beginning) } else { if len == 0 { // empty ranges begin at line just before the range beginning -= 1; } write!(f, "{},{}", beginning, len) } } } /// Unified diff hunk header formatter. pub struct UnifiedHunkHeader { old_range: UnifiedDiffHunkRange, new_range: UnifiedDiffHunkRange, } impl UnifiedHunkHeader { /// Creates a hunk header from a (non empty) slice of diff ops. pub fn new(ops: &[DiffOp]) -> UnifiedHunkHeader { let first = ops[0]; let last = ops[ops.len() - 1]; let old_start = first.old_range().start; let new_start = first.new_range().start; let old_end = last.old_range().end; let new_end = last.new_range().end; UnifiedHunkHeader { old_range: UnifiedDiffHunkRange(old_start, old_end), new_range: UnifiedDiffHunkRange(new_start, new_end), } } } impl fmt::Display for UnifiedHunkHeader { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "@@ -{} +{} @@", &self.old_range, &self.new_range) } } /// Unified diff formatter. /// /// ```rust /// use similar::TextDiff; /// # let old_text = ""; /// # let new_text = ""; /// let text_diff = TextDiff::from_lines(old_text, new_text); /// print!("{}", text_diff /// .unified_diff() /// .context_radius(10) /// .header("old_file", "new_file")); /// ``` /// /// ## Unicode vs Bytes /// /// The [`UnifiedDiff`] type supports both unicode and byte diffs for all /// types compatible with [`DiffableStr`]. You can pick between the two /// versions by using [`UnifiedDiff.to_string`] or [`UnifiedDiff.to_writer`]. /// The former uses [`DiffableStr::to_string_lossy`], the latter uses /// [`DiffableStr::as_bytes`] for each line. pub struct UnifiedDiff<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> { diff: &'diff TextDiff<'old, 'new, 'bufs, T>, context_radius: usize, missing_newline_hint: bool, header: Option<(String, String)>, } impl<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> UnifiedDiff<'diff, 'old, 'new, 'bufs, T> { /// Creates a formatter from a text diff object. pub fn from_text_diff(diff: &'diff TextDiff<'old, 'new, 'bufs, T>) -> Self { UnifiedDiff { diff, context_radius: 3, missing_newline_hint: true, header: None, } } /// Changes the context radius. /// /// The context radius is the number of lines between changes that should /// be emitted. This defaults to `3`. pub fn context_radius(&mut self, n: usize) -> &mut Self { self.context_radius = n; self } /// Sets a header to the diff. /// /// `a` and `b` are the file names that are added to the top of the unified /// file format. The names are accepted verbatim which lets you encode /// a timestamp into it when separated by a tab (`\t`). For more information /// see [the unified diff format specification](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/diff.html#tag_20_34_10_07) pub fn header(&mut self, a: &str, b: &str) -> &mut Self { self.header = Some((a.to_string(), b.to_string())); self } /// Controls the missing newline hint. /// /// By default a special `\ No newline at end of file` marker is added to /// the output when a file is not terminated with a final newline. This can /// be disabled with this flag. pub fn missing_newline_hint(&mut self, yes: bool) -> &mut Self { self.missing_newline_hint = yes; self } /// Iterates over all hunks as configured. pub fn iter_hunks(&self) -> impl Iterator<Item = UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T>> { let diff = self.diff; let missing_newline_hint = self.missing_newline_hint; self.diff .grouped_ops(self.context_radius) .into_iter() .filter(|ops| !ops.is_empty()) .map(move |ops| UnifiedDiffHunk::new(ops, diff, missing_newline_hint)) } /// Write the unified diff as bytes to the output stream. pub fn to_writer<W: io::Write>(&self, mut w: W) -> Result<(), io::Error> where 'diff: 'old + 'new + 'bufs, { let mut header = self.header.as_ref(); for hunk in self.iter_hunks() { if let Some((old_file, new_file)) = header.take() { writeln!(w, "--- {}", old_file)?; writeln!(w, "+++ {}", new_file)?; } write!(w, "{}", hunk)?; } Ok(()) } fn header_opt(&mut self, header: Option<(&str, &str)>) -> &mut Self { if let Some((a, b)) = header { self.header(a, b); } self } } /// Unified diff hunk formatter. /// /// The `Display` this renders out a single unified diff's hunk. pub struct UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> { diff: &'diff TextDiff<'old, 'new, 'bufs, T>, ops: Vec<DiffOp>, missing_newline_hint: bool, } impl<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T> { /// Creates a new hunk for some operations. pub fn new( ops: Vec<DiffOp>, diff: &'diff TextDiff<'old, 'new, 'bufs, T>, missing_newline_hint: bool, ) -> UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T> { UnifiedDiffHunk { diff, ops, missing_newline_hint, } } /// Returns the header for the hunk. pub fn header(&self) -> UnifiedHunkHeader { UnifiedHunkHeader::new(&self.ops) } /// Returns all operations in the hunk. pub fn ops(&self) -> &[DiffOp] { &self.ops } /// Returns the value of the `missing_newline_hint` flag. pub fn missing_newline_hint(&self) -> bool { self.missing_newline_hint } /// Iterates over all changes in a hunk. pub fn iter_changes<'x, 'slf>(&'slf self) -> AllChangesIter<'slf, 'x, T> where 'x: 'slf + 'old + 'new, 'old: 'x, 'new: 'x, { AllChangesIter::new(self.diff.old_slices(), self.diff.new_slices(), self.ops()) } /// Write the hunk as bytes to the output stream. pub fn to_writer<W: io::Write>(&self, mut w: W) -> Result<(), io::Error> where 'diff: 'old + 'new + 'bufs, { for (idx, change) in self.iter_changes().enumerate() { if idx == 0 { writeln!(w, "{}", self.header())?; } write!(w, "{}", change.tag())?; w.write_all(change.value().as_bytes())?; if !self.diff.newline_terminated() { writeln!(w)?; } if self.diff.newline_terminated() && change.missing_newline() { writeln!(w, "{}", MissingNewlineHint(self.missing_newline_hint))?; } } Ok(()) } } impl<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> fmt::Display for UnifiedDiffHunk<'diff, 'old, 'new, 'bufs, T> where 'diff: 'old + 'new + 'bufs, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (idx, change) in self.iter_changes().enumerate() { if idx == 0 { writeln!(f, "{}", self.header())?; } write!(f, "{}{}", change.tag(), change.to_string_lossy())?; if !self.diff.newline_terminated() { writeln!(f)?; } if self.diff.newline_terminated() && change.missing_newline() { writeln!(f, "{}", MissingNewlineHint(self.missing_newline_hint))?; } } Ok(()) } } impl<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> fmt::Display for UnifiedDiff<'diff, 'old, 'new, 'bufs, T> where 'diff: 'old + 'new + 'bufs, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut header = self.header.as_ref(); for hunk in self.iter_hunks() { if let Some((old_file, new_file)) = header.take() { writeln!(f, "--- {}", old_file)?; writeln!(f, "+++ {}", new_file)?; } write!(f, "{}", hunk)?; } Ok(()) } } /// Quick way to get a unified diff as string. /// /// `n` configures [`UnifiedDiff::context_radius`] and /// `header` configures [`UnifiedDiff::header`] when not `None`. pub fn unified_diff<'old, 'new>( alg: Algorithm, old: &'old str, new: &'new str, n: usize, header: Option<(&str, &str)>, ) -> String { TextDiff::configure() .algorithm(alg) .diff_lines(old, new) .unified_diff() .context_radius(n) .header_opt(header) .to_string() } #[test] fn test_unified_diff() { let diff = TextDiff::from_lines( "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\nx\ny\nz\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ", "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\nS\nt\nu\nv\nw\nx\ny\nz\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\no\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ", ); insta::assert_snapshot!(&diff.unified_diff().header("a.txt", "b.txt").to_string()); } #[test] fn test_empty_unified_diff() { let diff = TextDiff::from_lines("abc", "abc"); assert_eq!(diff.unified_diff().header("a.txt", "b.txt").to_string(), ""); } #[test] fn test_unified_diff_newline_hint() { let diff = TextDiff::from_lines("a\n", "b"); insta::assert_snapshot!(&diff.unified_diff().header("a.txt", "b.txt").to_string()); insta::assert_snapshot!(&diff .unified_diff() .missing_newline_hint(false) .header("a.txt", "b.txt") .to_string()); }
use rlua::{Lua}; use scripting::{ScriptTable}; use {Error}; /// Keeps track of the scripting engine and data in it. pub struct ScriptRuntime { lua: Lua, } impl ScriptRuntime { /// Creates a new runtime. pub fn new() -> Self { let lua = Lua::new(); ScriptRuntime { lua, } } pub(crate) fn set_model(&self, model: &ScriptTable) -> Result<(), Error> { let globals = self.lua.globals(); let model_table = model.to_lua_table(&self.lua)?; globals.set("model", model_table)?; Ok(()) } pub(crate) fn eval_bool(&self, source: &str) -> Result<bool, Error> { let value = self.lua.eval(source, None)?; Ok(value) } pub(crate) fn eval_integer(&self, source: &str) -> Result<i32, Error> { let value = self.lua.eval(source, None)?; Ok(value) } pub(crate) fn eval_float(&self, source: &str) -> Result<f32, Error> { let value = self.lua.eval(source, None)?; Ok(value) } pub(crate) fn eval_string(&self, source: &str) -> Result<String, Error> { let value = self.lua.eval(source, None)?; Ok(value) } }
use aoc2018::*; use std::str; fn main() -> Result<(), Error> { // only read once so we can use references into it to avoid copying the string. let lines = lines!(input!("day3.txt"), String, Skip, Pair<u32, u32>, Pair<u32, u32>) .collect::<Result<Vec<_>, Error>>()?; let mut duplicates = 0; // map out who owns each claim. let mut claimed_by = HashMap::<_, Vec<&str>>::new(); let mut nonoverlapping = HashSet::new(); for line in &lines { let (ref id, _, ref b, ref c) = *line; nonoverlapping.insert(id.as_str()); for x in b.0..b.0.saturating_add(c.0) { for y in b.1..b.1.saturating_add(c.1) { let m = claimed_by.entry((x, y)).or_default(); m.push(id.as_str()); if m.len() == 2 { duplicates += 1; } if m.len() > 1 { for remove in m { nonoverlapping.remove(remove); } } } } } let nonoverlapping = nonoverlapping.into_iter().collect::<Vec<_>>(); assert_eq!(duplicates, 104712); assert_eq!(nonoverlapping, vec!["#840"]); Ok(()) }
fn main() { //if else statement let number = 3; if number < 5 { println!("condition was true"); } else { println!("condition was false"); } // if else if let anothernumber = 6; if anothernumber % 4 == 0 { println!("number is divisible by 4"); } else if anothernumber % 3 == 0 { println!("number is divisible by 3"); } else if anothernumber % 2 == 0 { println!("number is divisible by 2"); } else { println!("number is not divisible by 4, 3, or 2"); } //if statement in let let condition = true; let yetanothernumber = if condition { 5 } else { 6 }; println!("The value of number is: {}", yetanothernumber); //while loop let mut countdownnum = 5; while countdownnum > 0 { println!("{}!", countdownnum); countdownnum -= 1; } println!("LIFTOFF!!!"); //for loop for i in 0..10 { println!("{}", i); } //reversed for loop for number in (1..4).rev() { println!("{}!", number); } println!("LIFTOFF!!!"); //for loop for iterating through array let a = [10, 20, 30, 40, 50]; for element in a.iter() { println!("the value is: {}", element); } }
use serde::{Deserialize, Serialize}; use std::convert::TryInto; lazy_static! { static ref REQUEST_HEADER_SIZE: u64 = bincode::serialized_size(&RequestHeader::default()) .expect("Unable to get size of default RequestHeader."); } /// All possible algorithms that can be requested. #[allow(non_camel_case_types)] #[derive(Serialize, Deserialize, PartialEq, Clone, Copy)] #[repr(C)] pub enum Algorithm { NoAlgorithm, FRODO640__ECDHp256, FRODO640, FRODO976__ECDHp384, FRODO976, FRODO1344__ECDHp521, FRODO1344, NTRU_HRSS_701, NTRU_HRSS_701__ECDHp256, NTRU_HPS_2048509, NTRU_HPS_2048509__ECDHp256, RND5_1CCA_5D, RND5_1CCA_5D__ECDHp256, RND5_3CCA_5D, RND5_3CCA_5D__ECDHp384, RND5_5CCA_5D, RND5_5CCA_5D__ECDHp521, KYBER_512, KYBER_512__ECDHp256, KYBER_768, KYBER_768__ECDHp384, KYBER_1024, KYBER_1024__ECDHp521, SABER_LIGHT, SABER_LIGHT__ECDHp256, SABER, SABER__ECDHp384, SABER_FIRE, SABER_FIRE__ECDHp521, } /// All possible operations that can be requested. #[derive(Serialize, Deserialize, PartialEq)] #[repr(C)] pub enum Operation { NoOperation, KeypairGeneration, Encapsulation, Decapsulation, } // Necessary so we can get a default size of RequestHeader at run-time so C knows // what size buffer to allocate. impl Default for Algorithm { fn default() -> Self { Algorithm::NoAlgorithm } } impl Default for Operation { fn default() -> Self { Operation::NoOperation } } // Ensure that RequestHeader always has a fixed size! If this size changes then change version number! /// Header that describes the request sent. /// # Explanation of the header /// - version is used for compatibility reasons. Typically there is no need to do anything with this /// as pq_message_lib deals with version internally. /// - identifier is used so that the receiver of the `RequestHeader` can link it back to the original request. /// - data_len describes the length of the upcoming data that belongs to this `RequestHeader`. The data after that /// will belong to a new `RequestHeader`. /// - algorithm is the `Algorithm` that the request is about. /// - operation is the `Operation` that the request is about. #[derive(Serialize, Deserialize, Default, PartialEq)] pub struct RequestHeader { pub version: u8, pub identifier: u64, pub data_len: u32, pub algorithm: Algorithm, pub operation: Operation, } /// Convenience struct to allow request body to be stored together together with the header. pub struct Request { pub header: RequestHeader, pub body: Vec<u8>, } /// Returns the size needed for the buffer where the serialized request header will be stored. /// Will evaluate only when used for the first time. #[no_mangle] pub extern "C" fn get_serialized_request_header_size() -> u64 { *REQUEST_HEADER_SIZE } /// Receive a serialized header. Simply attach the raw bytes behind this serialized header when sending /// over a channel. /// # Returns /// 0 on success, -1 on serialization failure. /// # Safety /// Ensure that `target_buffer` is large enough before executing this function. #[no_mangle] pub unsafe extern "C" fn serialize_request_header( target_buffer: *mut libc::c_uchar, target_buffer_len: libc::size_t, identifier: u64, data_len: u32, algorithm: Algorithm, operation: Operation, ) -> i16 { if target_buffer.is_null() || target_buffer_len < get_serialized_request_header_size() as usize { return -1; } let request_header = RequestHeader { version: crate::FORMAT_VERSION, identifier, data_len, algorithm, operation, }; if let Ok(encoded) = bincode::serialize(&request_header) { std::ptr::copy_nonoverlapping(encoded.as_ptr(), target_buffer, encoded.len()); 0 } else { // Unsure whether this is actually reachable but produce an error just in case so we don't crash. // Maybe in case of out-of-memory this can occur? -1 } } /// Given a a buffer will return a `ResponseHeader`. This header can be used to determine how many bytes /// of data are coming up. /// # Returns /// A RequestHeader for success. Anything else is a DeserializationError (e.g. when the provided buffer is too short) pub fn deserialize_request_header( request_header: &[u8], ) -> Result<RequestHeader, crate::DeserializationError> { bincode::deserialize(&request_header).map_err(|_| crate::DeserializationError) } /// Function which will put a `RequestHeader` and data together in a `Request`. /// This is purely a convenience function such that one can operate on a `Request` instead /// of keeping the header and data separate. pub fn deserialize_request(request_header: RequestHeader, request_data: Vec<u8>) -> Request { Request { header: request_header, body: request_data, } } /// Given the length of two entries returns the length of the buffer required to fit both entries including their lengths. #[no_mangle] pub extern "C" fn structure_two_entries_length( entry1_length: libc::size_t, entry2_length: libc::size_t, ) -> libc::size_t { entry1_length + entry2_length + 2 * std::mem::size_of::<usize>() } /// Given two entries and their length this function will put them back-to-back into data with length included. /// # Returns /// 0 on success. /// -1 when data was a null pointer. /// -2 when entry1 was a null pointer. /// -3 when entry2 was a null pointer. /// # Safety /// If entry1_length or entry2_length are not appropriate (too long for example) then an out of bounds /// access will occur; this is a bug introduced by the caller. When used in combination with the /// `structure_two_entries_length` function this will never occur. #[no_mangle] pub unsafe extern "C" fn structure_two_entries( data: *mut libc::c_uchar, entry1_length: libc::size_t, entry2_length: libc::size_t, entry1: *const libc::c_uchar, entry2: *const libc::c_uchar, ) -> i16 { if data.is_null() { return -1; } else if entry1.is_null() { return -2; } else if entry2.is_null() { return -3; } let usize_size_in_bytes = std::mem::size_of::<usize>(); std::ptr::copy_nonoverlapping( entry1_length.to_le_bytes().as_ptr(), data, usize_size_in_bytes, ); let data = data.add(usize_size_in_bytes); std::ptr::copy(entry1, data, entry1_length); let data = data.add(entry1_length); std::ptr::copy_nonoverlapping( entry2_length.to_le_bytes().as_ptr(), data, usize_size_in_bytes, ); let data = data.add(usize_size_in_bytes); std::ptr::copy(entry2, data, entry2_length); 0 } /// Given a buffer which was constructed using `structure_two_entries` this function will structure /// it back into two separate slices. A `DestructureError` will be returned in case /// this is not possible or would cause safety issues. pub fn destructure_two_entries(data: &[u8]) -> Result<(&[u8], &[u8]), crate::DestructureError> { let usize_size_in_bytes = std::mem::size_of::<usize>(); let entry1_length = data .get(..usize_size_in_bytes) .ok_or(crate::DestructureError)?; let rest = &data[usize_size_in_bytes..]; let entry1_length = usize::from_le_bytes( entry1_length .try_into() .map_err(|_| crate::DestructureError)?, ); let entry1 = rest.get(..entry1_length).ok_or(crate::DestructureError)?; let rest = &rest[entry1_length..]; let entry2_length = rest .get(..usize_size_in_bytes) .ok_or(crate::DestructureError)?; let rest = &rest[usize_size_in_bytes..]; let entry2_length = usize::from_le_bytes( entry2_length .try_into() .map_err(|_| crate::DestructureError)?, ); let entry2 = rest.get(..entry2_length).ok_or(crate::DestructureError)?; Ok((entry1, entry2)) }
pub mod v0; pub mod v1; pub struct AsciiDots; impl AsciiDots { pub const DOTS: &'static str = ".."; pub const CHAR_LEN: usize = 2; } pub struct UnicodeDots; impl UnicodeDots { pub const DOTS: char = '…'; pub const CHAR_LEN: usize = 1; }
pub mod survey_dto; pub use survey_dto::*;
//! Some well-known cryptographic algorithms, broken down into their primitive components for //! analysis.
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use core::any::Any; use alloc::sync::Arc; use alloc::vec::Vec; use core::sync::atomic::AtomicI64; use core::sync::atomic::Ordering; use alloc::string::String; use alloc::string::ToString; use spin::Mutex; use core::ops::*; use alloc::boxed::Box; use super::super::socket::*; use super::super::super::fs::attr::*; use super::super::super::fs::file::*; use super::super::super::fs::flags::*; use super::super::super::fs::dentry::*; use super::super::super::fs::dirent::*; //use super::super::super::fs::attr::*; use super::super::super::fs::host::hostinodeop::*; use super::super::super::kernel::fd_table::*; use super::super::super::kernel::abstract_socket_namespace::*; use super::super::super::kernel::waiter::*; use super::super::super::kernel::time::*; use super::super::super::qlib::common::*; use super::super::super::qlib::linux_def::*; use super::super::super::qlib::linux::socket::*; use super::super::super::task::*; //use super::super::super::qlib::mem::io::*; use super::super::super::qlib::mem::seq::*; use super::super::super::qlib::path::*; //use super::super::super::Kernel; use super::super::super::Kernel::HostSpace; //use super::super::super::fd::*; use super::super::super::tcpip::tcpip::*; use super::transport::unix::*; use super::transport::connectioned::*; use super::transport::connectionless::*; use super::super::super::socket::control::*; use super::super::super::socket::epsocket::epsocket::*; pub fn NewUnixSocket(task: &Task, ep: BoundEndpoint, stype: i32, hostfd: i32) -> Result<File> { //assert!(family == AFType::AF_UNIX, "NewUnixSocket family is not AF_UNIX"); let dirent = NewSocketDirent(task, UNIX_SOCKET_DEVICE.clone(), hostfd)?; let fileFlags = FileFlags { Read: true, Write: true, ..Default::default() }; return Ok(File::New(&dirent, &fileFlags, UnixSocketOperations::New(ep, stype, hostfd))) } pub struct UnixSocketOperations { pub ep: BoundEndpoint, pub stype: i32, pub send: AtomicI64, pub recv: AtomicI64, pub name: Mutex<Option<Vec<u8>>>, pub hostfd: i32, } impl UnixSocketOperations { pub fn New(ep: BoundEndpoint, stype: i32, hostfd: i32) -> Self { let ret = Self { ep: ep, stype: stype, send: AtomicI64::new(0), recv: AtomicI64::new(0), name: Mutex::new(None), hostfd: hostfd, }; return ret; } pub fn State(&self) -> i32 { return self.ep.State(); } pub fn IsPacket(&self) -> bool { if self.stype == SockType::SOCK_DGRAM || self.stype == SockType::SOCK_SEQPACKET { return true; } if self.stype == SockType::SOCK_STREAM { return false; } // We shouldn't have allowed any other socket types during creation. panic!("Invalid socket type {}", self.stype); } // GetPeerName implements the linux syscall getpeername(2) for sockets backed by // a transport.Endpoint. pub fn GetPeer(&self, _task: &Task) -> Result<(SockAddr, u32)> { let addr = self.ep.GetRemoteAddress()?; let l = addr.Len(); return Ok((SockAddr::Unix(addr), l as u32)) } // GetSockName implements the linux syscall getsockname(2) for sockets backed by // a transport.Endpoint. pub fn GetSockName(&self, _task: &Task) -> Result<(SockAddr, u32)> { let addr = self.ep.GetLocalAddress()?; let l = addr.Len(); return Ok((SockAddr::Unix(addr), l as u32)) } // blockingAccept implements a blocking version of accept(2), that is, if no // connections are ready to be accept, it will block until one becomes ready. pub fn BlockingAccept(&self, task: &Task) -> Result<ConnectionedEndPoint> { let entry = task.blocker.generalEntry.clone(); self.EventRegister(task, &entry, EVENT_IN); defer!(self.EventUnregister(task, &entry)); // Try to accept the connection; if it fails, then wait until we get a // notification. loop { match self.ep.Accept() { Ok(ep) => return Ok(ep), Err(Error::SysError(SysErr::EWOULDBLOCK)) => (), Err(e) => return Err(e), } task.blocker.BlockGeneral()?; } } fn encodeControlMsg(&self, task: &Task, mut ctrls: SCMControlMessages, controlDataLen: usize, mflags: &mut i32, cloexec: bool) -> Vec<u8> { // fill this with logic currently in sys_socket..... let mut controlVec: Vec<u8> = vec![0; controlDataLen]; let controlData = &mut controlVec[..]; let mut opt = SockOpt::PasscredOption(0); let controlData = if let Ok(_) = self.ep.GetSockOpt(&mut opt) { match opt { SockOpt::PasscredOption(0) => controlData, _ => match ctrls.Credentials { // Edge case: user set SO_PASSCRED but the sender didn't set it in control massage None => { let (data, flags) = ControlMessageCredentials::Empty().EncodeInto(controlData, *mflags); *mflags = flags; data }, Some(ref creds) => { let (data, flags) = creds.Credentials().EncodeInto(controlData, *mflags); *mflags = flags; data }, } } } else { controlData }; let controlData = match ctrls.Rights { None => controlData, Some(ref mut rights) => { let maxFDs = (controlData.len() as isize - SIZE_OF_CONTROL_MESSAGE_HEADER as isize) / 4; if maxFDs < 0 { *mflags |= MsgType::MSG_CTRUNC; controlData } else { let (fds, trunc) = rights.RightsFDs(task, cloexec, maxFDs as usize); if trunc { *mflags |= MsgType::MSG_CTRUNC; } let (controlData, _) = ControlMessageRights(fds).EncodeInto(controlData, *mflags); controlData } }, }; let new_size = controlDataLen - controlData.len(); controlVec.resize(new_size, 0); return controlVec; } } impl Drop for UnixSocketOperations { fn drop(&mut self) { self.ep.Close(); } } impl Passcred for UnixSocketOperations { fn Passcred(&self) -> bool { return self.ep.Passcred(); } } impl ConnectedPasscred for UnixSocketOperations { fn ConnectedPasscred(&self) -> bool { return self.ep.ConnectedPasscred(); } } impl Waitable for UnixSocketOperations { fn Readiness(&self, task: &Task, mask: EventMask) -> EventMask { self.ep.Readiness(task, mask) } fn EventRegister(&self, task: &Task, e: &WaitEntry, mask: EventMask) { self.ep.EventRegister(task, e, mask) } fn EventUnregister(&self, task: &Task,e: &WaitEntry) { self.ep.EventUnregister(task, e) } } // extractPath extracts and validates the address. pub fn ExtractPath(sockAddr: &[u8]) -> Result<Vec<u8>> { let addr = GetAddr(AFType::AF_UNIX as i16, sockAddr)?; let p = if let SockAddr::Unix(addr) = addr { addr.Path.as_bytes().to_vec() } else { panic!("impossible") }; if p.len() == 0 { // Not allowed. return Err(Error::SysError(SysErr::EINVAL)) } if p[p.len()-1] == '/' as u8 { // Weird, they tried to bind '/a/b/c/'? return Err(Error::SysError(SysErr::EISDIR)) } return Ok(p); } impl SpliceOperations for UnixSocketOperations {} impl FileOperations for UnixSocketOperations { fn as_any(&self) -> &Any { return self; } fn FopsType(&self) -> FileOpsType { return FileOpsType::UnixSocketOperations } fn Seekable(&self) -> bool { return false; } fn Seek(&self, _task: &Task, _f: &File, _whence: i32, _current: i64, _offset: i64) -> Result<i64> { return Err(Error::SysError(SysErr::ESPIPE)) } fn ReadDir(&self, _task: &Task, _f: &File, _offset: i64, _serializer: &mut DentrySerializer) -> Result<i64> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn ReadAt(&self, _task: &Task, _f: &File, dsts: &mut [IoVec], _offset: i64, _blocking: bool) -> Result<i64> { let count = IoVec::NumBytes(dsts); if count == 0 { return Ok(0) } match self.ep.RecvMsg(dsts, false, 0, false, None) { Err(Error::ErrClosedForReceive) => { // todo: fix this. How to handle ErrClosedForReceive, If again, Read will wait for it /*if self.IsPacket() { return Err(Error::SysError(SysErr::EAGAIN)) }*/ return Ok(0) } Err(e) => return Err(e), Ok((n, _, _, _)) => { return Ok(n as i64) } } } fn WriteAt(&self, task: &Task, _f: &File, srcs: &[IoVec], _offset: i64, _blocking: bool) -> Result<i64> { let ctrl = if self.ep.ConnectedPasscred() || self.ep.Passcred() { NewControlMessage(task, Some(self.ep.clone()), None) } else { SCMControlMessages::default() }; let count = IoVec::NumBytes(srcs); if count == 0 { let nInt = self.ep.SendMsg(srcs, &ctrl, &None)?; return Ok(nInt as i64) } match self.ep.SendMsg(srcs, &ctrl, &None) { Err(e) => return Err(e), Ok(n) => return Ok(n as i64) } } fn Append(&self, task: &Task, f: &File, srcs: &[IoVec]) -> Result<(i64, i64)> { let n = self.WriteAt(task, f, srcs, 0, false)?; return Ok((n, 0)) } fn Fsync(&self, _task: &Task, _f: &File, _start: i64, _end: i64, _syncType: SyncType) -> Result<()> { return Err(Error::SysError(SysErr::EINVAL)) } fn Flush(&self, _task: &Task, _f: &File) -> Result<()> { return Ok(()) } fn UnstableAttr(&self, task: &Task, f: &File) -> Result<UnstableAttr> { let inode = f.Dirent.Inode(); return inode.UnstableAttr(task); } fn Ioctl(&self, task: &Task, _f: &File, fd: i32, request: u64, val: u64) -> Result<()> { return Ioctl(task, &self.ep, fd, request, val) } fn IterateDir(&self, _task: &Task, _d: &Dirent, _dirCtx: &mut DirCtx, _offset: i32) -> (i32, Result<i64>) { return (0, Err(Error::SysError(SysErr::ENOTDIR))) } fn Mappable(&self) -> Result<HostInodeOp> { return Err(Error::SysError(SysErr::ENODEV)) } } // extractEndpoint retrieves the transport.BoundEndpoint associated with a Unix // socket path. The Release must be called on the transport.BoundEndpoint when // the caller is done with it. pub fn ExtractEndpoint(task: &Task, sockAddr: &[u8]) -> Result<BoundEndpoint> { let path = ExtractPath(sockAddr)?; //info!("unix socket path is {}", String::from_utf8(path.to_vec()).unwrap()); // Is it abstract? if path[0] == 0 { let ep = match BoundEndpoint(&path) { None => return Err(Error::SysError(SysErr::ECONNREFUSED)), Some(ep) => ep, }; return Ok(ep) } let path = String::from_utf8(path).unwrap(); // Find the node in the filesystem. let root = task.fsContext.RootDirectory(); let cwd = task.fsContext.WorkDirectory(); let mut remainingTraversals = 10; //DefaultTraversalLimit let mns = task.Thread().MountNamespace(); let d = mns.FindInode(task, &root, Some(cwd), &path, &mut remainingTraversals)?; // Extract the endpoint if one is there. let inode = d.Inode(); let iops = inode.lock().InodeOp.clone(); let fullName = d.MyFullName(); //if it is host unix socket, the ep is in virtual unix if iops.InodeType() == InodeType::Socket && iops.as_any().downcast_ref::<HostInodeOp>().is_some() { let ep = match BoundEndpoint(&fullName.into_bytes()) { None => return Err(Error::SysError(SysErr::ECONNREFUSED)), Some(ep) => ep, }; return Ok(ep) } let ep = match inode.BoundEndpoint(task, &path) { None => return Err(Error::SysError(SysErr::ECONNREFUSED)), Some(ep) => ep, }; return Ok(ep) } impl SockOperations for UnixSocketOperations { fn Connect(&self, task: &Task, socketaddr: &[u8], _blocking: bool) -> Result<i64> { let ep = ExtractEndpoint(task, socketaddr)?; // Connect the server endpoint. match self.ep.Connect(task, &ep) { Err(Error::SysError(SysErr::EPROTOTYPE)) => { // Linux for abstract sockets returns ErrConnectionRefused // instead of ErrWrongProtocolForSocket. let path = ExtractPath(socketaddr)?; if path[0] == 0 { return Err(Error::SysError(SysErr::ECONNREFUSED)) } else { return Err(Error::SysError(SysErr::EPROTOTYPE)) } } Err(e) => return Err(e), _ => (), } return Ok(0) } // Accept implements the linux syscall accept(2) for sockets backed by // a transport.Endpoint. fn Accept(&self, task: &Task, addr: &mut [u8], addrlen: &mut u32, flags: i32, blocking: bool) -> Result<i64> { let ep = match self.ep.Accept() { Err(Error::SysError(SysErr::EWOULDBLOCK)) => { if !blocking { return Err(Error::SysError(SysErr::EWOULDBLOCK)); } self.BlockingAccept(task)? } Err(e) => return Err(e), Ok(ep) => ep, }; let ep = BoundEndpoint::Connected(ep); let fd = HostSpace::Socket(AFType::AF_UNIX, self.stype, 0) as i32; if fd < 0 { return Err(Error::SysError(-fd)) } let ns = NewUnixSocket(task, ep, self.stype, fd)?; ns.flags.lock().0.NonSeekable = true; if flags & SocketFlags::SOCK_NONBLOCK != 0 { let mut fflags = ns.Flags(); fflags.NonBlocking = true; ns.SetFlags(task, fflags.SettableFileFlags()); } if *addrlen != 0 { *addrlen = ns.FileOp.GetPeerName(task, addr)? as u32; } let fdFlags = FDFlags { CloseOnExec: flags & SocketFlags::SOCK_CLOEXEC != 0, }; let fd = task.NewFDFrom(0, &ns, &fdFlags)?; return Ok(fd as i64); } fn Bind(&self, task: &Task, socketaddr: &[u8]) -> Result<i64> { let p = ExtractPath(socketaddr)?; info!("Bind p is {:?}", &p); let bep = self.ep.clone(); let addr = SockAddrUnix::New(core::str::from_utf8(&p).expect("Bind to string fail")); self.ep.Bind(&addr)?; let root = task.fsContext.RootDirectory(); // Is it abstract? if p[0] == 0 { Bind(p.clone(), &bep)?; *(self.name.lock()) = Some(p); } else { let p = String::from_utf8(p).unwrap(); info!("bind address is {}", &p); let cwd = task.fsContext.WorkDirectory(); let d; let name; if !p.contains('/') { d = cwd; name = &p[..]; } else { // Find the last path component, we know that something follows // that final slash, otherwise extractPath() would have failed. let lastSlash = LastIndex(&p, '/' as u8); assert!(lastSlash != -1); let subpath = if lastSlash == 0 { // Fix up subpath in case file is in root. "/" } else { &p[0..lastSlash as usize] }; let mut remainingTraversals = 10; d = task.Thread().MountNamespace().FindInode(task, &root, Some(cwd), &subpath.to_string(), &mut remainingTraversals)?; name = &p[lastSlash as usize + 1..]; } // Create the socket. let permisson = FilePermissions { User: PermMask {read: true, ..Default::default()}, ..Default::default() }; let inode = d.Inode(); let iops = inode.lock().InodeOp.clone(); //if it is host folder, create shadow host unix socket bind if iops.InodeType() == InodeType::Directory && iops.as_any().downcast_ref::<HostInodeOp>().is_some() { let fullName = d.MyFullName() + "/" + &name.to_string(); let hostfd = self.hostfd; let addr = SockAddrUnix::New(&fullName).ToNative(); let ret = HostSpace::Bind(hostfd, &addr as * const _ as u64, (UNIX_PATH_MAX + 2) as u32, task.Umask()); if ret < 0 { return Err(Error::SysError(-ret as i32)) } // handle the host unix socket as virtual unix socket Bind(fullName.into_bytes(), &bep)?; *(self.name.lock()) = Some(p.into_bytes()); } else { match d.Bind(task, &root, &name.to_string(), &bep, &permisson) { Err(_) => return Err(Error::SysError(SysErr::EADDRINUSE)), Ok(_) => (), } } } return Ok(0) } fn Listen(&self, _task: &Task, backlog: i32) -> Result<i64> { self.ep.Listen(backlog)?; return Ok(0); } fn Shutdown(&self, _task: &Task, how: i32) -> Result<i64> { let f = ConvertShutdown(how)?; self.ep.Shutdown(f)?; return Ok(0) } fn GetSockOpt(&self, task: &Task, level: i32, name: i32, opt: &mut [u8]) -> Result<i64> { let ret = GetSockOpt(task, self, &self.ep, AFType::AF_UNIX, self.ep.Type(), level, name, opt.len())?; let size = ret.Marsh(opt)?; return Ok(size as i64) } fn SetSockOpt(&self, task: &Task, level: i32, name: i32, opt: &[u8]) -> Result<i64> { SetSockOpt(task, self, &self.ep, level, name, opt)?; return Ok(0) } fn GetSockName(&self, _task: &Task, socketaddr: &mut [u8]) -> Result<i64> { let addr = self.ep.GetLocalAddress()?; let l = addr.Len(); SockAddr::Unix(addr).Marsh(socketaddr, l)?; return Ok(l as i64) } fn GetPeerName(&self, _task: &Task, socketaddr: &mut [u8]) -> Result<i64> { let addr = self.ep.GetRemoteAddress()?; let l = addr.Len(); SockAddr::Unix(addr).Marsh(socketaddr, l as usize)?; return Ok(l as i64) } fn RecvMsg(&self, task: &Task, dsts: &mut [IoVec], flags: i32, deadline: Option<Time>, senderRequested: bool, controlDataLen: usize) -> Result<(i64, i32, Option<(SockAddr, usize)>, Vec<u8>)> { let trunc = flags & MsgType::MSG_TRUNC != 0; let peek = flags & MsgType::MSG_PEEK != 0; let dontWait = flags & MsgType::MSG_DONTWAIT != 0; let waitAll = flags & MsgType::MSG_WAITALL != 0; let cloexec = flags & MsgType::MSG_CMSG_CLOEXEC != 0; // Calculate the number of FDs for which we have space and if we are // requesting credentials. let mut wantCreds = false; let mut msgFlags = 0; let mut rightsLen = controlDataLen as isize - SIZEOF_CMSGHDR as isize; if self.Passcred() { // Credentials take priority if they are enabled and there is space. wantCreds = rightsLen >= 0; if !wantCreds { msgFlags |= MsgType::MSG_CTRUNC; } let credlen = CMsgSpace(SIZEOF_UCRED); rightsLen -= credlen as isize; } // FDs are 32 bit (4 byte) ints. let mut numRights = rightsLen / 4; if numRights < 0 { numRights = 0; } let mut unixAddr = SockAddrUnix::default(); let mut total : i64 = 0; let mut sender = None; let mut outputctrls = SCMControlMessages::default(); let mut ControlVec = self.encodeControlMsg(task, outputctrls, controlDataLen, &mut msgFlags, cloexec); let size = IoVec::NumBytes(dsts); let buf = DataBuff::New(size); let mut bs = BlockSeqToIoVecs(buf.BlockSeq()); match self.ep.RecvMsg(&mut bs, wantCreds, numRights as u64, peek, Some(&mut unixAddr)) { Err(Error::SysError(SysErr::EAGAIN)) => { if dontWait { return Err(Error::SysError(SysErr::EAGAIN)) } } Err(Error::ErrClosedForReceive) => { if self.IsPacket() { return Err(Error::SysError(SysErr::EAGAIN)) } task.CopyDataOutToIovs(&buf.buf[0..total as usize], dsts)?; return Ok((total, msgFlags, sender, ControlVec)) } Err(e) => { return Err(e) } Ok((mut n, ms, ctrls, ctrunc)) => { sender = if senderRequested { let fromLen = unixAddr.Len(); Some((SockAddr::Unix(unixAddr), fromLen)) } else { None }; outputctrls = ctrls; ControlVec = self.encodeControlMsg(task, outputctrls, controlDataLen, &mut msgFlags, cloexec); if ctrunc { msgFlags |= MsgType::MSG_CTRUNC; } let seq = BlockSeq::NewFromSlice(&bs); if self.IsPacket() && n < ms { msgFlags |= MsgType::MSG_TRUNC; } if trunc { n = ms } if dontWait || !waitAll || self.IsPacket() || n >= seq.NumBytes() as usize { if self.IsPacket() && n < ms { msgFlags |= MsgType::MSG_TRUNC; } if trunc { n = ms; } task.CopyDataOutToIovs(&buf.buf[0..n as usize], dsts)?; return Ok((n as i64, msgFlags, sender, ControlVec)) } let seq = seq.DropFirst(n as u64); bs = BlockSeqToIoVecs(seq); total += n as i64; } } let general = task.blocker.generalEntry.clone(); self.EventRegister(task, &general, EVENT_READ); defer!(self.EventUnregister(task, &general)); loop { let mut unixAddr = SockAddrUnix::default(); match self.ep.RecvMsg(&mut bs, wantCreds, numRights as u64, peek, Some(&mut unixAddr)) { Err(Error::SysError(SysErr::EAGAIN)) => (), Err(Error::ErrClosedForReceive) => { task.CopyDataOutToIovs(&buf.buf[0..total as usize], dsts)?; return Ok((total as i64, msgFlags, sender, ControlVec)) } Err(e) => { if total > 0 { task.CopyDataOutToIovs(&buf.buf[0..total as usize], dsts)?; return Ok((total as i64, msgFlags, sender, ControlVec)) } return Err(e) }, Ok((n, ms, ctrls, ctrunc)) => { let sender = if senderRequested { let fromLen = unixAddr.Len(); Some((SockAddr::Unix(unixAddr), fromLen)) } else { None }; if ctrunc { msgFlags |= MsgType::MSG_CTRUNC; } if trunc { total += ms as i64 } else { total += n as i64 } // todo: handle waitAll let seq = BlockSeq::NewFromSlice(&bs); if waitAll && n < seq.NumBytes() as usize { info!("RecvMsg get waitall, but return partial......") } if self.IsPacket() && n < ms { msgFlags |= MsgType::MSG_TRUNC; } let seq = BlockSeq::NewFromSlice(&bs); if !waitAll || self.IsPacket() || n >= seq.NumBytes() as usize { if self.IsPacket() && n < ms { msgFlags |= MsgType::MSG_TRUNC; } let ControlVector = self.encodeControlMsg(task, ctrls, controlDataLen, &mut msgFlags, cloexec); task.CopyDataOutToIovs(&buf.buf[0..total as usize], dsts)?; return Ok((total, msgFlags, sender, ControlVector)) } let seq = seq.DropFirst(n as u64); bs = BlockSeqToIoVecs(seq); } } match task.blocker.BlockWithMonoTimer(true, deadline) { Err(Error::SysError(SysErr::ETIMEDOUT)) => { if total > 0 { task.CopyDataOutToIovs(&buf.buf[0..total as usize], dsts)?; return Ok((total as i64, msgFlags, sender, ControlVec)) } return Err(Error::SysError(SysErr::EAGAIN)) } Err(e) => return Err(e), _ =>(), } } } fn SendMsg(&self, task: &Task, srcs: &[IoVec], flags: i32, msgHdr: &mut MsgHdr, deadline: Option<Time>) -> Result<i64> { let to: Vec<u8> = if msgHdr.msgName != 0 { if self.stype == SockType::SOCK_SEQPACKET { Vec::new() } else if self.stype == SockType::SOCK_STREAM { if self.State() == SS_CONNECTED { return Err(Error::SysError(SysErr::EISCONN)) } return Err(Error::SysError(SysErr::EOPNOTSUPP)); } else { task.CopyInVec(msgHdr.msgName, msgHdr.nameLen as usize)? } } else { Vec::new() }; let controlVec: Vec<u8> = if msgHdr.msgControl != 0 { task.CopyInVec(msgHdr.msgControl, msgHdr.msgControlLen as usize)? } else { Vec::new() }; let toEp = if to.len() > 0 { let ep = ExtractEndpoint(task, &to)?; Some(ep) } else { None }; let ctrlMsg = if controlVec.len() > 0 { Parse(&controlVec)? } else { ControlMessages::default() }; let scmCtrlMsg = ctrlMsg.ToSCMUnix(task, &self.ep, &toEp)?; let size = IoVec::NumBytes(srcs); let mut buf = DataBuff::New(size); task.CopyDataInFromIovs(&mut buf.buf, srcs)?; let n = match self.ep.SendMsg(&buf.Iovs(), &scmCtrlMsg, &toEp) { Err(Error::SysError(SysErr::EAGAIN)) => { if flags & MsgType::MSG_DONTWAIT != 0 { return Err(Error::SysError(SysErr::EAGAIN)) } 0 } Err(e) => return Err(e), Ok(n) => { if flags & MsgType::MSG_DONTWAIT != 0 { return Ok(n as i64) } n }, }; // We'll have to block. Register for notification and keep trying to // send all the data. let general = task.blocker.generalEntry.clone(); self.EventRegister(task, &general, EVENT_OUT); defer!(self.EventUnregister(task, &general)); let mut total = n; let bs = buf.BlockSeq(); let totalLen = bs.Len(); while total < totalLen { let left = bs.DropFirst(total as u64); let srcs = left.ToIoVecs(); let n = match self.ep.SendMsg(&srcs, &scmCtrlMsg, &toEp) { Err(Error::SysError(SysErr::EAGAIN)) => { 0 } Err(e) => { if total > 0 { return Ok(total as i64) } return Err(e) }, Ok(n) => n }; total += n; match task.blocker.BlockWithMonoTimer(true, deadline) { Err(Error::SysError(SysErr::ETIMEDOUT)) => { return Err(Error::SysError(SysErr::EAGAIN)) } Err(e) => { return Err(e); } _ => () } } return Ok(total as i64) } fn SetRecvTimeout(&self, ns: i64) { self.recv.store(ns, Ordering::Relaxed) } fn SetSendTimeout(&self, ns: i64) { self.send.store(ns, Ordering::Relaxed) } fn RecvTimeout(&self) -> i64 { return self.recv.load(Ordering::Relaxed) } fn SendTimeout(&self) -> i64 { return self.send.load(Ordering::Relaxed) } } pub struct UnixSocketProvider { } impl Provider for UnixSocketProvider { fn Socket(&self, task: &Task, stype: i32, protocol: i32) -> Result<Option<Arc<File>>> { if protocol != 0 && protocol != AFType::AF_UNIX { return Err(Error::SysError(SysErr::EPROTONOSUPPORT)) } let fd = HostSpace::Socket(AFType::AF_UNIX, stype, protocol) as i32; if fd < 0 { return Err(Error::SysError(-fd)) } // Create the endpoint and socket. match stype { SockType::SOCK_DGRAM => { let ep = ConnectionLessEndPoint::New(fd); let ep = BoundEndpoint::ConnectLess(ep); return Ok(Some(Arc::new(NewUnixSocket(task, ep, stype, fd)?))) } SockType::SOCK_SEQPACKET => { let ep = ConnectionedEndPoint::New(stype, fd); let ep = BoundEndpoint::Connected(ep); return Ok(Some(Arc::new(NewUnixSocket(task, ep, stype, fd)?))) } SockType::SOCK_STREAM => { let ep = ConnectionedEndPoint::New(stype, fd); let ep = BoundEndpoint::Connected(ep); return Ok(Some(Arc::new(NewUnixSocket(task, ep, stype, fd)?))) } _ => return Err(Error::SysError(SysErr::EINVAL)) } } fn Pair(&self, task: &Task, stype: i32, protocol: i32) -> Result<Option<(Arc<File>, Arc<File>)>> { if protocol != 0 && protocol != AFType::AF_UNIX { return Err(Error::SysError(SysErr::EPROTONOSUPPORT)) } match stype { SockType::SOCK_STREAM => (), SockType::SOCK_DGRAM | SockType::SOCK_SEQPACKET => (), _ => return Err(Error::SysError(SysErr::EINVAL)) } let fd1 = HostSpace::Socket(AFType::AF_UNIX, stype, protocol) as i32; if fd1 < 0 { return Err(Error::SysError(-fd1)) } let fd2 = HostSpace::Socket(AFType::AF_UNIX, stype, protocol) as i32; if fd2 < 0 { return Err(Error::SysError(-fd2)) } // Create the endpoints and sockets. let (ep1, ep2) = ConnectionedEndPoint::NewPair(stype, fd1, fd2); let ep1 = BoundEndpoint::Connected(ep1); let ep2 = BoundEndpoint::Connected(ep2); let s1 = NewUnixSocket(task, ep1, stype, fd1)?; let s2 = NewUnixSocket(task, ep2, stype, fd2)?; return Ok(Some((Arc::new(s1), Arc::new(s2)))) } } pub fn Init() { FAMILIAES.write().RegisterProvider(AFType::AF_UNIX, Box::new(UnixSocketProvider { })) }
use crate::{ hardware::Hardware, twin::{self, resolve_relation}, twins::{ drone_twin::{ states::{DroneTwinState, LaunchedState, ReadyState}, DroneTwin, }, launchpad_twin::{LaunchpadTwin, LaunchpadTwinState}, mission_twin::{MissionTwin, MissionTwinState}, }, }; use actyx_sdk::HttpClient; use futures::Stream; use std::time::Duration; use tokio::{select, sync::mpsc, time::interval}; use tokio_stream::wrappers::ReceiverStream; use tokio_stream::StreamExt; use tokio_stream_ext::StreamOpsExt; pub struct Controller { name: String, service: HttpClient, hardware: Hardware, } #[derive(Clone, Debug)] struct AppState { pub launchpad: LaunchpadTwinState, pub drone: Option<DroneTwinState>, pub mission: Option<MissionTwinState>, } impl Controller { pub fn new(name: String, service: HttpClient) -> Self { Self { name, hardware: Hardware::new(service.clone()), service, } } fn service(&self) -> HttpClient { self.service.clone() } fn name(&self) -> String { self.name.clone() } pub async fn start(&mut self) -> Result<(), anyhow::Error> { LaunchpadTwin::emit_launchpad_registered(self.service(), self.name()).await?; let launchpad_twin = LaunchpadTwin::new(self.name()); let launchpad_stream = twin::execute_twin(self.service(), launchpad_twin.clone()).as_stream(); let current_mission = resolve_relation(self.service(), launchpad_twin.clone(), |s| { s.current_mission.map(|id| MissionTwin { id }) }); let assigned_drone = resolve_relation(self.service(), launchpad_twin.clone(), |s| { s.attached_drone.map(|id| DroneTwin { id }) }); let res = self .logic(launchpad_stream, current_mission, assigned_drone) .await; println!("Program terminated with {:#?}", res); Ok(()) } async fn logic( &mut self, mut launchpad_stream: impl Stream<Item = LaunchpadTwinState> + Unpin, mut current_mission: impl Stream<Item = MissionTwinState> + Unpin, mut assigned_drone: impl Stream<Item = DroneTwinState> + Unpin, ) -> Result<(), anyhow::Error> { let mut launchpad_state = None; let mut drone_state = None; let mut mission_state = None; let mut state_read = interval(Duration::from_millis(1000)); let (tx, rx) = mpsc::channel::<AppState>(3); let mut state_update = Box::pin(ReceiverStream::new(rx).debounce(Duration::from_millis(200))); loop { select! { _ = state_read.tick() => { drone_state.as_ref().map(|s| self.update_states(s)); }, new_launchpad = launchpad_stream.next() => { launchpad_state = new_launchpad; let _ = tx.send(AppState { drone: drone_state.clone(), launchpad: launchpad_state.clone().unwrap(), mission: mission_state.clone(), }).await; }, new_drone = assigned_drone.next() =>{ drone_state = new_drone; if let Some(launchpad) = launchpad_state.clone() { let _ = tx.send(AppState { drone: drone_state.clone(), launchpad, mission: mission_state.clone(), }).await; } }, new_mission = current_mission.next() => { mission_state = new_mission; if let Some(launchpad) = launchpad_state.clone() { let _ = tx.send(AppState { drone: drone_state.clone(), launchpad, mission: mission_state.clone(), }).await; } }, Some(app_state) = state_update.next() => { if let Err(e) = self.handler(app_state.clone()).await { println!("Something is wrong {:?}", e); }; }, } } } async fn update_states(&mut self, drone_state: &DroneTwinState) -> Result<(), anyhow::Error> { println!("update_states"); if let Ok(s) = self.hardware.get_state() { let (battery, id) = match drone_state { DroneTwinState::Undefined(_) => return Ok(()), DroneTwinState::Ready(e) => (e.battery, e.id.to_owned()), DroneTwinState::Launched(e) => (e.battery, e.id.to_owned()), DroneTwinState::Used(e) => (e.battery, e.id.to_owned()), }; println!("battery {} <-> new {}", battery, s.bat); if (battery as i8 - s.bat).abs() >= 5 { println!("update battery values {:?}", s.bat); DroneTwin::emit_drone_stats_updated(self.service(), id, s.bat as u8).await?; } }; Ok(()) } async fn handler(&mut self, app_state: AppState) -> Result<(), anyhow::Error> { let launchpad_state = app_state.launchpad; let mission_state = app_state.mission; let drone_state = app_state.drone; if let (Some(drone_state), Some(mission)) = (drone_state, mission_state) { match drone_state { DroneTwinState::Undefined(_) => { println!("FU: Starting an undefined drone!? NO!") } // drone is defined DroneTwinState::Ready(ref d @ ReadyState { .. }) if !d.is_enabled() => { println!("enable drone"); self.hardware.enable_drone().await; DroneTwin::emit_drone_activated(self.service(), d.id.to_owned(), self.name()) .await?; } // drone is enabled DroneTwinState::Ready(ReadyState { id, ssid, ip, connected: false, .. }) => { println!("connect to drone now"); self.hardware .connect_now(id.clone(), ssid.clone(), ip.clone()) .await? } // drone is enabled / and connected DroneTwinState::Ready(ReadyState { id, ssid, ip, connected: true, .. }) => { self.hardware .take_off_now(id.clone(), ssid.clone(), ip.clone(), mission.id.to_owned()) .await? } // drone is in the air and the current mission is *not* completed an currently not moving to the next waypoint DroneTwinState::Launched(LaunchedState { id, at_waypoint_id, target_waypoint_id: None, completed: false, .. }) => { self.hardware .exec_waypoint(id.to_owned(), at_waypoint_id as usize, &mission) .await?; } // Mission completed land now! DroneTwinState::Launched(LaunchedState { id, completed: true, .. }) => { self.hardware.land_now(id.clone()).await?; DroneTwin::emit_drone_mission_completed(self.service(), id, mission.id.clone()) .await?; } // drone is on the way to the next waypoint, and wait that the drone arrives on the next Waypoint DroneTwinState::Launched(LaunchedState { id, mission_id, target_waypoint_id: Some(next_wp), completed: false, .. }) => { println!( "Drone {} is on the way to {} for mission {}", id, next_wp, mission_id ); } DroneTwinState::Used(_) => { println!("FU do nothing when already in used state") } } } else { if let Some(next_mission) = launchpad_state.mission_queue.first() { println!("Activate next mission {}", next_mission); LaunchpadTwin::emit_mission_activated( self.service(), self.name(), next_mission.to_owned(), ) .await?; } } println!("----------------------------------------\n"); Ok(()) } }
use std::fs; use std::collections::HashMap; fn binary_space (instructions: &str, max: &u32) -> u32 { let mut low = 0; let mut current = max / 2; for code in instructions.chars() { if code == 'B' || code == 'R' { low += current; } current = current / 2 } return low; } fn get_seat (code: &str) -> (u32, u32, u32) { let row_instruction = &code[0..7]; let column_instruction = &code[7..10]; let row = binary_space(row_instruction, &128); let column = binary_space(column_instruction, &8); let id = row * 8 + column; return (row, column, id); } fn part_1 (filename: &str) -> u32 { let file_content = fs::read_to_string(filename).expect("Something went wrong reading the file"); let lines = file_content.lines(); let mut max = 0; for line in lines { let (_, __, id) = get_seat(line); if id > max { max = id } } max } fn part_2 (filename: &str) { let file_content = fs::read_to_string(filename).expect("Something went wrong reading the file"); let lines = file_content.lines(); let mut seats = HashMap::new(); for row in 1..127 { for column in 0..8 { seats.insert((row, column), row * 8 + column); } } for line in lines { let (row, column, _) = get_seat(line); seats.remove(&(row, column)); } let mut ids: Vec<u32> = seats.into_iter().map(|(_, v)| v).collect(); ids.sort(); for i in 1..ids.len()-1 { let id = ids[i]; let lower = ids[i-1]; let higher = ids[i+1]; if id - 1 != lower && id+1 != higher { println!("Available seat: {:?}", id); } } } fn main() { let result = part_1("src/exo5.source.txt"); println!("Result part 1: {}", result); part_2("src/exo5.source.txt"); }
// Copyright 2021 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 once_cell::sync::Lazy; pub static DATABEND_COMMIT_VERSION: Lazy<String> = Lazy::new(|| { let build_semver = option_env!("DATABEND_GIT_SEMVER"); let git_sha = option_env!("VERGEN_GIT_SHA"); let rustc_semver = option_env!("VERGEN_RUSTC_SEMVER"); let timestamp = option_env!("VERGEN_BUILD_TIMESTAMP"); match (build_semver, git_sha, rustc_semver, timestamp) { #[cfg(not(feature = "simd"))] (Some(v1), Some(v2), Some(v3), Some(v4)) => format!("{}-{}({}-{})", v1, v2, v3, v4), #[cfg(feature = "simd")] (Some(v1), Some(v2), Some(v3), Some(v4)) => { format!("{}-{}-simd({}-{})", v1, v2, v3, v4) } _ => String::new(), } });
mod kv; use kv::KVStore; fn main() { let store = KVStore {host: String::from("http://127.0.0.1:8500")}; println!("{:#?}", store.get(String::from("foo/bar/bar"))); println!("{}", store.put(String::from("foo/bar/bar"), String::from("foo"))) }
// SPDX-License-Identifier: MIT // Copyright (c) 2021-2022 brainpower <brainpower at mailbox dot org> use crate::Opt; impl<'a> std::fmt::Debug for Opt<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "Opt {{\n sopt: {:?},\n lopt: {:?},\n help: {:?},\n value: {:?},\n value_type: {},\n \ value_name: {:?}\n}}", self.sopt, self.lopt, self.help, self.value, self.value_type, self.value_name, ) } }
// Copyright 2020-2021, The Tremor Team // // 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. #![cfg(not(tarpaulin_include))] use crate::postprocessor::{make_postprocessors, postprocess, Postprocessors}; use crate::{codec::Codec, source::prelude::*}; use async_channel::{Sender, TryRecvError}; use async_std::net::{TcpListener, TcpStream}; use async_std::task; use async_tungstenite::tungstenite::Message; use futures::{SinkExt, StreamExt}; use halfbrown::HashMap; use std::collections::BTreeMap; use tremor_pipeline::EventId; use tremor_script::Value; #[derive(Deserialize, Debug, Clone)] pub struct Config { /// The port to listen on. pub port: u16, /// Host to listen on pub host: String, } impl ConfigImpl for Config {} pub struct Ws { pub config: Config, onramp_id: TremorUrl, } impl onramp::Impl for Ws { fn from_config(id: &TremorUrl, config: &Option<YamlValue>) -> Result<Box<dyn Onramp>> { if let Some(config) = config { let config: Config = Config::new(config)?; Ok(Box::new(Self { config, onramp_id: id.clone(), })) } else { Err("Missing config for websocket onramp".into()) } } } enum WsSourceReply { StartStream(usize, Option<Sender<SerializedResponse>>), EndStream(usize), Data(SourceReply), // stupid wrapper around SourceReply::Data } /// encoded response and additional information /// for post-processing and assembling WS messages pub struct SerializedResponse { event_id: EventId, ingest_ns: u64, data: Vec<u8>, binary: bool, } pub struct Int { uid: u64, onramp_id: TremorUrl, config: Config, is_linked: bool, listener: Option<Receiver<WsSourceReply>>, post_processors: Vec<String>, // mapping of event id to stream id messages: BTreeMap<u64, usize>, // mapping of stream id to the stream sender // TODO alternative to this? possible to store actual ws_stream refs here? streams: BTreeMap<usize, Sender<SerializedResponse>>, } impl std::fmt::Debug for Int { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "WS") } } impl Int { fn from_config( uid: u64, onramp_id: TremorUrl, post_processors: &[String], config: &Config, is_linked: bool, ) -> Self { let config = config.clone(); Self { uid, config, listener: None, post_processors: post_processors.to_vec(), onramp_id, is_linked, messages: BTreeMap::new(), streams: BTreeMap::new(), } } fn get_stream_sender_for_id(&self, id: u64) -> Option<&Sender<SerializedResponse>> { // TODO improve the way stream_id is retrieved -- this works as long as a // previous event id is used by pipelines/offramps (which is suitable only // for request/response style flow), but for websocket, arbitrary events can // come in here. // also messages keeps growing as events come in right now self.messages .get(&id) .and_then(|stream_id| self.streams.get(stream_id)) } } async fn handle_connection( source_url: TremorUrl, tx: Sender<WsSourceReply>, raw_stream: TcpStream, origin_uri: EventOriginUri, processors: Vec<String>, stream: usize, link: bool, ) -> Result<()> { let ws_stream = async_tungstenite::accept_async(raw_stream).await?; let (mut ws_write, mut ws_read) = ws_stream.split(); // TODO maybe send ws_write from tx and get rid of this task + extra channel? let stream_sender = if link { let (stream_tx, stream_rx): (Sender<SerializedResponse>, Receiver<SerializedResponse>) = bounded(crate::QSIZE); // response handling task task::spawn::<_, Result<()>>(async move { // create post-processors for this stream match make_postprocessors(processors.as_slice()) { Ok(mut post_processors) => { // wait for response messages to arrive (via reply_event) while let Ok(response) = stream_rx.recv().await { let event_id = response.event_id.to_string(); let msgs = match make_messages(response, &mut post_processors) { // post-process Ok(messages) => messages, Err(e) => { error!( "[Source::{}] Error post-processing response event: {}", &source_url, e.to_string() ); let err = create_error_response( format!("Error post-processing messages: {}", e), event_id, &source_url, ); let mut msgs = Vec::with_capacity(1); if let Ok(data) = simd_json::to_vec(&err) { msgs.push(Message::Binary(data)); } else { error!( "[Source::{}] Error serializing error response to json.", &source_url ); } msgs } }; for msg in msgs { ws_write.send(msg).await?; } } } Err(e) => error!( "[Onramp::WS] Invalid Post Processors, not starting response receiver task: {}", e ), // shouldn't happen, got validated before in init and is not changes after } Ok(()) }); Some(stream_tx) } else { None }; tx.send(WsSourceReply::StartStream(stream, stream_sender)) .await?; while let Some(msg) = ws_read.next().await { let mut meta = Value::object_with_capacity(1); match msg { Ok(Message::Text(t)) => { meta.insert("binary", false)?; tx.send(WsSourceReply::Data(SourceReply::Data { origin_uri: origin_uri.clone(), data: t.into_bytes(), meta: Some(meta), codec_override: None, stream, })) .await?; } Ok(Message::Binary(data)) => { meta.insert("binary", true)?; tx.send(WsSourceReply::Data(SourceReply::Data { origin_uri: origin_uri.clone(), data, meta: Some(meta), codec_override: None, stream, })) .await?; } Ok(Message::Ping(_) | Message::Pong(_)) => (), Ok(Message::Close(_)) => { tx.send(WsSourceReply::EndStream(stream)).await?; break; } Err(e) => error!("WS error returned while waiting for client data: {}", e), } } Ok(()) } fn make_messages( response: SerializedResponse, processors: &mut Postprocessors, ) -> Result<Vec<Message>> { let send_as_binary = response.binary; let processed = postprocess(processors.as_mut_slice(), response.ingest_ns, response.data)?; Ok(processed .into_iter() .map(|data| { if send_as_binary { Message::Binary(data) } else { let str = String::from_utf8_lossy(&data).to_string(); Message::Text(str) } }) .collect()) } fn create_error_response(err: String, event_id: String, source_id: &TremorUrl) -> Value<'static> { let mut err_data = tremor_script::Object::with_capacity(3); err_data.insert_nocheck("error".into(), Value::from(err)); err_data.insert_nocheck("event_id".into(), Value::from(event_id)); err_data.insert_nocheck("source_id".into(), Value::from(source_id.to_string())); Value::from(err_data) } #[async_trait::async_trait()] impl Source for Int { async fn pull_event(&mut self, id: u64) -> Result<SourceReply> { let messages = &mut self.messages; let streams = &mut self.streams; self.listener.as_ref().map_or_else( // listener channel dropped or not created yet, we ae disconnected || Ok(SourceReply::StateChange(SourceState::Disconnected)), // get a request or other control message from the ws server |listener| match listener.try_recv() { Ok(r) => match r { WsSourceReply::Data(wrapped) => match wrapped { SourceReply::Data { stream, .. } => { messages.insert(id, stream); Ok(wrapped) } _ => Err( "Invalid WsSourceReply received in pull_event. Something is fishy!" .into(), ), }, WsSourceReply::StartStream(stream, ref sender) => { debug!("[Source::WS] start stream {}", stream); if let Some(tx) = sender { streams.insert(stream, tx.clone()); } Ok(SourceReply::StartStream(stream)) } WsSourceReply::EndStream(stream) => { debug!("[Source::WS] end stream {}", stream); streams.remove(&stream); Ok(SourceReply::EndStream(stream)) } }, Err(TryRecvError::Empty) => Ok(SourceReply::Empty(10)), Err(TryRecvError::Closed) => { Ok(SourceReply::StateChange(SourceState::Disconnected)) } }, ) } async fn reply_event( &mut self, event: Event, codec: &dyn Codec, _codec_map: &HashMap<String, Box<dyn Codec>>, ) -> Result<()> { if let Some((_stream, eid)) = event.id.get_max_by_source(self.uid) { if let Some(tx) = self.get_stream_sender_for_id(eid) { for (value, meta) in event.value_meta_iter() { let binary = meta.get_bool("binary").unwrap_or_default(); // we do the encoding here, and the post-processing later on the sending task, as this is stream-based let data = match codec.encode(value) { Ok(data) => data, Err(e) => { error!( "[Source::{}] Error encoding reply event: {}", &self.onramp_id, e.to_string() ); let err_res = create_error_response( format!("Error encoding message: {}", e), event.id.to_string(), &self.onramp_id, ); simd_json::to_vec(&err_res)? // for proper error handling } }; let res = SerializedResponse { event_id: event.id.clone(), ingest_ns: event.ingest_ns, data, binary, }; tx.send(res).await?; } } } Ok(()) } async fn init(&mut self) -> Result<SourceState> { let listen_port = self.config.port; let listener = TcpListener::bind((self.config.host.as_str(), listen_port)).await?; let (tx, rx) = bounded(crate::QSIZE); let uid = self.uid; let source_url = self.onramp_id.clone(); let link = self.is_linked; make_postprocessors(self.post_processors.as_slice())?; // just for verification before starting the onramp let processors = self.post_processors.clone(); task::spawn(async move { let mut stream_id = 0; while let Ok((stream, socket)) = listener.accept().await { let uri = EventOriginUri { uid, scheme: "tremor-ws".to_string(), host: socket.ip().to_string(), port: Some(socket.port()), path: vec![listen_port.to_string()], }; stream_id += 1; task::spawn(handle_connection( source_url.clone(), tx.clone(), stream, uri, processors.clone(), stream_id, link, )); } }); self.listener = Some(rx); Ok(SourceState::Connected) } fn id(&self) -> &TremorUrl { &self.onramp_id } } #[async_trait::async_trait] impl Onramp for Ws { async fn start(&mut self, config: OnrampConfig<'_>) -> Result<onramp::Addr> { let source = Int::from_config( config.onramp_uid, self.onramp_id.clone(), config.processors.post, &self.config, config.is_linked, ); SourceManager::start(source, config).await } fn default_codec(&self) -> &str { "string" } }
mod puzzle; use crate::puzzle::Puzzle; use crate::puzzle::puzzle1; fn main() { solve_puzzle(&puzzle1::Puzzle1 {}); } fn solve_puzzle<T>(puzzle: &dyn Puzzle<T>){ let input = include_str!("puzzle1.txt"); let parsed_input = puzzle.parse_input(input); let result1 = puzzle.part1(&parsed_input); println!("{}", result1); let result2 = puzzle.part2(&parsed_input); println!("{}", result2); }
#[allow(unused_imports)] use proconio::{ input, fastout }; fn solve(d: f32, t: f32, s: f32) -> String { let ans: String; let time = d / s; if time > t { ans = "No".to_string(); } else { ans = "Yes".to_string(); } ans } fn run() -> Result<(), Box<dyn std::error::Error>> { input! { d: f32, t: f32, s: f32, } println!("{}", solve(d, t, s)); Ok(()) } fn main() { match run() { Err(err) => panic!("{}", err), _ => (), }; }
/* https://leetcode.com/problems/triangle/ */ use std::cmp; struct Solution; impl Solution { pub fn minimum_total(triangle: Vec<Vec<i32>>) -> i32 { let rows = triangle.len(); let mut dp = vec![vec![]; rows]; dp[0].push(triangle[0][0]); let mut minimum = dp[0][0]; for row in 1..rows { let cols = triangle[row].len(); for col in 0..cols { let (mut cost1, mut cost2) = (i32::MAX, i32::MAX); if col < cols - 1 { cost1 = dp[row - 1][col]; } if col > 0 { cost2 = dp[row - 1][col - 1]; } dp[row].push(triangle[row][col] + cmp::min(cost1, cost2)); if row == rows - 1 { if col == 0 { minimum = dp[row][col] } else { minimum = cmp::min(minimum, dp[row][col]) } } } } minimum } } #[test] fn test() { assert_eq!( 11, Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]]) ); assert_eq!(-10, Solution::minimum_total(vec![vec![-10]])); } /* Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] Output: 11 Explanation: The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). */
use rskafka_proto::{ApiKey, ErrorCode}; use rskafka_wire_format::error::ParseError; use std::borrow::Cow; use thiserror::Error; #[derive(Debug, Error)] #[error("kafka client error")] pub enum Error { #[error("missing {0} in config")] IncompleteConfig(&'static str), #[error("io error")] Io(#[from] std::io::Error), #[error("response parse error")] ParseError(#[from] ParseError), #[error("protocol error: {0}")] ProtocolError(Cow<'static, str>), #[error("received error response: {0} {1}")] ErrorResponse(ErrorCode, Cow<'static, str>), #[error("api not supported {:0?}, version {1}")] ApiNotSupported(ApiKey, i16), #[error("value error: {0}")] ValueError(Cow<'static, str>), #[error("cluster error: {0}")] ClusterError(String), } impl From<(ErrorCode, Option<String>)> for Error { fn from(v: (ErrorCode, Option<String>)) -> Self { Error::ErrorResponse(v.0, v.1.map(Into::into).unwrap_or("".into())) } } impl From<ErrorCode> for Error { fn from(v: ErrorCode) -> Self { (v, None).into() } }
//! https://github.com/lumen/otp/tree/lumen/lib/megaco/src/flex use super::*; test_compiles_lumen_otp!(megaco_flex_scanner); fn relative_directory_path() -> PathBuf { super::relative_directory_path().join("flex") }
pub use crate::models::{Transaction, Wallet, WatchWallet, RestoreWallet, ListWallet, Backup}; use crate::usages::{ USAGE, USAGE_TRANSACTION, USAGE_BALANCE, USAGE_LISTWALLET, USAGE_WATCHADDRESS, USAGE_RESTOREWALLET, USAGE_BACKUP, USAGE_GETWALLET }; #[derive(Debug, Eq, PartialEq)] pub enum Cmd { Transaction(Transaction), Balance(String), GetWallet(Wallet), ListWallet(ListWallet), WatchOnly(WatchWallet), Restore(RestoreWallet), Backup(Backup), Version, Help(String), } pub fn print_usage(cmd: String) { match &cmd[..] { "operation" => println!("{}", &USAGE[1..]), "transfer" => println!("{}", &USAGE_TRANSACTION[1..]), "balance" => println!("{}", &USAGE_BALANCE[1..]), "getnewaddress" => println!("{}", &USAGE_GETWALLET[1..]), "listaddresses" => println!("{}", &USAGE_LISTWALLET[1..]), "watchaddress" => println!("{}", &USAGE_WATCHADDRESS[1..]), "restore" => println!("{}", &USAGE_RESTOREWALLET[1..]), "backup" => println!("{}", &USAGE_BACKUP[1..]), _ => println!( "'{}' is not a Operation command. See 'operation --help'.", cmd ), } } pub fn print_version() { println!("operation version 0.1.0"); } enum Arg<T> { Plain(T), Short(T), Long(T), } impl Arg<String> { fn as_ref(&self) -> Arg<&str> { match *self { Arg::Plain(ref x) => Arg::Plain(&x[..]), Arg::Short(ref x) => Arg::Short(&x[..]), Arg::Long(ref x) => Arg::Long(&x[..]), } } #[allow(dead_code)] fn into_string(self) -> String { match self { Arg::Plain(x) => x, Arg::Short(x) => x, Arg::Long(x) => x, } } } impl std::fmt::Display for Arg<String> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match *self { Arg::Plain(ref x) => write!(f, "{}", x), Arg::Short(ref x) => write!(f, "-{}", x), Arg::Long(ref x) => write!(f, "--{}", x), } } } struct ArgIter { args: std::vec::IntoIter<String>, is_raw: bool, leftover: Option<String>, } impl ArgIter { pub fn new(args: Vec<String>) -> ArgIter { ArgIter { args: args.into_iter(), is_raw: false, leftover: None, } } } impl Iterator for ArgIter { type Item = Arg<String>; fn next(&mut self) -> Option<Arg<String>> { if self.leftover.is_some() { return self.leftover.take().map(Arg::Plain); } let arg = self.args.next()?; if self.is_raw { return Some(Arg::Plain(arg)); } if &arg == "--" { self.is_raw = true; return self.next(); } if arg.starts_with("--") { let mut flag = String::from(&arg[2..]); if let Some(i) = flag.find('=') { self.leftover = Some(flag.split_off(i + 1)); flag.truncate(i); } return Some(Arg::Long(flag)); } if arg.starts_with("-") { let mut flag = String::from(&arg[1..]); if flag.len() > 1 { self.leftover = Some(flag.split_off(1)); flag.truncate(1); } return Some(Arg::Short(flag)); } Some(Arg::Plain(arg)) } } pub fn parse(argv: Vec<String>) -> Result<Cmd, String> { let mut args = ArgIter::new(argv); // Skip executable name. args.next(); let arg = match args.next() { Some(a) => a, None => return Err("No command provided. See --help.".to_string()), }; match arg.as_ref() { Arg::Plain("transfer") => parse_transaction(args), Arg::Plain("balance") => parse_balance(args), Arg::Plain("getnewaddress") => parse_get_wallet(args), Arg::Plain("listaddresses") => parse_list_wallet(args), Arg::Plain("watchaddress") => parse_watchonly(args), Arg::Plain("restore") => parse_restore(args), Arg::Plain("backup") => parse_backup(args), Arg::Long("version") => drain(args).and(Ok(Cmd::Version)), Arg::Short("h") | Arg::Long("help") => parse_help(args), _ => return unexpected(arg), } } fn parse_balance(mut args: ArgIter) -> Result<Cmd, String> { let mut total_issuance: bool = false; let mut accountid: Option<String> = None; while let Some(arg) = args.next() { match arg.as_ref() { Arg::Short("t") | Arg::Long("total-issuance") => total_issuance = true, Arg::Short("f") | Arg::Long("free-balance") => { let msg = "Expected account id after --free-balance."; accountid = Some(expect_plain(&mut args, msg)?); } Arg::Short("h") | Arg::Long("help") => return drain_help(args, "balance"), _ => return unexpected(arg), } } if total_issuance { Ok(Cmd::Balance("total-issuance".to_string())) } else { let accountid = match accountid { Some(id) => id, None => "".to_owned() }; Ok(Cmd::Balance(accountid)) } } fn parse_list_wallet(mut args: ArgIter) -> Result<Cmd, String> { let mut location: Option<String> = None; while let Some(arg) = args.next() { match arg.as_ref() { Arg::Short("l") | Arg::Long("location") => { let msg = "Expected path or directoty after --location."; location = Some(expect_plain(&mut args, msg)?); } Arg::Short("h") | Arg::Long("help") => return drain_help(args, "listaddresses"), _ => return unexpected(arg), } } Ok(Cmd::ListWallet(ListWallet { location })) } fn parse_watchonly(mut args: ArgIter) -> Result<Cmd, String> { let mut location: Option<String> = None; let mut name: Option<String> = None; let mut address: Option<String> = None; while let Some(arg) = args.next() { match arg.as_ref() { Arg::Short("a") | Arg::Long("addr") => { let msg = "Expected account address after --location."; address = Some(expect_plain(&mut args, msg)?); } Arg::Short("l") | Arg::Long("location") => { let msg = "Expected path or directoty after --location."; location = Some(expect_plain(&mut args, msg)?); } Arg::Short("n") | Arg::Long("name") => { let msg = "Expected account name after --name."; name = Some(expect_plain(&mut args, msg)?); } Arg::Short("h") | Arg::Long("help") => return drain_help(args, "watchaddress"), _ => return unexpected(arg), } } Ok(Cmd::WatchOnly(WatchWallet { location, name, address, })) } fn parse_restore(mut args: ArgIter) -> Result<Cmd, String> { let mut location: Option<String> = None; let mut file: Option<String> = None; let mut password: Option<String> = None; while let Some(arg) = args.next() { match arg.as_ref() { Arg::Short("f") | Arg::Long("file") => { let msg = "Expected file diretory or path after --location."; file = Some(expect_plain(&mut args, msg)?); } Arg::Short("l") | Arg::Long("location") => { let msg = "Expected path or directoty after --location."; location = Some(expect_plain(&mut args, msg)?); } Arg::Short("p") | Arg::Long("password") => { let msg = "Expected password after --password."; password = Some(expect_plain(&mut args, msg)?); } Arg::Short("h") | Arg::Long("help") => return drain_help(args, "restore"), _ => return unexpected(arg), } } Ok(Cmd::Restore(RestoreWallet { location, file, password, })) } fn parse_backup(mut args: ArgIter) -> Result<Cmd, String> { let mut location: Option<String> = None; let mut address: Option<String> = None; let mut file: Option<String> = None; let mut password: Option<String> = None; while let Some(arg) = args.next() { match arg.as_ref() { Arg::Short("f") | Arg::Long("file") => { let msg = "Expected file diretory or path after --location."; file = Some(expect_plain(&mut args, msg)?); } Arg::Short("l") | Arg::Long("location") => { let msg = "Expected path or directoty after --location."; location = Some(expect_plain(&mut args, msg)?); } Arg::Short("a") | Arg::Long("addr") => { let msg = "Expected account address after --name."; address = Some(expect_plain(&mut args, msg)?); } Arg::Short("p") | Arg::Long("password") => { let msg = "Expected password after --password."; password = Some(expect_plain(&mut args, msg)?); } Arg::Short("h") | Arg::Long("help") => return drain_help(args, "backup"), _ => return unexpected(arg), } } Ok(Cmd::Backup(Backup { location, address, file, password, })) } fn parse_get_wallet(mut args: ArgIter) -> Result<Cmd, String> { let mut ed25519: bool = false; let mut ecdsa: bool = false; let mut sr25519: bool = false; let mut password: Option<String> = None; let mut name: Option<String> = None; let mut location: Option<String> = None; let mut phrase: Option<String> = None; while let Some(arg) = args.next() { match arg.as_ref() { Arg::Short("e") | Arg::Long("ed25519") => ed25519 = true, Arg::Short("k") | Arg::Long("ecdsa") => ecdsa = true, Arg::Short("s") | Arg::Long("sr25519") => sr25519 = true, Arg::Short("p") | Arg::Long("password") => { let msg = "Expected password after --password."; password = Some(expect_plain(&mut args, msg)?); } Arg::Short("n") | Arg::Long("name") => { let msg = "Expected account name after --name."; name = Some(expect_plain(&mut args, msg)?); } Arg::Short("l") | Arg::Long("location") => { let msg = "Expected path or directoty after --location."; location = Some(expect_plain(&mut args, msg)?); } Arg::Long("phrase") => { let msg = "Expected mnemonic or seed after --phrase."; phrase = Some(expect_plain(&mut args, msg)?); } Arg::Short("h") | Arg::Long("help") => return drain_help(args, "getnewaddress"), _ => return unexpected(arg), } } let label: &str; if ed25519 { label = "ed25519"; } else if ecdsa { label = "ed25519"; } else if sr25519 { label = "sr25519"; } else { label = "sr25519"; }; Ok(Cmd::GetWallet(Wallet { label: label.to_string(), password, name, location, phrase, })) } fn parse_transaction(mut args: ArgIter) -> Result<Cmd, String> { let mut sender: String = "".into(); let mut receiver: String = "".into(); let mut amount: String = "".into(); let mut location: Option<String> = None; while let Some(arg) = args.next() { match arg.as_ref() { Arg::Short("s") | Arg::Long("sender") => { let msg = "Expected account after --sender."; sender = expect_plain(&mut args, msg)?; } Arg::Short("r") | Arg::Long("receiver") => { let msg = "Expected account id after --receiver."; receiver = expect_plain(&mut args, msg)?; } Arg::Short("a") | Arg::Long("amount") => { let msg = "Expected amount of token after --amount."; amount = expect_plain(&mut args, msg)?; } Arg::Short("l") | Arg::Long("location") => { let msg = "Expected path or directoty after --location."; location = Some(expect_plain(&mut args, msg)?); } Arg::Short("h") | Arg::Long("help") => return drain_help(args, "transfer"), _ => return unexpected(arg), } } let transfer = Transaction { sender, receiver, amount, location, }; Ok(Cmd::Transaction(transfer)) } fn parse_help(mut args: ArgIter) -> Result<Cmd, String> { match args.next() { Some(Arg::Plain(cmd)) => drain(args).and(Ok(Cmd::Help(cmd))), Some(arg) => unexpected(arg), None => Ok(Cmd::Help("operation".to_string())), } } fn drain_help(args: ArgIter, cmd: &'static str) -> Result<Cmd, String> { drain(args).and(Ok(Cmd::Help(cmd.to_string()))) } fn expect_plain(args: &mut ArgIter, msg: &'static str) -> Result<String, String> { match args.next() { Some(Arg::Plain(a)) => Ok(a), Some(arg) => Err(format!("Unexpected argument '{}'. {}", arg, msg)), None => Err(msg.to_string()), } } fn drain(args: ArgIter) -> Result<(), String> { for arg in args { return unexpected::<()>(arg); } Ok(()) } fn unexpected<T>(arg: Arg<String>) -> Result<T, String> { Err(format!( "Unexpected argument '{}'. See 'operation --help'.", arg )) }
use super::*; #[test] fn sends_message_when_timer_expires() { run!( |arc_process| { ( Just(arc_process.clone()), milliseconds(), strategy::term(arc_process.clone()), ) }, |(arc_process, milliseconds, message)| { let time = arc_process.integer(milliseconds); let destination_arc_process = test::process::child(&arc_process); let destination = destination_arc_process.pid_term(); let options = options(&arc_process); prop_assert_badarg!( result(arc_process.clone(), time, destination, message, options), "supported option is {:abs, bool}" ); Ok(()) }, ); }
use anyhow::anyhow; use std::sync::Arc; use std::thread; fn main() -> anyhow::Result<()> { for _ in 0..100 { let thread = Arc::new(ste::spawn()); let mut threads = Vec::new(); for _ in 0..2 { let thread = thread.clone(); let t = thread::spawn(move || { thread.submit(|| { thread::sleep(std::time::Duration::from_millis(10)); panic!("trigger"); }) }); threads.push(t); } for t in threads { assert!(t.join().is_err()); } let thread = Arc::try_unwrap(thread).map_err(|_| anyhow!("unwrap failed"))?; thread.join(); } Ok(()) }
use crate::librb::socklen_t; use libc; use libc::sockaddr; use libc::sockaddr_in; use libc::sockaddr_in6; extern "C" { pub type sockaddr_x25; pub type sockaddr_un; pub type sockaddr_ns; pub type sockaddr_iso; pub type sockaddr_ipx; pub type sockaddr_inarp; pub type sockaddr_eon; pub type sockaddr_dl; pub type sockaddr_ax25; pub type sockaddr_at; #[no_mangle] fn getsockname(__fd: libc::c_int, __addr: __SOCKADDR_ARG, __len: *mut socklen_t) -> libc::c_int; } pub type __socklen_t = libc::c_uint; #[repr(C)] #[derive(Copy, Clone)] pub union __SOCKADDR_ARG { pub __sockaddr__: *mut sockaddr, pub __sockaddr_at__: *mut sockaddr_at, pub __sockaddr_ax25__: *mut sockaddr_ax25, pub __sockaddr_dl__: *mut sockaddr_dl, pub __sockaddr_eon__: *mut sockaddr_eon, pub __sockaddr_in__: *mut sockaddr_in, pub __sockaddr_in6__: *mut sockaddr_in6, pub __sockaddr_inarp__: *mut sockaddr_inarp, pub __sockaddr_ipx__: *mut sockaddr_ipx, pub __sockaddr_iso__: *mut sockaddr_iso, pub __sockaddr_ns__: *mut sockaddr_ns, pub __sockaddr_un__: *mut sockaddr_un, pub __sockaddr_x25__: *mut sockaddr_x25, } #[repr(C)] #[derive(Copy, Clone)] pub union C2RustUnnamed { pub __u6_addr8: [u8; 16], pub __u6_addr16: [u16; 8], pub __u6_addr32: [u32; 4], } pub type in_port_t = u16; pub type in_addr_t = u32; pub unsafe fn bb_getsockname( mut sockfd: libc::c_int, mut addr: *mut libc::c_void, mut addrlen: socklen_t, ) -> libc::c_int { /* The usefullness of this function is that for getsockname(), * addrlen must go on stack (to _have_ an address to be passed), * but many callers do not need its modified value. * By using this shim, they can avoid unnecessary stack spillage. */ return getsockname( sockfd, __SOCKADDR_ARG { __sockaddr__: addr as *mut sockaddr, }, &mut addrlen, ); }
use super::*; // `returns_binary` in integration tests // `is_the_same_as_float_to_binary_2_with_scientific_20` in integration tests #[test] fn is_dual_of_binary_to_float_1() { with_process_arc(|arc_process| { TestRunner::new(Config::with_source_file(file!())) .run(&strategy::term::float(arc_process.clone()), |float| { let result_binary = result(&arc_process, float, options(&arc_process)); prop_assert!(result_binary.is_ok()); let binary = result_binary.unwrap(); prop_assert_eq!(binary_to_float_1::result(&arc_process, binary), Ok(float)); Ok(()) }) .unwrap(); }); } fn options(_: &Process) -> Term { Term::NIL }
pub fn add(x: i32, y: i32) -> i32 { x + y } #[ test ] fn test_add() { assert_eq!(0, add(0, 0)); assert_ne!(0, add(0, 1)); }
use std::fmt; use std::error::Error; use value::Value; use value::Value::*; use self::FilterError::*; #[derive(Debug)] pub enum FilterError { InvalidType(String), InvalidArgumentCount(String), InvalidArgument(u16, String), // (position, "expected / given ") } impl FilterError { pub fn invalid_type<T>(s: &str) -> Result<T, FilterError> { Err(FilterError::InvalidType(s.to_owned())) } } impl fmt::Display for FilterError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidType(ref e) => write!(f, "Invalid type : {}", e), InvalidArgumentCount(ref e) => write!(f, "Invalid number of arguments : {}", e), InvalidArgument(ref pos, ref e) => { write!(f, "Invalid argument given at position {} : {}", pos, e) } } } } impl Error for FilterError { fn description(&self) -> &str { match *self { InvalidType(ref e) | InvalidArgumentCount(ref e) | InvalidArgument(_, ref e) => e, } } } pub type FilterResult = Result<Value, FilterError>; pub type Filter = Fn(&Value, &[Value]) -> FilterResult; pub fn size(input: &Value, _args: &[Value]) -> FilterResult { match *input { Str(ref x) => Ok(Num(x.len() as f32)), Array(ref x) => Ok(Num(x.len() as f32)), Object(ref x) => Ok(Num(x.len() as f32)), _ => Err(InvalidType("String, Array or Object expected".to_owned())), } } pub fn upcase(input: &Value, _args: &[Value]) -> FilterResult { match *input { Str(ref s) => Ok(Str(s.to_uppercase())), _ => Err(InvalidType("String expected".to_owned())), } } pub fn minus(input: &Value, args: &[Value]) -> FilterResult { let num = match *input { Num(n) => n, _ => return Err(InvalidType("Num expected".to_owned())), }; match args.first() { Some(&Num(x)) => Ok(Num(num - x)), _ => Err(InvalidArgument(0, "Num expected".to_owned())), } } pub fn plus(input: &Value, args: &[Value]) -> FilterResult { let num = match *input { Num(n) => n, _ => return Err(InvalidType("Num expected".to_owned())), }; match args.first() { Some(&Num(x)) => Ok(Num(num + x)), _ => Err(InvalidArgument(0, "Num expected".to_owned())), } } pub fn times(input: &Value, args: &[Value]) -> FilterResult { let num = match *input { Num(n) => n, _ => return Err(InvalidType("Num expected".to_owned())), }; match args.first() { Some(&Num(x)) => Ok(Num(num * x)), _ => Err(InvalidArgument(0, "Num expected".to_owned())), } } pub fn divided_by(input: &Value, args: &[Value]) -> FilterResult { let num = match *input { Num(n) => n, _ => return Err(InvalidType("Num expected".to_owned())), }; match args.first() { Some(&Num(x)) => Ok(Num((num / x).floor())), _ => Err(InvalidArgument(0, "Num expected".to_owned())), } } pub fn floor(input: &Value, _args: &[Value]) -> FilterResult { match *input { Num(n) => Ok(Num(n.floor())), _ => Err(InvalidType("Num expected".to_owned())), } } pub fn ceil(input: &Value, _args: &[Value]) -> FilterResult { match *input { Num(n) => Ok(Num(n.ceil())), _ => Err(InvalidType("Num expected".to_owned())), } } pub fn round(input: &Value, _args: &[Value]) -> FilterResult { match *input { Num(n) => Ok(Num(n.round())), _ => Err(InvalidType("Num expected".to_owned())), } } pub fn replace(input: &Value, args: &[Value]) -> FilterResult { if args.len() != 2 { return Err(InvalidArgumentCount(format!("expected 2, {} given", args.len()))); } match *input { Str(ref x) => { let arg1 = match args[0] { Str(ref a) => a, _ => return Err(InvalidArgument(0, "Str expected".to_owned())), }; let arg2 = match args[1] { Str(ref a) => a, _ => return Err(InvalidArgument(1, "Str expected".to_owned())), }; Ok(Str(x.replace(arg1, arg2))) } _ => Err(InvalidType("String expected".to_owned())), } } #[cfg(test)] mod tests { use value::Value::*; use super::*; macro_rules! unit { ( $a:ident, $b:expr ) => {{ unit!($a, $b, &[]) }}; ( $a:ident, $b:expr , $c:expr) => {{ $a(&$b, $c).unwrap() }}; } macro_rules! tos { ( $a:expr ) => {{ Str($a.to_owned()) }}; } #[test] fn unit_size() { assert_eq!(unit!(size, tos!("abc")), Num(3f32)); assert_eq!(unit!(size, tos!("this has 22 characters")), Num(22f32)); } #[test] fn unit_upcase() { assert_eq!(unit!(upcase, tos!("abc")), tos!("ABC")); assert_eq!(unit!(upcase, tos!("Hello World 21")), tos!("HELLO WORLD 21")); } #[test] fn unit_minus() { assert_eq!(unit!(minus, Num(2f32), &[Num(1f32)]), Num(1f32)); assert_eq!(unit!(minus, Num(21.5), &[Num(1.25)]), Num(20.25)); } #[test] fn unit_plus() { assert_eq!(unit!(plus, Num(2f32), &[Num(1f32)]), Num(3f32)); assert_eq!(unit!(plus, Num(21.5), &[Num(2.25)]), Num(23.75)); } #[test] fn unit_times() { assert_eq!(unit!(times, Num(2f32), &[Num(3f32)]), Num(6f32)); assert_eq!(unit!(times, Num(8.5), &[Num(0.5)]), Num(4.25)); assert!(times(&Bool(true), &[Num(8.5)]).is_err()); assert!(times(&Num(2.5), &[Bool(true)]).is_err()); assert!(times(&Num(2.5), &[]).is_err()); } #[test] fn unit_divided_by() { assert_eq!(unit!(divided_by, Num(4f32), &[Num(2f32)]), Num(2f32)); assert_eq!(unit!(divided_by, Num(5f32), &[Num(2f32)]), Num(2f32)); assert!(divided_by(&Bool(true), &[Num(8.5)]).is_err()); assert!(divided_by(&Num(2.5), &[Bool(true)]).is_err()); assert!(divided_by(&Num(2.5), &[]).is_err()); } #[test] fn unit_floor() { assert_eq!(unit!(floor, Num(1.1f32), &[]), Num(1f32)); assert_eq!(unit!(floor, Num(1f32), &[]), Num(1f32)); assert!(floor(&Bool(true), &[]).is_err()); } #[test] fn unit_ceil() { assert_eq!(unit!(ceil, Num(1.1f32), &[]), Num(2f32)); assert_eq!(unit!(ceil, Num(1f32), &[]), Num(1f32)); assert!(ceil(&Bool(true), &[]).is_err()); } #[test] fn unit_round() { assert_eq!(unit!(round, Num(1.1f32), &[]), Num(1f32)); assert_eq!(unit!(round, Num(1.5f32), &[]), Num(2f32)); assert_eq!(unit!(round, Num(2f32), &[]), Num(2f32)); assert!(round(&Bool(true), &[]).is_err()); } #[test] fn unit_replace() { assert_eq!(unit!(replace, tos!("barbar"), &[tos!("bar"), tos!("foo")]), tos!("foofoo")); } }
#![cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use crate::detail::sandwich::{sw012, sw_mm_three, sw_mm_two}; use crate::detail::sse::{dp_bc, hi_dp_bc, rcp_nr1, rsqrt_nr1}; use crate::util::ApplyTo; use crate::{Branch, Line, Plane, Point}; #[derive(Default)] pub struct EulerAngles { pub roll: f32, pub pitch: f32, pub yaw: f32, } impl EulerAngles { pub fn new(roll: f32, pitch: f32, yaw: f32) -> EulerAngles { EulerAngles { roll, pitch, yaw } } } /// \defgroup rotor Rotors /// /// The rotor is an entity that represents a rigid rotation about an axis. /// To apply the rotor to a supported entity, the call operator is available. /// /// !!! example /// /// ```c++ /// // Initialize a point at (1, 3, 2) /// kln::point p{1.f, 3.f, 2.f}; /// /// // Create a normalized rotor representing a pi/2 radian /// // rotation about the xz-axis. /// kln::rotor r{kln::pi * 0.5f, 1.f, 0.f, 1.f}; /// /// // Rotate our point using the created rotor /// kln::point rotated = r(p); /// ``` /// We can rotate lines and planes as well using the rotor's call operator. /// /// Rotors can be multiplied to one another with the `*` operator to create /// a new rotor equivalent to the application of each factor. /// /// !!! example /// /// ```c++ /// // Create a normalized rotor representing a $\frac{\pi}{2}$ radian /// // rotation about the xz-axis. /// kln::rotor r1{kln::pi * 0.5f, 1.f, 0.f, 1.f}; /// /// // Create a second rotor representing a $\frac{\pi}{3}$ radian /// // rotation about the yz-axis. /// kln::rotor r2{kln::pi / 3.f, 0.f, 1.f, 1.f}; /// /// // Use the geometric product to create a rotor equivalent to first /// // applying r1, then applying r2. Note that the order of the /// // operands here is significant. /// kln::rotor r3 = r2 * r1; /// ``` /// /// The same `*` operator can be used to compose the rotor's action with other /// translators and motors. #[derive(Copy, Clone, Debug)] pub struct Rotor { pub p1_: __m128, } common_operations!(Rotor, p1_); impl Rotor { get_basis_blade_fn!(e12, e21, p1_, 3); get_basis_blade_fn!(e31, e13, p1_, 2); get_basis_blade_fn!(e23, e32, p1_, 1); } use std::fmt; impl fmt::Display for Rotor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "\nRotor:\tScalar\te23\te31\te12\n\t{:.3}\t{:.3}\t{:.3}\t{:.3}\n", self.scalar(), self.e23(), self.e32(), self.e12(), ) } } impl From<&EulerAngles> for Rotor { fn from(ea: &EulerAngles) -> Self { // pub fn from_euler_angles(ea: &EulerAngles) -> Rotor { // https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles#cite_note-3 let half_yaw: f32 = ea.yaw * 0.5; let half_pitch: f32 = ea.pitch * 0.5; let half_roll: f32 = ea.roll * 0.5; let cos_y: f32 = f32::cos(half_yaw); let sin_y: f32 = f32::sin(half_yaw); let cos_p: f32 = f32::cos(half_pitch); let sin_p: f32 = f32::sin(half_pitch); let cos_r: f32 = f32::cos(half_roll); let sin_r: f32 = f32::sin(half_roll); unsafe { let p1_ = _mm_set_ps( cos_r * cos_p * sin_y - sin_r * sin_p * cos_y, cos_r * sin_p * cos_y + sin_r * cos_p * sin_y, sin_r * cos_p * cos_y - cos_r * sin_p * sin_y, cos_r * cos_p * cos_y + sin_r * sin_p * sin_y, ); Rotor::from(p1_).normalized() } } } impl From<Rotor> for EulerAngles { fn from(rotor: Rotor) -> EulerAngles { let pi = std::f32::consts::PI; let pi_2 = pi / 2.; let mut ea = EulerAngles::default(); #[repr(align(16))] struct ArrayAlignedTo16ByteBoundary { mem: [f32; 4], }; let mut buf = ArrayAlignedTo16ByteBoundary { mem: <[f32; 4]>::default(), }; rotor.store(&mut buf.mem[0]); let test = buf.mem[1] * buf.mem[2] + buf.mem[3] * buf.mem[0]; if test > 0.4999 { ea.roll = 2. * f32::atan2(buf.mem[1], buf.mem[0]); ea.pitch = pi_2; ea.yaw = 0.; return ea; } else if test < -0.4999 { ea.roll = -2. * f32::atan2(buf.mem[1], buf.mem[0]); ea.pitch = -pi_2; ea.yaw = 0.; return ea; } let buf1_2 = buf.mem[1] * buf.mem[1]; let buf2_2 = buf.mem[2] * buf.mem[2]; let buf3_2 = buf.mem[3] * buf.mem[3]; ea.roll = f32::atan2( 2. * (buf.mem[0] * buf.mem[1] + buf.mem[2] * buf.mem[3]), 1. - 2. * (buf1_2 + buf2_2), ); let sinp = 2. * (buf.mem[0] * buf.mem[2] - buf.mem[1] * buf.mem[3]); if f32::abs(sinp) > 1. { ea.pitch = f32::copysign(pi_2, sinp); } else { ea.pitch = f32::asin(sinp); } ea.yaw = f32::atan2( 2. * (buf.mem[0] * buf.mem[3] + buf.mem[1] * buf.mem[2]), 1. - 2. * (buf2_2 + buf3_2), ); ea } } impl Rotor { /// Convenience constructor. Computes transcendentals and normalizes /// rotation axis. pub fn new(ang_rad: f32, x: f32, y: f32, z: f32) -> Rotor { let norm: f32 = f32::sqrt(x * x + y * y + z * z); let inv_norm: f32 = 1. / norm; let half: f32 = 0.5 * ang_rad; // Rely on compiler to coalesce these two assignments into a single // sincos call at instruction selection time let sin_ang = f32::sin(half); let scale = sin_ang * inv_norm; unsafe { let mut p1_ = _mm_set_ps(z, y, x, f32::cos(half)); p1_ = _mm_mul_ps(p1_, _mm_set_ps(scale, scale, scale, 1.)); Rotor::from(p1_) } } /// Fast load operation for packed data that is already normalized. The /// argument `data` should point to a set of 4 float values with layout `(a, /// b, c, d)` corresponding to the multivector /// $a + b\mathbf{e}_{23} + c\mathbf{e}_{31} + d\mathbf{e}_{12}$. /// /// !!! danger /// /// The rotor data loaded this way *must* be normalized. That is, the /// rotor $r$ must satisfy $r\widetilde{r} = 1$. pub fn load_normalized(&mut self, data: &f32) { unsafe { self.p1_ = _mm_loadu_ps(data); } } /// Constrains the rotor to traverse the shortest arc pub fn constrain(&mut self) { unsafe { let um = _mm_and_ps(self.p1_, _mm_set_ss(-0.)); let mask: __m128 = _mm_shuffle_ps(um, um, 0); self.p1_ = _mm_xor_ps(mask, self.p1_); } } pub fn constrained(self) -> Rotor { let mut out = Rotor::clone(&self); out.constrain(); out } /// Store m128 contents into an array of 4 floats pub fn store(self, out: &mut f32) { unsafe { _mm_store_ps(&mut *out, self.p1_); } } pub fn invert(&mut self) { let inv_norm: __m128 = rsqrt_nr1(hi_dp_bc(self.p1_, self.p1_)); unsafe { self.p1_ = _mm_mul_ps(self.p1_, inv_norm); self.p1_ = _mm_mul_ps(self.p1_, inv_norm); self.p1_ = _mm_xor_ps(_mm_set_ps(-0., -0., -0., 0.), self.p1_); } } pub fn inverse(self) -> Self { let mut out = Self::from(self.p1_); out.invert(); out } pub fn normalize(&mut self) { unsafe { let inv_norm: __m128 = rsqrt_nr1(dp_bc(self.p1_, self.p1_)); self.p1_ = _mm_mul_ps(self.p1_, inv_norm); } } pub fn scalar(self) -> f32 { let mut out: f32 = 0.; unsafe { _mm_store_ss(&mut out, self.p1_); } out } } use std::ops::Neg; impl Neg for Rotor { type Output = Self; /// Unary minus #[inline] fn neg(self) -> Self::Output { Self::from(unsafe { _mm_xor_ps(self.p1_, _mm_set1_ps(-0.)) }) } } impl PartialEq for Rotor { fn eq(&self, other: &Rotor) -> bool { unsafe { _mm_movemask_ps(_mm_cmpeq_ps(self.p1_, other.p1_)) == 0b1111 } } } impl ApplyTo<Branch> for Rotor { fn apply_to(self, rhs: Branch) -> Branch { Branch { p1_: sw_mm_two(rhs.p1_, self.p1_), } } } // [[nodiscard]] line KLN_VEC_CALL operator()(line const& l) const noexcept impl ApplyTo<Line> for Rotor { /// Conjugates a line $\ell$ with this rotor and returns the result /// $r\ell \widetilde{r}$. fn apply_to(self, l: Line) -> Line { let (branch, ideal) = sw_mm_three(l.p1_, l.p2_, self.p1_); Line::from(branch, ideal) } } impl ApplyTo<Point> for Rotor { /// Conjugates a point $p$ with this rotor and returns the result /// $rp\widetilde{r}$. fn apply_to(self, p: Point) -> Point { // NOTE: Conjugation of a plane and point with a rotor is identical unsafe { Point::from(sw012(false, p.p3_, self.p1_, _mm_setzero_ps())) } } } impl ApplyTo<Plane> for Rotor { /// Conjugates a plane $p$ with this rotor and returns the result /// $rp\widetilde{r}$. fn apply_to(self, p: Plane) -> Plane { unsafe { Plane::from(sw012(false, p.p0_, self.p1_, _mm_setzero_ps())) } } } #[cfg(test)] mod tests { #![cfg(target_arch = "x86_64")] use std::arch::x86_64::*; fn approx_eq(a: f32, b: f32) { assert!((a - b).abs() < 1e-6) } use crate::{sqrt, ApplyTo, EulerAngles, Line, Point, Rotor}; #[test] fn rotor_line() { // Make an unnormalized rotor to verify correctness let data: [f32; 4] = [1., 4., -3., 2.]; let mut r = Rotor::default(); r.load_normalized(&data[0]); // a*e01 + b*e01 + c*e02 + d*e23 + e*e31 + f*e12 let l1 = Line::new(-1., 2., -3., -6., 5., 4.); let l2 = r.apply_to(l1); assert_eq!(l2.e01(), -110.); assert_eq!(l2.e02(), 20.); assert_eq!(l2.e03(), 10.); assert_eq!(l2.e12(), -240.); assert_eq!(l2.e31(), 102.); assert_eq!(l2.e23(), -36.); } #[test] fn rotor_point() { let pi = std::f32::consts::PI; let r = Rotor::new(pi * 0.5, 0., 0., 1.); let p1 = Point::new(1., 0., 0.); let p2: Point = r.apply_to(p1); assert_eq!(p2.x(), 0.); approx_eq(p2.y(), -1.); //approx assert_eq!(p2.z(), 0.); } #[test] fn euler_angles_precision() { let pi = std::f32::consts::PI; let ea1 = EulerAngles::new(pi * 0.2, pi * 0.2, 0.); let r1 = Rotor::from(&ea1); let ea2 = EulerAngles::from(r1); approx_eq(ea1.roll, ea2.roll); approx_eq(ea1.pitch, ea2.pitch); approx_eq(ea1.yaw, ea2.yaw); } #[test] fn euler_angles() { // Make 3 rotors about the x, y, and z-axes. let rx = Rotor::new(1., 1., 0., 0.); let ry = Rotor::new(1., 0., 1., 0.); let rz = Rotor::new(1., 0., 0., 1.); let r: Rotor = rx * ry * rz; let ea = EulerAngles::from(r); approx_eq(ea.roll, 1.); approx_eq(ea.pitch, 1.); approx_eq(ea.yaw, 1.); let r2 = Rotor::from(&ea); #[repr(align(16))] struct ArrayAlignedTo16ByteBoundary { mem: [f32; 8], }; let mut buf = ArrayAlignedTo16ByteBoundary { mem: <[f32; 8]>::default(), }; //let mut buf = <[f32; 8]>::default(); r.store(&mut buf.mem[0]); r2.store(&mut buf.mem[4]); for i in 0..4 { approx_eq(buf.mem[i], buf.mem[i + 4]); } } #[test] fn rotor_constrain() { let mut r1 = Rotor::new(1., 2., 3., 4.); let mut r2 = r1.constrained(); assert_eq!(r1, r2); r1 = -r1; r2 = r1.constrained(); assert_eq!(r1, -r2); } #[test] fn rotor_sqrt() { let pi = std::f32::consts::PI; let r = Rotor::new(pi * 0.5, 1., 2., 3.); let mut r2: Rotor = sqrt(r); r2 = r2 * r2; approx_eq(r2.scalar(), r.scalar()); approx_eq(r2.e23(), r.e23()); approx_eq(r2.e31(), r.e31()); approx_eq(r2.e12(), r.e12()); } #[test] fn normalize_rotor() { unsafe { let mut r = Rotor::from(_mm_set_ps(4., -3., 3., 28.)); // r.p1_ = _mm_set_ps(4.f, -3.f, 3.f, 28.f); r.normalize(); let norm: Rotor = r * r.reverse(); approx_eq(norm.scalar(), 1.); approx_eq(norm.e12(), 0.); approx_eq(norm.e31(), 0.); approx_eq(norm.e23(), 0.); } } }
/// Custom string implemenation. /// /// There is a lot of unsafe code here. Many of the features here can and were implementable in /// terms of safe code using enums, and various components of the standard library. We moved to /// this representation because it significanly improved some benchmarks in terms of time and /// space, and it also makes for more ergonomic interop with LLVM. /// /// TODO explain more about what is going on here. use crate::pushdown::FieldSet; use crate::runtime::{Float, Int}; use regex::bytes::Regex; use smallvec::SmallVec; use std::alloc::{alloc_zeroed, dealloc, realloc, Layout}; use std::cell::{Cell, UnsafeCell}; use std::hash::{Hash, Hasher}; use std::io::{self, Write}; use std::marker::PhantomData; #[cfg(feature = "unstable")] use std::intrinsics::likely; #[cfg(not(feature = "unstable"))] fn likely(b: bool) -> bool { b } use std::mem; use std::ptr; use std::rc::Rc; use std::slice; use std::str; #[derive(Copy, Clone, Eq, PartialEq, Debug)] #[repr(usize)] enum StrTag { Inline = 0, Literal = 1, Shared = 2, Concat = 3, Boxed = 4, } const NUM_VARIANTS: usize = 5; impl StrTag { fn forced(self) -> bool { use StrTag::*; match self { Literal | Boxed | Inline => true, Concat | Shared => false, } } } // Why the repr(C)? We may rely on the lengths coming first. #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(transparent)] struct Inline(u128); const MAX_INLINE_SIZE: usize = 15; impl Default for Inline { fn default() -> Inline { Inline(StrTag::Inline as u128) } } impl Inline { unsafe fn from_raw(ptr: *const u8, len: usize) -> Inline { debug_assert!(len <= MAX_INLINE_SIZE); if len > MAX_INLINE_SIZE { std::hint::unreachable_unchecked(); } let mut res = ((len << 3) | StrTag::Inline as usize) as u128; ptr::copy_nonoverlapping( ptr, mem::transmute::<&mut u128, *mut u8>(&mut res).offset(1), len, ); Inline(res) } unsafe fn from_unchecked(bs: &[u8]) -> Inline { Self::from_raw(bs.as_ptr(), bs.len()) } fn len(&self) -> usize { (self.0 as usize & 0xFF) >> 3 } fn bytes(&self) -> &[u8] { unsafe { slice::from_raw_parts( mem::transmute::<&Inline, *const u8>(self).offset(1), self.len(), ) } } #[inline(always)] fn itoa(i: Int) -> Option<Inline> { if i > 999999999999999 || i < -99999999999999 { return None; } let mut res = 0u128; let buf = unsafe { slice::from_raw_parts_mut((&mut res as *mut _ as *mut u8).offset(1), 15) }; let len = itoa::write(buf, i).unwrap(); Some(Inline(res | ((len << 3) | StrTag::Inline as usize) as u128)) } } #[derive(Clone)] #[repr(C)] struct Literal<'a> { ptr: *const u8, len: u64, _marker: PhantomData<&'a ()>, } #[derive(Clone, Debug)] #[repr(C)] struct Boxed { buf: Buf, len: u64, } #[derive(Clone, Debug)] #[repr(C)] struct Shared { buf: Buf, start: u32, end: u32, } #[derive(Clone, Debug)] struct ConcatInner<'a> { left: Str<'a>, right: Str<'a>, } #[derive(Clone)] #[repr(C)] struct Concat<'a> { inner: Rc<ConcatInner<'a>>, len: u64, } impl<'a> Concat<'a> { // unsafe because len must be left.len() + right.len(). It must also be greater than // MAX_INLINE_LEN. unsafe fn new(len: u64, left: Str<'a>, right: Str<'a>) -> Concat<'a> { debug_assert!(len > MAX_INLINE_SIZE as u64); debug_assert_eq!(len, (left.len() + right.len()) as u64); Concat { len, inner: Rc::new(ConcatInner { left, right }), } } fn left(&self) -> Str<'a> { self.inner.left.clone() } fn right(&self) -> Str<'a> { self.inner.right.clone() } } #[derive(PartialEq, Eq)] #[repr(C)] struct StrRep<'a> { hi: usize, low: u64, _marker: PhantomData<&'a ()>, } impl<'a> Default for StrRep<'a> { fn default() -> StrRep<'a> { Inline::default().into() } } impl<'a> StrRep<'a> { fn get_tag(&self) -> StrTag { use StrTag::*; let tag = self.hi & 0x7; debug_assert!(tag < NUM_VARIANTS); match tag { 0 => Inline, 1 => Literal, 2 => Shared, 3 => Concat, 4 => Boxed, _ => unreachable!(), } } } macro_rules! impl_tagged_from { ($from:ty, $tag:expr) => { impl<'a> From<$from> for StrRep<'a> { fn from(s: $from) -> StrRep<'a> { let mut rep = unsafe { mem::transmute::<$from, StrRep>(s) }; rep.hi |= ($tag as usize); rep } } }; } impl_tagged_from!(Shared, StrTag::Shared); impl_tagged_from!(Concat<'a>, StrTag::Concat); impl_tagged_from!(Boxed, StrTag::Boxed); // Unlike the other variants, `Inline` always has the tag in place, so we can just cast it // directly. impl<'a> From<Inline> for StrRep<'a> { fn from(i: Inline) -> StrRep<'a> { unsafe { mem::transmute::<Inline, StrRep>(i) } } } impl<'a> From<Literal<'a>> for StrRep<'a> { fn from(s: Literal<'a>) -> StrRep<'a> { if s.len <= MAX_INLINE_SIZE as u64 { unsafe { Inline::from_raw(s.ptr, s.len as usize).into() } } else if s.ptr as usize & 0x7 == 0 { let mut rep = unsafe { mem::transmute::<Literal<'a>, StrRep>(s) }; rep.hi |= StrTag::Literal as usize; rep } else { let buf = unsafe { Buf::read_from_raw(s.ptr, s.len as usize) }; Boxed { len: s.len, buf }.into() } } } impl<'a> StrRep<'a> { fn len(&mut self) -> usize { match self.get_tag() { StrTag::Boxed | StrTag::Literal | StrTag::Concat => self.low as usize, StrTag::Shared => unsafe { self.view_as(|s: &Shared| s.end as usize - s.start as usize) }, StrTag::Inline => unsafe { self.view_as_inline(Inline::len) }, } } unsafe fn view_as_inline<R>(&self, f: impl FnOnce(&Inline) -> R) -> R { f(mem::transmute::<&StrRep<'a>, &Inline>(self)) } unsafe fn view_as<T, R>(&mut self, f: impl FnOnce(&T) -> R) -> R { let old = self.hi; self.hi = old & !0x7; let res = f(mem::transmute::<&mut StrRep<'a>, &T>(self)); self.hi = old; res } unsafe fn drop_as<T>(&mut self) { let old = self.hi; self.hi = old & !0x7; ptr::drop_in_place(mem::transmute::<&mut StrRep<'a>, *mut T>(self)); } unsafe fn copy(&self) -> StrRep<'a> { StrRep { low: self.low, hi: self.hi, _marker: PhantomData, } } // drop_with_tag is a parallel implementation of drop given an explicit tag. It is used in // conjunction with the LLVM-native "fast path" for dropping strings. See the gen_drop_str // function in llvm/builtin_functions.rs for more context. // // drop_with_tag must not be called with an Inline or Literal tag. unsafe fn drop_with_tag(&mut self, tag: u64) { // Debug-asserts are here to ensure that we catch any perturbing of the tag values getting // out of sync with this function. debug_assert_eq!(tag, self.get_tag() as u64); match tag { 2 => { debug_assert_eq!(tag, StrTag::Shared as u64); self.drop_as::<Shared>(); } 3 => { debug_assert_eq!(tag, StrTag::Concat as u64); self.drop_as::<Concat>(); } 4 => { debug_assert_eq!(tag, StrTag::Boxed as u64); self.drop_as::<Boxed>(); } _ => unreachable!(), } } } impl<'a> Drop for StrRep<'a> { fn drop(&mut self) { // Drop shows up on a lot of profiles. It doesn't appear as though drop is particularly // slow (efforts to do drops in batches, keeping the batch in thread-local storage, were // slightly slower), just that in short scripts there are just a lot of strings. let tag = self.get_tag(); unsafe { match tag { StrTag::Inline | StrTag::Literal => {} StrTag::Shared => self.drop_as::<Shared>(), StrTag::Boxed => self.drop_as::<Boxed>(), StrTag::Concat => self.drop_as::<Concat>(), } }; } } /// A Str that is either trivially copyable or holds the sole reference to some heap-allocated /// memory. We also ensure no non-static Literal variants are active in the string, as we intend to /// send this across threads, and non-static lifetimes are cumbersome in that context. #[derive(Default, Debug, Hash, PartialEq, Eq)] pub struct UniqueStr<'a>(Str<'a>); unsafe impl<'a> Send for UniqueStr<'a> {} impl<'a> Clone for UniqueStr<'a> { fn clone(&self) -> UniqueStr<'a> { UniqueStr(self.clone_str()) } } impl<'a> UniqueStr<'a> { pub fn into_str(self) -> Str<'a> { self.0 } pub fn is_empty(&self) -> bool { self.0.is_empty() } // TODO: is this safe for INLINE values? // Seems like we aren't guaranteed that inlines are valid for all of <'a> // We probably just want to use Strs pub fn literal_bytes(&self) -> &'a [u8] { assert!(self.0.drop_is_trivial()); unsafe { &*self.0.get_bytes() } } pub fn clone_str(&self) -> Str<'a> { let rep = unsafe { self.0.rep_mut() }; match rep.get_tag() { StrTag::Inline | StrTag::Literal => self.0.clone(), StrTag::Boxed => unsafe { rep.view_as(|b: &Boxed| { let bs = b.buf.as_bytes(); Str::from_rep( Boxed { buf: Buf::read_from_raw(bs.as_ptr(), bs.len()), len: bs.len() as u64, } .into(), ) }) }, StrTag::Shared | StrTag::Concat => unreachable!(), } } } impl<'a> From<Str<'a>> for UniqueStr<'a> { fn from(s: Str<'a>) -> UniqueStr<'a> { unsafe { let rep = s.rep_mut(); match rep.get_tag() { StrTag::Inline | StrTag::Literal => return UniqueStr(s), StrTag::Shared | StrTag::Concat => s.force(), StrTag::Boxed => {} }; debug_assert_eq!(StrTag::Boxed, rep.get_tag()); // We have a box in place, check its refcount if let Some(boxed) = rep.view_as(|b: &Boxed| { if b.buf.refcount() == 1 { None } else { // Copy a new buffer. let bs = b.buf.as_bytes(); debug_assert_eq!(bs.len() as u64, b.len); Some(Boxed { buf: Buf::read_from_raw(bs.as_ptr(), bs.len()), len: bs.len() as u64, }) } }) { UniqueStr(Str::from_rep(boxed.into())) } else { UniqueStr(s) } } } } // Why UnsafeCell? We want something that wont increase the size of StrRep, but we also need to // mutate it in-place. We can *almost* just use Cell here, but we cannot implement Clone behind // cell. #[derive(Default)] #[repr(transparent)] pub struct Str<'a>(UnsafeCell<StrRep<'a>>); impl<'a> Str<'a> { pub fn is_empty(&self) -> bool { unsafe { mem::transmute::<&Str, &Inline>(self) == &Inline::default() } } unsafe fn rep(&self) -> &StrRep<'a> { &*self.0.get() } unsafe fn rep_mut(&self) -> &mut StrRep<'a> { &mut *self.0.get() } pub unsafe fn drop_with_tag(&self, tag: u64) { self.rep_mut().drop_with_tag(tag) } // We rely on string literals having trivial drops for LLVM codegen, as they may be dropped // repeatedly. pub fn drop_is_trivial(&self) -> bool { match unsafe { self.rep() }.get_tag() { StrTag::Literal | StrTag::Inline => true, StrTag::Shared | StrTag::Concat | StrTag::Boxed => false, } } // leaks `self` unless you transmute it back. This is used in LLVM codegen pub fn into_bits(self) -> u128 { unsafe { mem::transmute::<Str<'a>, u128>(self) } } pub fn split( &self, pat: &Regex, // We want to accommodate functions that skip based on empty fields, like Awk whitespace // splitting. As a result, we pass down the field, and whether or not it was empty (emptiness // checks for the string itself are insufficient if used_fields projects some fields away), // the pattern returns the number of fields added to the output. mut push: impl FnMut(Str<'a>, bool /*is_empty*/) -> usize, used_fields: &FieldSet, ) { if self.is_empty() { return; } self.with_bytes(|s| { let mut prev = 0; let mut cur_field = 1; for m in pat.find_iter(s) { let is_empty = prev == m.start(); cur_field += if used_fields.get(cur_field) { push(self.slice(prev, m.start()), is_empty) } else { push(Str::default(), is_empty) }; prev = m.end(); } let is_empty = prev == s.len(); if used_fields.get(cur_field) { push(self.slice(prev, s.len()), is_empty); } else { push(Str::default(), is_empty); } }); } pub fn join_slice<'other, 'b>(&self, inps: &[Str<'other>]) -> Str<'b> { // We've noticed that performance of `join_slice` is very sensitive to the number of // `realloc` calls that happen when pushing onto DynamicBufHeap, so we spend the extra time // of computing the size of the joined string ahead of time exactly. let mut sv = SmallVec::<[&[u8]; 16]>::with_capacity(inps.len()); let sep_bytes: &[u8] = unsafe { &*self.get_bytes() }; let mut size = 0; for (i, inp) in inps.iter().enumerate() { let inp_bytes = unsafe { &*inp.get_bytes() }; sv.push(inp_bytes); size += inp_bytes.len(); if i < inps.len() - 1 { size += sep_bytes.len() } } let mut buf = DynamicBufHeap::new(size); for (i, inp) in sv.into_iter().enumerate() { buf.write(inp).unwrap(); if i < inps.len() - 1 { buf.write(sep_bytes).unwrap(); } } unsafe { buf.into_str() } } pub fn join(&self, mut ss: impl Iterator<Item = Str<'a>>) -> Str<'a> { let mut res = if let Some(s) = ss.next() { s } else { return Default::default(); }; for s in ss { res = Str::concat(res.clone(), Str::concat(self.clone(), s.clone())); } res } // TODO: SIMD implementations of to_upper and to_lower aren't too difficult to write; // it's probably worth specializing these implementations with those if possible. pub fn to_lower_ascii<'b>(&self) -> Str<'b> { self.map_bytes(|b| match b { b'A'..=b'Z' => b - b'A' + b'a', _ => b, }) } pub fn to_upper_ascii<'b>(&self) -> Str<'b> { self.map_bytes(|b| match b { b'a'..=b'z' => b - b'a' + b'A', _ => b, }) } fn map_bytes<'b>(&self, mut f: impl FnMut(u8) -> u8) -> Str<'b> { self.with_bytes(|bs| { if bs.len() <= MAX_INLINE_SIZE { let mut buf = SmallVec::<[u8; MAX_INLINE_SIZE]>::with_capacity(bs.len()); for b in bs { buf.push(f(*b)) } unsafe { Str::from_rep(Inline::from_unchecked(buf.as_slice()).into()) } } else { let mut buf = DynamicBufHeap::new(bs.len()); for b in bs { buf.push_byte(f(*b)) } unsafe { buf.into_str() } } }) } pub fn subst_first(&self, pat: &Regex, subst: &Str<'a>) -> (Str<'a>, bool) { self.with_bytes(|s| { subst.with_bytes(|subst| { if let Some(m) = pat.find(s) { let mut buf = DynamicBuf::new(s.len()); buf.write(&s[0..m.start()]).unwrap(); process_match(&s[m.start()..m.end()], subst, &mut buf).unwrap(); buf.write(&s[m.end()..s.len()]).unwrap(); (unsafe { buf.into_str() }, true) } else { (self.clone(), false) } }) }) } pub fn subst_all(&self, pat: &Regex, subst: &Str<'a>) -> (Str<'a>, Int) { self.with_bytes(|s| { subst.with_bytes(|subst| { let mut buf = DynamicBuf::new(0); let mut prev = 0; let mut count = 0; for m in pat.find_iter(s) { buf.write(&s[prev..m.start()]).unwrap(); process_match(&s[m.start()..m.end()], subst, &mut buf).unwrap(); prev = m.end(); count += 1; } if count == 0 { (self.clone(), count) } else { buf.write(&s[prev..s.len()]).unwrap(); (unsafe { buf.into_str() }, count) } }) }) } pub fn len(&self) -> usize { unsafe { self.rep_mut() }.len() } pub fn concat(left: Str<'a>, right: Str<'a>) -> Str<'a> { if left.is_empty() { mem::forget(left); return right; } if right.is_empty() { mem::forget(right); return left; } let llen = left.len(); let rlen = right.len(); let new_len = llen + rlen; if new_len <= MAX_INLINE_SIZE { let mut b = DynamicBuf::new(0); unsafe { b.write(&*left.get_bytes()).unwrap(); b.write(&*right.get_bytes()).unwrap(); b.into_str() } } else { // TODO: we can add another case here. If `left` is boxed and has a refcount of 1, we // can move it into a dynamicbuf and push `right` onto it, avoiding the heap // allocation. We _only_ want to do this if we reevaluate the `realloc` that DynamicBuf // does when you convert it back into a string, though. We would have to keep a // capacity around as well as a length. let concat = unsafe { Concat::new(new_len as u64, left, right) }; Str::from_rep(concat.into()) } } fn from_rep(rep: StrRep<'a>) -> Str<'a> { Str(UnsafeCell::new(rep)) } // This helper method assumes: // * that from and to cannot overflow when moved to u32s/shared/etc. // * that any CONCATs have been forced away. // * to - from > MAX_INLINE_SIZE unsafe fn slice_nooverflow(&self, from: usize, to: usize) -> Str<'a> { let rep = self.rep_mut(); let tag = rep.get_tag(); let new_rep = match tag { StrTag::Shared => rep.view_as(|s: &Shared| { let start = s.start + from as u32; let end = s.start + to as u32; Shared { start, end, buf: s.buf.clone(), } .into() }), StrTag::Boxed => rep.view_as(|b: &Boxed| { Shared { start: from as u32, end: to as u32, buf: b.buf.clone(), } .into() }), StrTag::Literal => rep.view_as(|l: &Literal| { let new_ptr = l.ptr.offset(from as isize); let new_len = (to - from) as u64; Literal { len: new_len, ptr: new_ptr, _marker: PhantomData, } .into() }), StrTag::Inline | StrTag::Concat => unreachable!(), }; Str::from_rep(new_rep) } unsafe fn slice_internal(&self, from: usize, to: usize) -> Str<'a> { assert!(from <= to); if from == to { return Default::default(); } let len = self.len(); assert!( to <= len, "invalid args to slice: range [{},{}) with len {}", from, to, len ); let new_len = to - from; if new_len <= MAX_INLINE_SIZE { return Str::from_rep(Inline::from_unchecked(&(*self.get_bytes())[from..to]).into()); } let tag = self.rep().get_tag(); let u32_max = u32::max_value() as usize; let mut may_overflow = to > u32_max || from > u32_max; if !may_overflow && tag == StrTag::Shared { // If we are taking a slice of an existing slice, then we can overflow by adding the // starts and ends together. may_overflow = self.rep_mut().view_as(|s: &Shared| { (s.start as usize + from) > u32_max || (s.start as usize + to) > u32_max }); } // Slices of literals are addressed with 64 bits. may_overflow = may_overflow && tag != StrTag::Literal; if may_overflow { // uncommon case: we cannot represent a Shared value. We need to copy and box the value // instead. // TODO: We can optimize cases when we are getting suffixes of Literal values // by creating new ones with offset pointers. This doesn't seem worth optimizing right // now, but we may want to in the future. self.force(); let rep = self.rep_mut(); let tag = rep.get_tag(); // All other variants ruled out by how large `self` is and the fact that we // just called `force` debug_assert_eq!(tag, StrTag::Boxed); return Str::from_rep(rep.view_as(|b: &Boxed| { let buf = Buf::read_from_raw(b.buf.as_ptr().offset(from as isize), new_len); Boxed { len: new_len as u64, buf, } .into() })); } // Force concat up here so we don't have to worry about aliasing `rep` in slice_nooverflow. if let StrTag::Concat = tag { self.force() } self.slice_nooverflow(from, to) } pub fn slice(&self, from: usize, to: usize) -> Str<'a> { // TODO: consider returning a result here so we can error out in a more graceful way. { let bs = unsafe { &*self.get_bytes() }; assert!( (from == to && to == bs.len()) || from < bs.len(), "internal error: invalid index len={}, from={}, to={}", bs.len(), from, to, ); assert!(to <= bs.len(), "internal error: invalid index"); } unsafe { self.slice_internal(from, to) } } // Why is [with_bytes] safe and [force] unsafe? Let's go case-by-case for the state of `self` // EMPTY: no data is passed into `f`. // BOXED: The function signature ensures that no string references can "escape" `f`, and `self` // will persist for the function body, which will keep the underlying buffer alive. // CONCAT: We `force` these strings, so they will be BOXED. // SHARED: This one is tricky. It may seem to be covered by the BOXED case, but the difference // is that shared strings give up there references to the underlying buffer if they get // forced. So if we did s.with_bytes(|x| { /* force s */; *x}), then *x is a // use-after-free! // // This is why [force] is unsafe. As written, no safe method will force a SHARED Str. // If we add force to a public API (e.g. for garbage collection), we'll need to ensure // that we don't call with_bytes around it, or clone the string before forcing. unsafe fn force(&self) { let (tag, len) = { let rep = self.rep_mut(); (rep.get_tag(), rep.len()) }; if tag.forced() { return; } let mut whead = 0; let mut res = UniqueBuf::new(len); macro_rules! push_bytes { ($slice:expr, [$from:expr, $to:expr]) => {{ let from = $from; let slen = $to - from; push_bytes!(&$slice[$from], slen); }}; ($at:expr, $len:expr) => {{ let slen = $len; debug_assert!((len - whead) >= slen); let head = &mut res.as_mut_bytes()[whead]; ptr::copy_nonoverlapping($at, head, slen); whead += slen; }}; } let mut todos = SmallVec::<[Str<'a>; 16]>::new(); let mut cur: Str<'a> = self.clone(); let new_rep: StrRep<'a> = 'outer: loop { let rep = cur.rep_mut(); let tag = rep.get_tag(); cur = loop { match tag { StrTag::Inline => rep.view_as_inline(|i| { push_bytes!(i.bytes(), [0, i.len()]); }), StrTag::Literal => rep.view_as(|l: &Literal| { push_bytes!(l.ptr, l.len as usize); }), StrTag::Boxed => rep.view_as(|b: &Boxed| { push_bytes!(b.buf.as_bytes(), [0, b.len as usize]); }), StrTag::Shared => rep.view_as(|s: &Shared| { push_bytes!(s.buf.as_bytes(), [s.start as usize, s.end as usize]); }), StrTag::Concat => { break rep.view_as(|c: &Concat| { todos.push(c.right()); c.left() }) } } if let Some(c) = todos.pop() { break c; } break 'outer Boxed { len: len as u64, buf: res.into_buf(), } .into(); }; }; *self.rep_mut() = new_rep; } // Avoid using this function; subsequent immutable calls to &self can invalidate the pointer. pub fn get_bytes(&self) -> *const [u8] { let rep = unsafe { self.rep_mut() }; let tag = rep.get_tag(); unsafe { match tag { StrTag::Inline => rep.view_as_inline(|i| i.bytes() as *const _), StrTag::Literal => rep.view_as(|lit: &Literal| { slice::from_raw_parts(lit.ptr, lit.len as usize) as *const _ }), StrTag::Shared => rep.view_as(|s: &Shared| { &s.buf.as_bytes()[s.start as usize..s.end as usize] as *const _ }), StrTag::Boxed => rep.view_as(|b: &Boxed| b.buf.as_bytes() as *const _), StrTag::Concat => { self.force(); self.get_bytes() } } } } pub fn with_bytes<R>(&self, f: impl FnOnce(&[u8]) -> R) -> R { let raw = self.get_bytes(); unsafe { f(&*raw) } } pub fn unmoor(self) -> Str<'static> { let rep = unsafe { self.rep_mut() }; let tag = rep.get_tag(); if let StrTag::Literal = tag { let new_rep = unsafe { rep.view_as(|lit: &Literal| { let buf = Buf::read_from_raw(lit.ptr, lit.len as usize); Boxed { len: lit.len, buf }.into() }) }; *rep = new_rep; } unsafe { mem::transmute::<Str<'a>, Str<'static>>(self) } } } impl<'a> Clone for Str<'a> { fn clone(&self) -> Str<'a> { let rep = unsafe { self.rep_mut() }; let tag = rep.get_tag(); let cloned_rep: StrRep<'a> = unsafe { match tag { StrTag::Literal | StrTag::Inline => rep.copy(), StrTag::Shared => rep.view_as(|s: &Shared| s.clone()).into(), StrTag::Boxed => rep.view_as(|b: &Boxed| b.clone()).into(), StrTag::Concat => rep.view_as(|c: &Concat<'a>| c.clone()).into(), } }; Str(UnsafeCell::new(cloned_rep)) } } impl<'a> PartialEq for Str<'a> { fn eq(&self, other: &Str<'a>) -> bool { // If the bits are the same, then the strings are equal. if unsafe { self.rep() == other.rep() } { return true; } // TODO: we could intern these strings if they wind up equal. self.with_bytes(|bs1| other.with_bytes(|bs2| bs1 == bs2)) } } impl<'a> Eq for Str<'a> {} impl<'a> Hash for Str<'a> { fn hash<H: Hasher>(&self, state: &mut H) { self.with_bytes(|bs| bs.hash(state)) } } impl<'a> From<&'a str> for Str<'a> { fn from(s: &'a str) -> Str<'a> { s.as_bytes().into() } } impl<'a> From<&'a [u8]> for Str<'a> { fn from(bs: &'a [u8]) -> Str<'a> { if bs.len() == 0 { Default::default() } else if bs.len() <= MAX_INLINE_SIZE { Str::from_rep(unsafe { Inline::from_raw(bs.as_ptr(), bs.len()).into() }) } else if bs.as_ptr() as usize & 0x7 != 0 { // Strings are not guaranteed to be word aligned. Copy over strings that aren't. This // is more important for tests; most of the places that literals can come from in an // awk program will hand out aligned pointers. let buf = Buf::read_from_bytes(bs); let boxed = Boxed { len: bs.len() as u64, buf, }; Str::from_rep(boxed.into()) } else { let literal = Literal { len: bs.len() as u64, ptr: bs.as_ptr(), _marker: PhantomData, }; Str::from_rep(literal.into()) } } } impl<'a> From<String> for Str<'a> { fn from(s: String) -> Str<'a> { if s.len() == 0 { return Default::default(); } let buf = Buf::read_from_bytes(s.as_bytes()); let boxed = Boxed { len: s.len() as u64, buf, }; Str::from_rep(boxed.into()) } } // For numbers, we are careful to check if a number only requires 15 digits or fewer to be // represented. This allows us to trigger the "Inline" variant and avoid a heap allocation, // sometimes at the expenseof a small copy. impl<'a> From<Int> for Str<'a> { fn from(i: Int) -> Str<'a> { if let Some(i) = Inline::itoa(i) { return Str::from_rep(i.into()); } let mut buf = [0u8; 21]; let n = itoa::write(&mut buf[..], i).unwrap(); Buf::read_from_bytes(&buf[..n]).into_str() } } impl<'a> From<Float> for Str<'a> { fn from(f: Float) -> Str<'a> { let mut ryubuf = ryu::Buffer::new(); let s = ryubuf.format(f); let slen = s.len(); // Print Float as Int if it ends in ".0". let slen = if &s.as_bytes()[slen - 2..] == b".0" { slen - 2 } else { slen }; Buf::read_from_bytes(&s.as_bytes()[..slen]).into_str() } } impl Str<'static> { // Why have this? Parts of the runtime hold onto a Str<'static> to avoid adding a lifetime // parameter to the struct. pub fn upcast<'a>(self) -> Str<'a> { unsafe { mem::transmute::<Str<'static>, Str<'a>>(self) } } pub fn upcast_ref<'a>(&self) -> &Str<'a> { unsafe { mem::transmute::<&Str<'static>, &Str<'a>>(self) } } } #[repr(C)] struct BufHeader { size: usize, // We only have "strong counts" count: Cell<usize>, } #[repr(transparent)] pub struct UniqueBuf(*mut BufHeader); unsafe impl Send for UniqueBuf {} pub struct DynamicBufHeap { data: UniqueBuf, write_head: usize, } impl DynamicBufHeap { pub fn new(size: usize) -> DynamicBufHeap { DynamicBufHeap { data: UniqueBuf::new(size), write_head: 0, } } fn size(&self) -> usize { unsafe { (*self.data.0).size } } pub fn as_mut_bytes(&mut self) -> &mut [u8] { self.data.as_mut_bytes() } pub fn write_head(&self) -> usize { self.write_head } pub fn into_buf(self) -> Buf { self.data.into_buf() } pub unsafe fn into_str<'a>(mut self) -> Str<'a> { // TODO: we can probably make this safe? I think this was unsafe from back when strings had // to be utf8. // Shrink the buffer to fit. self.realloc(self.write_head); self.data.into_buf().into_str() } unsafe fn realloc(&mut self, new_cap: usize) { let cap = self.size(); if cap == new_cap { return; } let new_buf = realloc( self.data.0 as *mut u8, UniqueBuf::layout(cap), UniqueBuf::layout(new_cap).size(), ) as *mut BufHeader; (*new_buf).size = new_cap; self.data.0 = new_buf; } fn push_byte(&mut self, b: u8) { let cap = self.size(); debug_assert!( cap >= self.write_head, "cap={}, write_head={}", cap, self.write_head ); let remaining = cap - self.write_head; unsafe { if remaining == 0 { let new_cap = std::cmp::max(cap + 1, cap * 2); self.realloc(new_cap); } *self.data.as_mut_ptr().offset(self.write_head as isize) = b; }; self.write_head += 1; } } impl Write for DynamicBufHeap { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { let cap = self.size(); debug_assert!( cap >= self.write_head, "cap={}, write_head={}", cap, self.write_head ); let remaining = cap - self.write_head; unsafe { if remaining < buf.len() { let new_cap = std::cmp::max(cap + buf.len(), cap * 2); self.realloc(new_cap); ptr::copy( buf.as_ptr(), self.data.as_mut_ptr().offset(self.write_head as isize), buf.len(), ); // NB: even after copying, there may be uninitialized memory at the tail of the // buffer. We enforce that this memory is never read by doing a realloc(write_head) // before moving this into a Buf. Before then, we don't read the underlying data at // all. } else { ptr::copy( buf.as_ptr(), self.data.as_mut_ptr().offset(self.write_head as isize), buf.len(), ) } }; self.write_head += buf.len(); Ok(buf.len()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } pub enum DynamicBuf { Inline(smallvec::SmallVec<[u8; MAX_INLINE_SIZE]>), Heap(DynamicBufHeap), } impl Default for DynamicBuf { fn default() -> DynamicBuf { DynamicBuf::Inline(Default::default()) } } impl DynamicBuf { pub fn new(size: usize) -> DynamicBuf { if size <= MAX_INLINE_SIZE { DynamicBuf::Inline(Default::default()) } else { DynamicBuf::Heap(DynamicBufHeap::new(size)) } } pub unsafe fn into_str<'a>(self) -> Str<'a> { match self { DynamicBuf::Inline(sv) => Str::from_rep(Inline::from_unchecked(&sv[..]).into()), DynamicBuf::Heap(dbuf) => dbuf.into_str(), } } } impl Write for DynamicBuf { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { match self { DynamicBuf::Inline(sv) => { let new_len = sv.len() + buf.len(); if sv.len() + buf.len() > MAX_INLINE_SIZE { let mut heap = DynamicBufHeap::new(new_len); heap.write(&sv[..]).unwrap(); heap.write(buf).unwrap(); *self = DynamicBuf::Heap(heap); } else { sv.extend(buf.iter().cloned()); } Ok(buf.len()) } DynamicBuf::Heap(dbuf) => dbuf.write(buf), } } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[repr(transparent)] pub struct Buf(*const BufHeader); impl Clone for Buf { fn clone(&self) -> Buf { let header: &BufHeader = unsafe { &(*self.0) }; let cur = header.count.get(); header.count.set(cur + 1); Buf(self.0) } } impl Drop for UniqueBuf { fn drop(&mut self) { let header: &mut BufHeader = unsafe { &mut (*self.0) }; debug_assert_eq!(header.count.get(), 1); unsafe { dealloc(self.0 as *mut u8, UniqueBuf::layout(header.size)) } } } impl Drop for Buf { fn drop(&mut self) { let header: &BufHeader = unsafe { &(*self.0) }; let cur = header.count.get(); debug_assert!(cur > 0); if cur == 1 { mem::drop(UniqueBuf(self.0 as *mut _)); return; } header.count.set(cur - 1); } } impl UniqueBuf { fn layout(size: usize) -> Layout { Layout::from_size_align( size + mem::size_of::<BufHeader>(), mem::align_of::<BufHeader>(), ) .unwrap() } pub fn new(size: usize) -> UniqueBuf { let layout = UniqueBuf::layout(size); unsafe { let alloced = alloc_zeroed(layout) as *mut BufHeader; assert!(!alloced.is_null()); ptr::write( alloced, BufHeader { size, count: Cell::new(1), }, ); UniqueBuf(alloced) } } pub fn as_mut_bytes(&mut self) -> &mut [u8] { let header: &BufHeader = unsafe { &(*self.0) }; debug_assert_eq!(header.count.get(), 1); unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), header.size) } } pub fn as_mut_ptr(&mut self) -> *mut u8 { let header: &BufHeader = unsafe { &(*self.0) }; debug_assert_eq!(header.count.get(), 1); unsafe { self.0.offset(1) as *mut u8 } } pub fn into_buf(self) -> Buf { let res = Buf(self.0); mem::forget(self); res } } impl Buf { pub fn into_str<'a>(self) -> Str<'a> { Str::from_rep( Boxed { len: self.len() as u64, buf: self, } .into(), ) } pub fn len(&self) -> usize { unsafe { &(*self.0) }.size } pub fn as_bytes(&self) -> &[u8] { let size = self.len(); unsafe { slice::from_raw_parts(self.as_ptr(), size) } } pub fn as_ptr(&self) -> *const u8 { unsafe { self.0.offset(1) as *const u8 } } fn refcount(&self) -> usize { let header: &BufHeader = unsafe { &(*self.0) }; header.count.get() } // Unsafe because `from` and `to` must point to the start of characters. pub fn slice_to_str<'a>(&self, from: usize, to: usize) -> Str<'a> { debug_assert!(from <= self.len()); debug_assert!(to <= self.len()); debug_assert!(from <= to, "invalid slice [{}, {})", from, to); let len = to.saturating_sub(from); if len == 0 { Str::default() } else /* NB: we could also have the following. * This creates a tradeoff: in scripts where we split several fields, performing this copy * has a noticeable impact on performance. * * In scripts that mainly read a small number of columns, the additional indirection layer * of indirection leads to a marginal performance hit when reading this data. For now, we * opt for the faster `slice` operation, but there's a solid case for either one, to the * point where we may want this to be configurable. if len <= MAX_INLINE_SIZE { unsafe { Str::from_rep( Inline::from_raw(self.as_ptr().offset(std::cmp::max(0, from as isize)), len) .into(), ) } } else */ if likely(from <= u32::max_value() as usize && to <= u32::max_value() as usize) { Str::from_rep( Shared { buf: self.clone(), start: from as u32, end: to as u32, } .into(), ) } else { self.clone().into_str().slice(from, to) } } pub unsafe fn read_from_raw(ptr: *const u8, len: usize) -> Buf { let mut ubuf = UniqueBuf::new(len); ptr::copy_nonoverlapping(ptr, ubuf.as_mut_ptr(), len); ubuf.into_buf() } pub fn read_from_bytes(s: &[u8]) -> Buf { unsafe { Buf::read_from_raw(s.as_ptr(), s.len()) } } pub fn try_unique(self) -> Result<UniqueBuf, Buf> { if self.refcount() == 1 { let res = UniqueBuf(self.0 as *mut _); mem::forget(self); Ok(res) } else { Err(self) } } } /// Helper function for `subst_first` and `subst_all`: handles '&' syntax. fn process_match(matched: &[u8], subst: &[u8], w: &mut impl Write) -> io::Result<()> { if memchr::memchr(b'&', subst).is_none() { w.write(subst).unwrap(); return Ok(()); } let mut start = 0; let mut escaped = false; for (i, b) in subst.iter().cloned().enumerate() { match b { b'&' => { if escaped { w.write(&subst[start..i - 1])?; w.write(&[b'&'])?; } else { w.write(&subst[start..i])?; w.write(matched)?; } start = i + 1; } b'\\' => { if !escaped { escaped = true; continue; } w.write(&subst[start..i])?; start = i + 1; } _ => {} } escaped = false; } w.write(&subst[start..])?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn inline_basics() { let test_str = "hello there"; unsafe { let i = Inline::from_unchecked(test_str.as_bytes()); assert_eq!(test_str, str::from_utf8(i.bytes()).unwrap()); } let s: Str = "hi there".into(); assert_eq!(unsafe { s.rep().get_tag() }, StrTag::Inline); let s1 = s.slice(0, 1); assert_eq!(unsafe { s1.rep().get_tag() }, StrTag::Inline); s1.with_bytes(|bs1| assert_eq!(bs1, b"h")); } #[test] fn basic_behavior() { let base_1 = b"hi there fellow"; let base_2 = b"how are you?"; let base_3 = b"hi there fellowhow are you?"; let s1 = Str::from(&base_1[..]); let s2 = Str::from(&base_2[..]); let s3 = Str::from(&base_3[..]); s1.with_bytes(|bs| assert_eq!(bs, base_1)); s2.with_bytes(|bs| assert_eq!(bs, base_2, "{:?}", s2)); s3.with_bytes(|bs| assert_eq!(bs, base_3)); let s4 = Str::concat(s1, s2.clone()); assert_eq!(s3, s4); s4.with_bytes(|bs| assert_eq!(bs, base_3)); let s5 = Str::concat( Str::concat(Str::from("hi"), Str::from(" there")), Str::concat( Str::from(" "), Str::concat(Str::from("fel"), Str::from("low")), ), ); s5.with_bytes(|bs| assert_eq!(bs, base_1)); // Do this multiple times to play with the refcount. assert_eq!(s2.slice(1, 4), s3.slice(16, 19)); assert_eq!(s2.slice(2, 6), s3.slice(17, 21)); } fn test_str_split(pat: &Regex, base: &[u8]) { let s = Str::from(base); let want = pat .split(base) .skip_while(|x| x.len() == 0) .collect::<Vec<_>>(); let mut got = Vec::new(); s.split( &pat, |sub, _is_empty| { got.push(sub); 1 }, &FieldSet::all(), ); let total_got = got.len(); let total = want.len(); for (g, w) in got.iter().cloned().zip(want.iter().cloned()) { assert_eq!(g, Str::from(std::str::from_utf8(w).unwrap())); } if total_got > total { // We want there to be trailing empty fields in this case. for s in &got[total..] { assert_eq!(s.len(), 0); } } else { assert_eq!(total_got, total, "got={:?} vs want={:?}", got, want); } } #[test] fn basic_splitting() { let pat0 = Regex::new(",").unwrap(); test_str_split(&pat0, b"what,is,,,up,"); let pat = Regex::new(r#"[ \t]"#).unwrap(); test_str_split(&pat, b"what is \t up "); } #[test] fn split_long_string() { let pat = Regex::new(r#"[ \t]"#).unwrap(); test_str_split( &pat, crate::test_string_constants::PRIDE_PREJUDICE_CH2.as_bytes(), ); } #[test] fn dynamic_string() { let mut d = DynamicBuf::new(0); write!( &mut d, "This is the first part of the string {}\n", "with formatting and everything!" ) .unwrap(); write!(&mut d, "And this is the second part").unwrap(); let s = unsafe { d.into_str() }; s.with_bytes(|bs| { assert_eq!( bs, br#"This is the first part of the string with formatting and everything! And this is the second part"# ) }); } #[test] fn subst() { let s1: Str = "String number one".into(); let s2: Str = "m".into(); let re1 = Regex::new("n").unwrap(); let (s3, n1) = s1.subst_all(&re1, &s2); assert_eq!(n1, 3); s3.with_bytes(|bs| assert_eq!(bs, b"Strimg mumber ome")); let re2 = Regex::new("xxyz").unwrap(); let (s4, n2) = s3.subst_all(&re2, &s2); assert_eq!(n2, 0); assert_eq!(s3, s4); let empty = Str::default(); let (s5, n3) = empty.subst_all(&re1, &s2); assert_eq!(n3, 0); assert_eq!(empty, s5); let s6: Str = "xxyz substituted into another xxyz".into(); let (s7, subbed) = s6.subst_first(&re2, &s1); s7.with_bytes(|bs| assert_eq!(bs, b"String number one substituted into another xxyz")); assert!(subbed); } #[test] fn subst_ampersand() { let s1: Str = "hahbhc".into(); let s2: Str = "ha&".into(); let re1 = Regex::new("h.").unwrap(); let (s3, subbed) = s1.subst_first(&re1, &s2); assert!(subbed); s3.with_bytes(|bs| assert_eq!(bs, b"hahahbhc")); let (s4, count) = s1.subst_all(&re1, &s2); s4.with_bytes(|bs| assert_eq!(bs, b"hahahahbhahc")); assert_eq!(count, 3); let s5: Str = "hz\\&".into(); let (s6, subbed) = s1.subst_first(&re1, &s5); s6.with_bytes(|bs| assert_eq!(bs, b"hz&hbhc")); assert!(subbed); } } #[cfg(all(feature = "unstable", test))] mod bench { extern crate test; use super::*; use test::{black_box, Bencher}; fn bench_max_min(b: &mut Bencher, min: i64, max: i64) { use rand::{thread_rng, Rng}; let mut rng = thread_rng(); let mut v = Vec::new(); let size = 1 << 12; v.resize_with(size, || rng.gen_range(min..=max)); let mut i = 0; b.iter(|| { let n = unsafe { *v.get_unchecked(i) }; i += 1; i &= size - 1; black_box(Str::from(n)) }) } #[bench] fn bench_itoa_small(b: &mut Bencher) { bench_max_min(b, -99999, 99999) } #[bench] fn bench_itoa_medium(b: &mut Bencher) { bench_max_min(b, -99999999999999, 999999999999999) } #[bench] fn bench_itoa_large(b: &mut Bencher) { bench_max_min(b, i64::min_value(), i64::max_value()) } #[bench] fn bench_get_bytes_drop_empty(b: &mut Bencher) { b.iter(|| { let s = Str::default(); black_box(s.get_bytes()); }); } #[bench] fn bench_get_bytes_drop_literal(b: &mut Bencher) { // Arena will align the string properly. use crate::arena::Arena; let a = Arena::default(); let literal = a.alloc_str("this is a string that is longer than the maximum inline size"); b.iter(|| { let s: Str = literal.into(); black_box(s.get_bytes()); }); } #[bench] fn bench_get_bytes_drop_inline(b: &mut Bencher) { let literal = "AAAAAAAA"; b.iter(|| { let s: Str = literal.into(); black_box(s.get_bytes()); }); } #[bench] fn bench_substr_inline(b: &mut Bencher) { let literal = "AAAAAAAA"; let mut i = 0; let len = literal.len(); let s: Str = literal.into(); b.iter(|| { i &= 7; black_box(s.slice(i, len)); i += 1; }); } #[bench] fn bench_substr_boxed(b: &mut Bencher) { // Write 4KiB of As let mut dbuf = DynamicBuf::new(4096); let bs: Vec<u8> = (0..4096).map(|_| b'A').collect(); dbuf.write(&bs[..]).unwrap(); let s = unsafe { dbuf.into_str() }; let mut i = 0; let len = 4096; b.iter(|| { i &= 4095; black_box(s.slice(i, len)); i += 1; }); } } mod formatting { use super::*; use std::fmt::{self, Debug, Display, Formatter}; impl<'a> Display for Str<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { self.with_bytes(|bs| match std::str::from_utf8(bs) { Ok(s) => write!(f, "{}", s), Err(_) => write!(f, "{:?}", bs), }) } } impl<'a> Debug for Str<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { unsafe { let rep = self.rep_mut(); match rep.get_tag() { StrTag::Inline => { rep.view_as_inline(|i| write!(f, "Str(Inline({:?}))", i.bytes())) } StrTag::Literal => rep.view_as(|l: &Literal| write!(f, "Str({:?})", l)), StrTag::Shared => rep.view_as(|s: &Shared| write!(f, "Str({:?})", s)), StrTag::Concat => rep.view_as(|c: &Concat| { write!(f, "Str(Concat({:?}, {:?}))", c.left(), c.right()) }), StrTag::Boxed => rep.view_as(|b: &Boxed| write!(f, "Str({:?})", b)), }? } write!(f, "/[disp=<{}>]", self) } } impl<'a> Debug for Literal<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!( f, "Literal {{ len: {}, ptr: {:x}=>{:?} }}", self.len, self.ptr as usize, str::from_utf8(unsafe { slice::from_raw_parts(self.ptr, self.len as usize) }) .unwrap(), ) } } impl<'a> Debug for Buf { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let header = unsafe { &*self.0 }; write!( f, "Buf {{ size: {}, count: {}, contents: {:?} }}", header.size, header.count.get(), self.as_bytes(), ) } } }
mod architecture; /// File-related utilities. /// /// Most utilities defined in this module are higher-level abstractions over `std::fs`, but common /// operations nonetheless. pub mod file; pub mod notify; mod platform; pub use architecture::Architecture; pub use platform::Platform;
pub struct Solution; impl Solution { pub fn set_zeroes(matrix: &mut Vec<Vec<i32>>) { let m = matrix.len(); if m == 0 { return; } let n = matrix[0].len(); if n == 0 { return; } let mut zero_row = vec![false; m]; let mut zero_col = vec![false; n]; for i in 0..m { for j in 0..n { if matrix[i][j] == 0 { zero_row[i] = true; zero_col[j] = true; } } } for i in 0..m { for j in 0..n { if zero_row[i] || zero_col[j] { matrix[i][j] = 0; } } } } } #[test] fn test0073() { let mut matrix = vec![vec![1, 1, 1], vec![1, 0, 1], vec![1, 1, 1]]; Solution::set_zeroes(&mut matrix); assert_eq!(matrix, vec![vec![1, 0, 1], vec![0, 0, 0], vec![1, 0, 1]]); let mut matrix = vec![vec![0, 1, 2, 0], vec![3, 4, 5, 2], vec![1, 3, 1, 5]]; Solution::set_zeroes(&mut matrix); assert_eq!( matrix, vec![vec![0, 0, 0, 0], vec![0, 4, 5, 0], vec![0, 3, 1, 0]] ); }
fn main() { let input = include_str!("day12.txt"); let split = input.split("\n"); let v: Vec<&str> = split.collect(); let mut x = 0; let mut y = 0; let mut direction = "e"; for thing in v { if thing.chars().nth(0).unwrap() == 'N' { let removedfirst = thing.chars().next().map(|c| &thing[c.len_utf8()..]); y += removedfirst.unwrap().parse::<i32>().unwrap(); } else if thing.chars().nth(0).unwrap() == 'S' { let removedfirst = thing.chars().next().map(|c| &thing[c.len_utf8()..]); y -= removedfirst.unwrap().parse::<i32>().unwrap(); } else if thing.chars().nth(0).unwrap() == 'E' { let removedfirst = thing.chars().next().map(|c| &thing[c.len_utf8()..]); x += removedfirst.unwrap().parse::<i32>().unwrap(); } else if thing.chars().nth(0).unwrap() == 'W' { let removedfirst = thing.chars().next().map(|c| &thing[c.len_utf8()..]); x -= removedfirst.unwrap().parse::<i32>().unwrap(); } else if thing.chars().nth(0).unwrap() == 'F' { let removedfirst = thing.chars().next().map(|c| &thing[c.len_utf8()..]); if direction == "n" { y += removedfirst.unwrap().parse::<i32>().unwrap(); } else if direction == "s" { y -= removedfirst.unwrap().parse::<i32>().unwrap(); } else if direction == "e" { x += removedfirst.unwrap().parse::<i32>().unwrap(); } else if direction == "w" { x -= removedfirst.unwrap().parse::<i32>().unwrap(); } } else if thing.chars().nth(0).unwrap() == 'L' { let removedfirst = thing.chars().next().map(|c| &thing[c.len_utf8()..]); if removedfirst.unwrap().parse::<i32>().unwrap() == 90 { if direction == "n" { direction = "w"; } else if direction == "s" { direction = "e"; } else if direction == "e" { direction = "n"; } else if direction == "w" { direction = "s"; } } else if removedfirst.unwrap().parse::<i32>().unwrap() == 180 { if direction == "n" { direction = "s"; } else if direction == "s" { direction = "n"; } else if direction == "e" { direction = "w"; } else if direction == "w" { direction = "e"; } } else if removedfirst.unwrap().parse::<i32>().unwrap() == 270 { if direction == "s" { direction = "w"; } else if direction == "n" { direction = "e"; } else if direction == "e" { direction = "s"; } else if direction == "w" { direction = "n"; } } } else if thing.chars().nth(0).unwrap() == 'R' { let removedfirst = thing.chars().next().map(|c| &thing[c.len_utf8()..]); if removedfirst.unwrap().parse::<i32>().unwrap() == 90 { if direction == "s" { direction = "w"; } else if direction == "n" { direction = "e"; } else if direction == "e" { direction = "s"; } else if direction == "w" { direction = "n"; } } else if removedfirst.unwrap().parse::<i32>().unwrap() == 180 { if direction == "n" { direction = "s"; } else if direction == "s" { direction = "n"; } else if direction == "e" { direction = "w"; } else if direction == "w" { direction = "e"; } } else if removedfirst.unwrap().parse::<i32>().unwrap() == 270 { if direction == "n" { direction = "w"; } else if direction == "s" { direction = "e"; } else if direction == "e" { direction = "n"; } else if direction == "w" { direction = "s"; } } } } println!("{}", x.abs() + y.abs()); }
use std::collections::HashSet; use proconio::input; fn main() { input! { n: u8, m: usize, a: [[u8]; m], }; let mut ans = 0; for bits in 0..(1 << m) { let mut b = HashSet::new(); for i in 0..m { if bits >> i & 1 == 1 { for &y in &a[i] { b.insert(y); } } } let mut ok = true; for x in 1..=n { if b.contains(&x) == false { ok = false; } } if ok { ans += 1; } } println!("{}", ans); }
use std::ops::{Sub, Add, AddAssign, Neg}; use std::cmp::{PartialOrd, Ord, Ordering}; use std::mem; use std::f32; use std::slice; use vector::Vector3; /// A point in 3D space. /// /// Points are represented as cartesian coordinates with an `x`, `y`, and `z` position, as well as /// a `w` homogeneous coordinate for the purposes of linear algebra calculations. #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Point { pub x: f32, pub y: f32, pub z: f32, pub w: f32, } impl Point { /// Creates a new point with the given coordinates. pub fn new(x: f32, y: f32, z: f32) -> Point { Point { x: x, y: y, z: z, w: 1.0, } } /// Creates a new point at the origin `(0.0, 0.0, 0.0, 1.0)`. pub fn origin() -> Point { Point { x: 0.0, y: 0.0, z: 0.0, w: 1.0, } } /// Creates a new point at the minimum representable coordinate. /// /// The minimum point is the one which has `f32::MIN` for its x, y, and z coordinates, and 1.0 /// for its w coordinate. pub fn min() -> Point { Point::new(f32::MIN, f32::MIN, f32::MIN) } /// Creates a new point at the maximum representable coordinate. /// /// The maximum point is the one which has `f32::MAX` for its x, y, and z coordinates, and 1.0 /// for its w coordinate. pub fn max() -> Point { Point::new(f32::MAX, f32::MAX, f32::MAX) } /// Calculates the distance in (in abstract units) between two points. /// /// This method uses `sqrt()` to calculate the distance between the points. If the exact /// distance isn't necessary (e.g. when comparing two or more distances to each other) use /// `distance_sqr()` as it is cheaper to calculate. pub fn distance(&self, other: &Point) -> f32 { self.distance_sqr(other).sqrt() } /// Calculates the squared distance between two points. /// /// This method is offered as an optimization over `distance()` because there are some cases /// where the square distance is sufficent and calculating the squared distance avoids a /// relatively costly square root calculation. pub fn distance_sqr(&self, other: &Point) -> f32 { let diff_x = self.x - other.x; let diff_y = self.y - other.y; let diff_z = self.z - other.z; diff_x * diff_x + diff_y * diff_y + diff_z * diff_z } pub fn as_vector3(&self) -> Vector3 { Vector3::new(self.x, self.y, self.z) } pub fn as_array(&self) -> &[f32; 4] { unsafe { mem::transmute(self) } } pub fn as_slice_of_arrays(points: &[Point]) -> &[[f32; 4]] { let ptr = points.as_ptr() as *const _; unsafe { slice::from_raw_parts(ptr, points.len()) } } pub fn as_ref(points: &[Point]) -> &[f32] { let ptr = points.as_ptr() as *const _; let len = points.len() * 4; unsafe { slice::from_raw_parts(ptr, len) } } pub fn slice_from_f32_slice(raw: &[f32]) -> &[Point] { assert!( raw.len() % 4 == 0, "To convert a slice of f32 to a slice of Point it must have a length that is a \ multiple of 4"); unsafe { slice::from_raw_parts(raw.as_ptr() as *const Point, raw.len() / 4) } } } impl Sub for Point { type Output = Vector3; fn sub(self, rhs: Self) -> Vector3 { Vector3::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) } } impl AddAssign<Vector3> for Point { fn add_assign(&mut self, rhs: Vector3) { self.x += rhs.x; self.y += rhs.y; self.z += rhs.z; self.w = 1.0; } } impl Add<Vector3> for Point { type Output = Point; fn add(mut self, rhs: Vector3) -> Point { self += rhs; self } } impl Sub<Vector3> for Point { type Output = Point; fn sub(self, rhs: Vector3) -> Point { Point { x: self.x - rhs.x, y: self.y - rhs.y, z: self.z - rhs.z, w: 1.0, } } } impl Neg for Point { type Output = Point; fn neg(self) -> Point { Point { x: -self.x, y: -self.y, z: -self.z, w: 1.0, } } } /// We lie about Point being Eq because it's needed for Ord. For our purposes we don't /// care that it's not technically true according to the spec. impl Eq for Point {} impl PartialOrd for Point { /// Ordering for points is defined by ordering the ordering precedence as x > y > z. /// /// TODO: Elaborate on ordering for points in vectors in the module documentation? fn partial_cmp(&self, other: &Point) -> Option<Ordering> { debug_assert!(self.w == 1.0 && other.w == 1.0, "Points must be normalized before comparison"); if self.x < other.x { Some(Ordering::Less) } else if self.x > other.x { Some(Ordering::Greater) } else if self.y < other.y { Some(Ordering::Less) } else if self.y > other.y { Some(Ordering::Greater) } else if self.z < other.z { Some(Ordering::Less) } else if self.z > other.z { Some(Ordering::Greater) } else if self.x == other.x && self.y == other.y && self.z == other.z { Some(Ordering::Equal) } else { None } } } impl Ord for Point { /// Super bad-nasty implementation of Ord for Point. /// /// This is so that we can use cmp::min() and cmp::max() with Point, but we have to settle /// for panicking when a strict ordering can't be determined. We could also choose to define /// an arbitrary ordering for NaN elements, but if a point has NaN coordinates something has /// likely gone wrong so panicking will help even stranger bugs from appearing. fn cmp(&self, other: &Point) -> Ordering { match PartialOrd::partial_cmp(self, other) { Some(ordering) => ordering, None => { panic!( "Trying to compare points {:?} and {:?} when one as NaN coordinates", self, other) } } } } impl From<(f32, f32, f32)> for Point { fn from(from: (f32, f32, f32)) -> Point { Point { x: from.0, y: from.1, z: from.2, w: 1.0, } } } impl From<(f32, f32, f32, f32)> for Point { fn from(from: (f32, f32, f32, f32)) -> Point { Point { x: from.0, y: from.1, z: from.2, w: from.3, } } } impl<'a> From<&'a [f32]> for Point { fn from(from: &[f32]) -> Point { assert!(from.len() == 3 || from.len() == 4); Point { x: from[0], y: from[1], z: from[2], w: if from.len() == 4 { from[3] } else { 1.0 }, } } } impl From<Vector3> for Point { /// Creates a new `Point` from a `Vector3`. /// /// This behaves as if the `Vector3` had been added to the origin, resulting in a `Point` with /// the same x, y, and z coordinates as the original `Vector3` had. The conversion can be /// expressed as `<x, y, z> => (x, y, z, 1.0)`. fn from(from: Vector3) -> Point { Point { x: from.x, y: from.y, z: from.z, w: 1.0, } } }
use game::*; #[test] /// Test the index fn fn first_last_test() { #![allow(unused_variables)] let deck = Deck::new(); let first = deck[0]; let last = deck[51]; let f_tup = first.to_string_pair(); let l_tup = last.to_string_pair(); assert!(f_tup.0 == "Ace" && f_tup.1 == "Diamond"); assert!(l_tup.0 == "King" && l_tup.1 == "Spade"); } #[test] /// Test the iterator fn iterator_test() { #![allow(unused_variables)] let deck = Deck::new(); let mut count = 0; for card in deck { count += 1; } assert!(count == 52); } #[test] /// Test the draw_to_hand fn fn draw_to_hand_test() { #![allow(unused_variables)] let mut deck = Deck::new(); let mut hand = Hand::new(); draw_to_hand(&mut deck,&mut hand,5); assert!(deck.count() == (47)); assert!(hand.count() == 5); } #[test] /// Test the play_to_discard fn fn play_to_discard_test() { #![allow(unused_variables)] let mut deck = Deck::new(); let mut hand = Hand::new(); draw_to_hand(&mut deck,&mut hand,5); play_to_discard(&mut deck, &mut hand); assert!(hand.count() == 0); deck.shuffle(); assert!(deck.count() == 52); } #[test] fn overdraw_test() { #![allow(unused_variables)] let mut deck = Deck::new(); let mut hand = Hand::new(); draw_to_hand(&mut deck, &mut hand, 100); assert!(deck.count() == 0); assert!(hand.count() == 52); }
// Copyright 2021 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 common_exception::Result; use common_expression::types::nullable::NullableDomain; use common_expression::types::number::SimpleDomain; use common_expression::types::string::StringDomain; use common_expression::types::DataType; use common_expression::types::DateType; use common_expression::types::NumberDataType; use common_expression::types::NumberType; use common_expression::types::StringType; use common_expression::types::TimestampType; use common_expression::types::ValueType; use common_expression::with_number_mapped_type; use common_expression::ConstantFolder; use common_expression::Domain; use common_expression::Expr; use common_expression::FunctionContext; use common_expression::Scalar; use common_expression::TableSchemaRef; use common_functions::BUILTIN_FUNCTIONS; use storages_common_table_meta::meta::ColumnStatistics; use storages_common_table_meta::meta::StatisticsOfColumns; use crate::Index; #[derive(Clone)] pub struct RangeIndex { expr: Expr<String>, func_ctx: FunctionContext, schema: TableSchemaRef, } impl RangeIndex { pub fn try_create( func_ctx: FunctionContext, expr: &Expr<String>, schema: TableSchemaRef, ) -> Result<Self> { Ok(Self { expr: expr.clone(), func_ctx, schema, }) } pub fn try_apply_const(&self) -> Result<bool> { // Only return false, which means to skip this block, when the expression is folded to a constant false. Ok(!matches!(self.expr, Expr::Constant { scalar: Scalar::Boolean(false), .. })) } #[tracing::instrument(level = "debug", name = "range_filter_eval", skip_all)] pub fn apply(&self, stats: &StatisticsOfColumns) -> Result<bool> { let input_domains = self .expr .column_refs() .into_iter() .map(|(name, ty)| { let column_ids = self.schema.leaf_columns_of(&name); let stats = column_ids .iter() .filter_map(|column_id| stats.get(column_id)) .collect::<_>(); let domain = statistics_to_domain(stats, &ty); Ok((name, domain)) }) .collect::<Result<_>>()?; let (new_expr, _) = ConstantFolder::fold_with_domain( &self.expr, input_domains, self.func_ctx, &BUILTIN_FUNCTIONS, ); // Only return false, which means to skip this block, when the expression is folded to a constant false. Ok(!matches!(new_expr, Expr::Constant { scalar: Scalar::Boolean(false), .. })) } } pub fn statistics_to_domain(mut stats: Vec<&ColumnStatistics>, data_type: &DataType) -> Domain { if stats.len() != data_type.num_leaf_columns() { return Domain::full(data_type); } match data_type { DataType::Nullable(box inner_ty) => { if stats.len() == 1 && (stats[0].min.is_null() || stats[0].max.is_null()) { return Domain::Nullable(NullableDomain { has_null: true, value: None, }); } let has_null = if stats.len() == 1 { stats[0].null_count > 0 } else { // Only leaf columns have statistics, // nested columns are treated as having nullable values true }; let domain = statistics_to_domain(stats, inner_ty); Domain::Nullable(NullableDomain { has_null, value: Some(Box::new(domain)), }) } DataType::Tuple(inner_tys) => { let inner_domains = inner_tys .iter() .map(|inner_ty| { let n = inner_ty.num_leaf_columns(); let stats = stats.drain(..n).collect(); statistics_to_domain(stats, inner_ty) }) .collect::<Vec<_>>(); Domain::Tuple(inner_domains) } DataType::Array(box inner_ty) => { let n = inner_ty.num_leaf_columns(); let stats = stats.drain(..n).collect(); let inner_domain = statistics_to_domain(stats, inner_ty); Domain::Array(Some(Box::new(inner_domain))) } DataType::Map(box inner_ty) => { let n = inner_ty.num_leaf_columns(); let stats = stats.drain(..n).collect(); let inner_domain = statistics_to_domain(stats, inner_ty); let kv_domain = inner_domain.as_tuple().unwrap(); Domain::Map(Some(( Box::new(kv_domain[0].clone()), Box::new(kv_domain[1].clone()), ))) } _ => { let stat = stats[0]; with_number_mapped_type!(|NUM_TYPE| match data_type { DataType::Number(NumberDataType::NUM_TYPE) => { NumberType::<NUM_TYPE>::upcast_domain(SimpleDomain { min: NumberType::<NUM_TYPE>::try_downcast_scalar(&stat.min.as_ref()) .unwrap(), max: NumberType::<NUM_TYPE>::try_downcast_scalar(&stat.max.as_ref()) .unwrap(), }) } DataType::String => Domain::String(StringDomain { min: StringType::try_downcast_scalar(&stat.min.as_ref()) .unwrap() .to_vec(), max: Some( StringType::try_downcast_scalar(&stat.max.as_ref()) .unwrap() .to_vec() ), }), DataType::Timestamp => TimestampType::upcast_domain(SimpleDomain { min: TimestampType::try_downcast_scalar(&stat.min.as_ref()).unwrap(), max: TimestampType::try_downcast_scalar(&stat.max.as_ref()).unwrap(), }), DataType::Date => DateType::upcast_domain(SimpleDomain { min: DateType::try_downcast_scalar(&stat.min.as_ref()).unwrap(), max: DateType::try_downcast_scalar(&stat.max.as_ref()).unwrap(), }), // Unsupported data type _ => Domain::full(data_type), }) } } } impl Index for RangeIndex {}
use scanner_proc_macro::insert_scanner; #[insert_scanner] fn main() { let x = scan!(i64); let ans = if x >= 0 { x / 10 } else if x % 10 == 0 { x / 10 } else { x / 10 - 1 }; println!("{}", ans); }
use crate::{stark_hash, Felt}; /// HashChain is the structure used over at cairo side to represent the hash construction needed /// for computing the class hash. /// /// Empty hash chained value equals `H(0, 0)` where `H` is the [`stark_hash()`] function, and the /// second value is the number of values hashed together in this chain. For other values, the /// accumulator is on each update replaced with the `H(hash, value)` and the number of count /// incremented by one. #[derive(Default)] pub struct HashChain { hash: Felt, count: usize, } impl HashChain { pub fn update(&mut self, value: Felt) { self.hash = stark_hash(self.hash, value); self.count = self .count .checked_add(1) .expect("could not have deserialized larger than usize Vecs"); } pub fn chain_update(mut self, value: Felt) -> Self { self.update(value); self } pub fn finalize(self) -> Felt { let count = Felt::from_be_slice(&self.count.to_be_bytes()).expect("usize is smaller than 251-bits"); stark_hash(self.hash, count) } } #[cfg(test)] mod tests { use super::{Felt, HashChain}; #[test] fn test_non_empty_chain() { let mut chain = HashChain::default(); chain.update(Felt::from_hex_str("0x1").unwrap()); chain.update(Felt::from_hex_str("0x2").unwrap()); chain.update(Felt::from_hex_str("0x3").unwrap()); chain.update(Felt::from_hex_str("0x4").unwrap()); let computed_hash = chain.finalize(); // produced by the cairo-lang Python implementation: // `hex(compute_hash_on_elements([1, 2, 3, 4]))` let expected_hash = Felt::from_hex_str("0x66bd4335902683054d08a0572747ea78ebd9e531536fb43125424ca9f902084") .unwrap(); assert_eq!(expected_hash, computed_hash); } }
extern crate flate2; extern crate tar; use flate2::read::GzDecoder; use flate2::write::GzEncoder; use flate2::Compression; use std::fs::File; use std::path::Path; use tar::Archive; pub fn decompress_tgz(tar_path: &Path, output_dir: &Path) -> Result<(), std::io::Error> { // let path = "archive.tar.gz"; // let tar_gz = File::open(tar_path)?; let tar = GzDecoder::new(tar_gz); let mut archive = Archive::new(tar); archive.unpack(output_dir)?; // println!("{:?}\n{:?}", tar_path, output_dir); Ok(()) } pub fn compress() -> Result<(), std::io::Error> { let tar_gz = File::create("archive.tar.gz")?; let enc = GzEncoder::new(tar_gz, Compression::default()); let mut tar = tar::Builder::new(enc); let mut f = File::open("test_data/hello.txt").unwrap(); tar.append_file("gen/scrooge/297e53822ddf/wilyns.thrift.src.main.thrift.thrift-scala/c8959dfdc97a/com/twitter/wilyns/thriftscala/LookupRequest.scala", &mut f )?; tar.finish(); Ok(()) }
#[doc = "Reader of register CLKCR"] pub type R = crate::R<u32, super::CLKCR>; #[doc = "Writer for register CLKCR"] pub type W = crate::W<u32, super::CLKCR>; #[doc = "Register CLKCR `reset()`'s with value 0"] impl crate::ResetValue for super::CLKCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CLKDIV`"] pub type CLKDIV_R = crate::R<u16, u16>; #[doc = "Write proxy for field `CLKDIV`"] pub struct CLKDIV_W<'a> { w: &'a mut W, } impl<'a> CLKDIV_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x03ff) | ((value as u32) & 0x03ff); self.w } } #[doc = "Reader of field `PWRSAV`"] pub type PWRSAV_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PWRSAV`"] pub struct PWRSAV_W<'a> { w: &'a mut W, } impl<'a> PWRSAV_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 `WIDBUS`"] pub type WIDBUS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WIDBUS`"] pub struct WIDBUS_W<'a> { w: &'a mut W, } impl<'a> WIDBUS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14); self.w } } #[doc = "Reader of field `NEGEDGE`"] pub type NEGEDGE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `NEGEDGE`"] pub struct NEGEDGE_W<'a> { w: &'a mut W, } impl<'a> NEGEDGE_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 `HWFC_EN`"] pub type HWFC_EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HWFC_EN`"] pub struct HWFC_EN_W<'a> { w: &'a mut W, } impl<'a> HWFC_EN_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 `DDR`"] pub type DDR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DDR`"] pub struct DDR_W<'a> { w: &'a mut W, } impl<'a> DDR_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 `BUSSPEED`"] pub type BUSSPEED_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BUSSPEED`"] pub struct BUSSPEED_W<'a> { w: &'a mut W, } impl<'a> BUSSPEED_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 `SELCLKRX`"] pub type SELCLKRX_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SELCLKRX`"] pub struct SELCLKRX_W<'a> { w: &'a mut W, } impl<'a> SELCLKRX_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 20)) | (((value as u32) & 0x03) << 20); self.w } } impl R { #[doc = "Bits 0:9 - Clock divide factor This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0). This field defines the divide factor between the input clock (SDMMCCLK) and the output clock (SDMMC_CK): SDMMC_CK frequency = SDMMCCLK / \\[2 * CLKDIV\\]. 0xx: etc.. xxx: etc.."] #[inline(always)] pub fn clkdiv(&self) -> CLKDIV_R { CLKDIV_R::new((self.bits & 0x03ff) as u16) } #[doc = "Bit 12 - Power saving configuration bit This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0) For power saving, the SDMMC_CK clock output can be disabled when the bus is idle by setting PWRSAV:"] #[inline(always)] pub fn pwrsav(&self) -> PWRSAV_R { PWRSAV_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bits 14:15 - Wide bus mode enable bit This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0)"] #[inline(always)] pub fn widbus(&self) -> WIDBUS_R { WIDBUS_R::new(((self.bits >> 14) & 0x03) as u8) } #[doc = "Bit 16 - SDMMC_CK dephasing selection bit for data and Command. This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0). When clock division = 1 (CLKDIV = 0), this bit has no effect. Data and Command change on SDMMC_CK falling edge. When clock division &gt;1 (CLKDIV &gt; 0) &amp; DDR = 0: - SDMMC_CK edge occurs on SDMMCCLK rising edge. When clock division >1 (CLKDIV > 0) & DDR = 1: - Data changed on the SDMMCCLK falling edge succeeding a SDMMC_CK edge. - SDMMC_CK edge occurs on SDMMCCLK rising edge. - Data changed on the SDMMC_CK falling edge succeeding a SDMMC_CK edge. - SDMMC_CK edge occurs on SDMMCCLK rising edge."] #[inline(always)] pub fn negedge(&self) -> NEGEDGE_R { NEGEDGE_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - Hardware flow control enable This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0) When Hardware flow control is enabled, the meaning of the TXFIFOE and RXFIFOF flags change, please see SDMMC status register definition in Section56.8.11."] #[inline(always)] pub fn hwfc_en(&self) -> HWFC_EN_R { HWFC_EN_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - Data rate signaling selection This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0) DDR rate shall only be selected with 4-bit or 8-bit wide bus mode. (WIDBUS &gt; 00). DDR = 1 has no effect when WIDBUS = 00 (1-bit wide bus). DDR rate shall only be selected with clock division &gt;1. (CLKDIV &gt; 0)"] #[inline(always)] pub fn ddr(&self) -> DDR_R { DDR_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - Bus speed mode selection between DS, HS, SDR12, SDR25 and SDR50, DDR50, SDR104. This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0)"] #[inline(always)] pub fn busspeed(&self) -> BUSSPEED_R { BUSSPEED_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bits 20:21 - Receive clock selection. These bits can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0)"] #[inline(always)] pub fn selclkrx(&self) -> SELCLKRX_R { SELCLKRX_R::new(((self.bits >> 20) & 0x03) as u8) } } impl W { #[doc = "Bits 0:9 - Clock divide factor This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0). This field defines the divide factor between the input clock (SDMMCCLK) and the output clock (SDMMC_CK): SDMMC_CK frequency = SDMMCCLK / \\[2 * CLKDIV\\]. 0xx: etc.. xxx: etc.."] #[inline(always)] pub fn clkdiv(&mut self) -> CLKDIV_W { CLKDIV_W { w: self } } #[doc = "Bit 12 - Power saving configuration bit This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0) For power saving, the SDMMC_CK clock output can be disabled when the bus is idle by setting PWRSAV:"] #[inline(always)] pub fn pwrsav(&mut self) -> PWRSAV_W { PWRSAV_W { w: self } } #[doc = "Bits 14:15 - Wide bus mode enable bit This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0)"] #[inline(always)] pub fn widbus(&mut self) -> WIDBUS_W { WIDBUS_W { w: self } } #[doc = "Bit 16 - SDMMC_CK dephasing selection bit for data and Command. This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0). When clock division = 1 (CLKDIV = 0), this bit has no effect. Data and Command change on SDMMC_CK falling edge. When clock division &gt;1 (CLKDIV &gt; 0) &amp; DDR = 0: - SDMMC_CK edge occurs on SDMMCCLK rising edge. When clock division >1 (CLKDIV > 0) & DDR = 1: - Data changed on the SDMMCCLK falling edge succeeding a SDMMC_CK edge. - SDMMC_CK edge occurs on SDMMCCLK rising edge. - Data changed on the SDMMC_CK falling edge succeeding a SDMMC_CK edge. - SDMMC_CK edge occurs on SDMMCCLK rising edge."] #[inline(always)] pub fn negedge(&mut self) -> NEGEDGE_W { NEGEDGE_W { w: self } } #[doc = "Bit 17 - Hardware flow control enable This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0) When Hardware flow control is enabled, the meaning of the TXFIFOE and RXFIFOF flags change, please see SDMMC status register definition in Section56.8.11."] #[inline(always)] pub fn hwfc_en(&mut self) -> HWFC_EN_W { HWFC_EN_W { w: self } } #[doc = "Bit 18 - Data rate signaling selection This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0) DDR rate shall only be selected with 4-bit or 8-bit wide bus mode. (WIDBUS &gt; 00). DDR = 1 has no effect when WIDBUS = 00 (1-bit wide bus). DDR rate shall only be selected with clock division &gt;1. (CLKDIV &gt; 0)"] #[inline(always)] pub fn ddr(&mut self) -> DDR_W { DDR_W { w: self } } #[doc = "Bit 19 - Bus speed mode selection between DS, HS, SDR12, SDR25 and SDR50, DDR50, SDR104. This bit can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0)"] #[inline(always)] pub fn busspeed(&mut self) -> BUSSPEED_W { BUSSPEED_W { w: self } } #[doc = "Bits 20:21 - Receive clock selection. These bits can only be written when the CPSM and DPSM are not active (CPSMACT = 0 and DPSMACT = 0)"] #[inline(always)] pub fn selclkrx(&mut self) -> SELCLKRX_W { SELCLKRX_W { w: self } } }
use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; pub fn lines_from_file(filename: &str) -> Vec<String> { let mut file = match File::open(filename) { Ok(file) => file, Err(_) => panic!("no such file"), }; let mut file_contents = String::new(); file.read_to_string(&mut file_contents) .ok() .expect("failed to read!"); let lines: Vec<String> = file_contents.split("\n") .map(|s: &str| s.to_string()) .collect(); lines } pub fn count_bit(bit: &mut [u8]) -> f32 { let mut counter = 0.0; for i in 0..bit.len() { counter += bit[i].count_ones() as f32; } counter } pub fn byte_xor(byte1: &[u8], byte2: &[u8]) -> Vec<u8> { let mut xor = Vec::new(); for i in 0..byte1.len() { xor.push(byte1[i] ^ byte2[i]); } xor } pub fn get_text_from_file(filename: &str) -> Vec<u8>{ let mut file = match File::open(filename) { Ok(file) => file, Err(_) => panic!("no such file"), }; let mut text = String::new(); file.read_to_string(&mut text) .ok() .expect("failed to read!"); text.as_bytes().to_vec() } pub fn single_byte_xor(string: &[u8], key: u8) -> Vec<u8> { string.iter().map(| x | x ^ key).collect() } pub fn hex_to_bytes(string: &str) -> Vec<u8> { let mut bytes: Vec<u8> = Vec::new(); for i in 0..(string.len() / 2) { match u8::from_str_radix(&string[2 * i..2 * i + 2], 16) { Ok(n) => bytes.push(n), Err(_) => println!("Error in hex conversion"), } } bytes } pub fn get_score(xor: &Vec<u8>) -> u32 { let frequency: HashMap<u8, u32> = [ (b'a', 8), (b'e', 12), (b'h', 6), (b'i', 7), (b'n', 7), (b'o', 8), (b't', 8), (b's', 6), (b'r', 6), (b'd', 4), (b'l', 4), (b'c', 3), (b'u', 3), (b' ', 12), ] .iter().cloned().collect(); // Check if there are only ASCII values if xor.len() == 0 || !xor.iter().all(|c| c < &127) { return 0; } xor.iter().map(|b| frequency.get(&b.to_ascii_lowercase()).unwrap_or(&0)).sum() }
use ggez::event; use block::Block; use color::Color; use coord::Coord; use ggez::Context; use ggez::graphics; use square::Square; use consts::SCORE_LINE; use ggez::graphics::Font; use consts::{WINDOW_HEIGHT, WINDOW_WIDTH}; use consts::{GAME_FIELD_POS_X, GAME_FIELD_POS_Y}; use consts::{GAME_FIELD_HEIGHT, GAME_FIELD_WIDTH}; use consts::{GAME_FIELD_BORDER_SIZE, SQUARE_BORDER, SQUARE_SIDE}; use consts::{BACKGROUND_COLOR, GAME_FIELD_BORDER_COLOR, GAME_FIELD_COLOR}; use consts::{PREVIEW_POS_X, PREVIEW_POS_Y, PREVIEW_SIZE_X, PREVIEW_SIZE_Y}; pub struct Gamestate { score: i32, game_over: bool, next_block: Block, current_block: Block, field: [Square; (GAME_FIELD_WIDTH * GAME_FIELD_HEIGHT) as usize], } impl Gamestate { pub fn new() -> Self { Gamestate { score: 0, game_over: false, next_block: Block::new(), current_block: Block::new(), field: [Square::ThereIsNo; (GAME_FIELD_WIDTH * GAME_FIELD_HEIGHT) as usize], } } pub fn input(&mut self, ctx: &mut Context, events: &mut event::Events, exit: &mut bool) { for event in events.poll() { ctx.process_event(&event); match event { event::Event::Quit { .. } | event::Event::KeyDown { keycode: Some(event::Keycode::Escape), .. } => *exit = true, event::Event::KeyDown { keycode: Some(event::Keycode::Up), .. } => self.current_block.rotate(&self.field), event::Event::KeyDown { keycode: Some(event::Keycode::Right), .. } => self.current_block.right(&self.field), event::Event::KeyDown { keycode: Some(event::Keycode::Left), .. } => self.current_block.left(&self.field), event::Event::KeyDown { keycode: Some(event::Keycode::Down), .. } => self.current_block.boost(), event::Event::KeyUp { keycode: Some(event::Keycode::Down), .. } => self.current_block.brake(), _ => {} } } } pub fn frame(&mut self) { self.current_block.lower(); if self.current_block.detect_collision(&self.field) { if self.current_block.position().y as i32 <= 1 { self.game_over = true; } self.current_block.up(); self.block_to_field(); self.score += self.current_block.shape().points(); self.current_block = self.next_block; self.next_block = Block::new(); self.check_rows(); } } pub fn draw(&self, ctx: &mut Context, font: &Font) { graphics::clear(ctx); self.draw_background(ctx); self.draw_field(ctx); self.draw_current_block(ctx); self.draw_preview(ctx); self.draw_next_block(ctx); self.draw_score(ctx, font); graphics::present(ctx); } fn draw_score(&self, ctx: &mut Context, font: &Font) { let text = graphics::Text::new( ctx, &("score: ".to_string() + &self.score.to_string()), &font, ).expect("!"); graphics::draw( ctx, &text, graphics::Point2::new( PREVIEW_POS_X as f32, (PREVIEW_POS_Y + PREVIEW_SIZE_Y) as f32 - 40.0, ), 0.0, ).expect("!"); } fn block_to_field(&mut self) { let block = self.current_block.block(); for i in 0..block.0.len() { if self.current_block.position().y as i32 <= 0 { continue; } let x = self.current_block.position().x as i32 + block.0[i].x as i32; let y = self.current_block.position().y as i32 + block.0[i].y as i32; self.field[(x + y * GAME_FIELD_WIDTH) as usize] = Square::ThereIs(block.1, block.2); } } fn check_rows(&mut self) { 'y: for mut y in 0..GAME_FIELD_HEIGHT { for x in 0..GAME_FIELD_WIDTH { match self.field[(x + y * GAME_FIELD_WIDTH) as usize] { Square::ThereIs(_, _) => {} Square::ThereIsNo => continue 'y, } } self.score += SCORE_LINE; for row in 0..y { for col in 0..GAME_FIELD_WIDTH { if row < 0 { self.field[(col + (y - row) * GAME_FIELD_WIDTH) as usize] = Square::ThereIsNo; } else { self.field[(col + (y - row) * GAME_FIELD_WIDTH) as usize] = self.field[(col + (y - row - 1) * GAME_FIELD_WIDTH) as usize]; } } } } } fn draw_next_block(&self, ctx: &mut Context) { let block = self.next_block.block(); let x = self.next_block.shape().x() / 2.0; let y = self.next_block.shape().y() / 2.0; for i in 0..4 { self.draw_square( ctx, Coord::new_f( PREVIEW_POS_X as f32 + ((PREVIEW_SIZE_X as f32 * SQUARE_SIDE) / 2.0) - x * SQUARE_SIDE + block.0[i].x * SQUARE_SIDE, PREVIEW_POS_Y as f32 + ((PREVIEW_SIZE_Y as f32 * SQUARE_SIDE) / 2.0) - y * SQUARE_SIDE + block.0[i].y * SQUARE_SIDE, ), block.1, block.2, ); } } fn draw_preview(&self, ctx: &mut Context) { let preview = ( Coord::new(PREVIEW_POS_X as i32, PREVIEW_POS_Y as i32), Coord::new( PREVIEW_SIZE_X * SQUARE_SIDE as i32, PREVIEW_SIZE_Y * SQUARE_SIDE as i32, ), ); let rect = graphics::Rect::new( preview.0.x - GAME_FIELD_BORDER_SIZE, preview.0.y - GAME_FIELD_BORDER_SIZE, preview.1.x + GAME_FIELD_BORDER_SIZE * 2.0, preview.1.y + GAME_FIELD_BORDER_SIZE * 2.0, ); graphics::set_color( ctx, graphics::Color::from_rgb( GAME_FIELD_BORDER_COLOR.red(), GAME_FIELD_BORDER_COLOR.green(), GAME_FIELD_BORDER_COLOR.blue(), ), ).expect("HA LOL"); graphics::rectangle(ctx, graphics::DrawMode::Fill, rect).expect("BLEN"); let rect = graphics::Rect::new(preview.0.x, preview.0.y, preview.1.x, preview.1.y); graphics::set_color( ctx, graphics::Color::from_rgb( GAME_FIELD_COLOR.0.red(), GAME_FIELD_COLOR.0.green(), GAME_FIELD_COLOR.0.blue(), ), ).expect("HA LOL"); graphics::rectangle(ctx, graphics::DrawMode::Fill, rect).expect("BLEN"); } fn draw_field(&self, ctx: &mut Context) { let field = ( Coord::new(GAME_FIELD_POS_X as i32, GAME_FIELD_POS_Y as i32), Coord::new( GAME_FIELD_WIDTH * SQUARE_SIDE as i32, GAME_FIELD_HEIGHT * SQUARE_SIDE as i32, ), ); let rect = graphics::Rect::new( field.0.x - GAME_FIELD_BORDER_SIZE, field.0.y - GAME_FIELD_BORDER_SIZE, field.1.x + GAME_FIELD_BORDER_SIZE * 2.0, field.1.y + GAME_FIELD_BORDER_SIZE * 2.0, ); graphics::set_color( ctx, graphics::Color::from_rgb( GAME_FIELD_BORDER_COLOR.red(), GAME_FIELD_BORDER_COLOR.green(), GAME_FIELD_BORDER_COLOR.blue(), ), ).expect("HA LOL"); graphics::rectangle(ctx, graphics::DrawMode::Fill, rect).expect("BLEN"); for i in 0..GAME_FIELD_WIDTH { let rect = graphics::Rect::new( GAME_FIELD_POS_X as f32 + SQUARE_SIDE * i as f32, field.0.y, SQUARE_SIDE, field.1.y, ); if i % 2 == 0 { graphics::set_color( ctx, graphics::Color::from_rgb( GAME_FIELD_COLOR.0.red(), GAME_FIELD_COLOR.0.green(), GAME_FIELD_COLOR.0.blue(), ), ).expect("HA LOL"); } else { graphics::set_color( ctx, graphics::Color::from_rgb( GAME_FIELD_COLOR.1.red(), GAME_FIELD_COLOR.1.green(), GAME_FIELD_COLOR.1.blue(), ), ).expect("HA LOL"); } graphics::rectangle(ctx, graphics::DrawMode::Fill, rect).expect("BLEN"); } for i in 0..self.field.len() { let y = i as i32 / GAME_FIELD_WIDTH; let x = i as i32 % GAME_FIELD_WIDTH; match self.field[(x + y * GAME_FIELD_WIDTH) as usize] { Square::ThereIs(ref c1, ref c2) => self.draw_square( ctx, Coord::new( GAME_FIELD_POS_X + x * SQUARE_SIDE as i32, GAME_FIELD_POS_Y + y * SQUARE_SIDE as i32, ), *c1, *c2, ), Square::ThereIsNo => {} } } } fn draw_background(&self, ctx: &mut Context) { let rect = graphics::Rect::new(0.0, 0.0, WINDOW_WIDTH as f32, WINDOW_HEIGHT as f32); graphics::set_color( ctx, graphics::Color::from_rgb( BACKGROUND_COLOR.red(), BACKGROUND_COLOR.green(), BACKGROUND_COLOR.blue(), ), ).expect("HA LOL"); graphics::rectangle(ctx, graphics::DrawMode::Fill, rect).expect("BLEN"); } fn draw_current_block(&self, ctx: &mut Context) { let block = self.current_block.block(); for i in 0..4 { self.draw_square( ctx, Coord::new( GAME_FIELD_POS_X + (self.current_block.position().x as i32 * SQUARE_SIDE as i32) + (block.0[i].x as i32 * SQUARE_SIDE as i32), GAME_FIELD_POS_Y + (self.current_block.position().y as i32 * SQUARE_SIDE as i32) + (block.0[i].y as i32 * SQUARE_SIDE as i32), ), block.1, block.2, ); } } fn draw_square(&self, ctx: &mut Context, position: Coord, color1: Color, color2: Color) { if position.y as i32 <= 0 { return; } let rect = graphics::Rect::new(position.x, position.y, SQUARE_SIDE, SQUARE_SIDE); graphics::set_color( ctx, graphics::Color::from_rgb(color1.red(), color1.green(), color1.blue()), ).expect("HA LOL"); graphics::rectangle(ctx, graphics::DrawMode::Fill, rect).expect("BLEN"); let rect = graphics::Rect::new( position.x + SQUARE_BORDER, position.y + SQUARE_BORDER, SQUARE_SIDE - SQUARE_BORDER * 2.0, SQUARE_SIDE - SQUARE_BORDER * 2.0, ); graphics::set_color( ctx, graphics::Color::from_rgb(color2.red(), color2.green(), color2.blue()), ).expect("HA LOL"); graphics::rectangle(ctx, graphics::DrawMode::Fill, rect).expect("BLEN"); } pub fn game_over(&self) -> bool { self.game_over } }
extern crate native_windows_derive as nwd; extern crate native_windows_gui as nwg; use std::cell::RefCell; use std::rc::Rc; use nwg::NativeUi; use nwd::NwgUi; use nwg::stretch::{geometry::{Size, Rect},style::{Dimension, FlexDirection, JustifyContent, Style},}; const PT_10: Dimension = Dimension::Points(10.0); const PAD: Rect<Dimension> = Rect { start: PT_10, end: PT_10, top: PT_10, bottom: PT_10 }; #[derive(Default, NwgUi)] pub struct MyApp { #[nwg_control(title: "test", size: (400, 300), position: (80, 60))] #[nwg_events(OnWindowClose: [nwg::stop_thread_dispatch()], OnInit: [MyApp::setup_combo_callback(RC_SELF)])] window: nwg::Window, #[nwg_layout(parent: window, padding: PAD, auto_spacing: None, flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center)] main_layout: nwg::FlexboxLayout, #[nwg_control(text: "Add combobox")] #[nwg_layout_item(layout: main_layout, size: Size { width: Dimension::Percent(1.0), height: Dimension::Points(40.0)})] #[nwg_events(OnButtonClick: [MyApp::add_combobox])] button: nwg::Button, #[nwg_control(parent: window, flags: "VISIBLE")] #[nwg_layout_item(layout: main_layout, size: Size { width: Dimension::Percent(1.0), height: Dimension::Points(290.0)})] frame: nwg::Frame, #[nwg_layout(parent: frame, padding: PAD, auto_spacing: None, flex_direction: FlexDirection::Column)] frame_layout: nwg::FlexboxLayout, combo_box_handler: RefCell<Option<nwg::EventHandler>>, combo_boxes: RefCell<Vec<nwg::ComboBox<String>>>, } impl MyApp { fn setup_combo_callback(app_rc: &Rc<MyApp>) { // Clone the app and store it in our own callback let app = app_rc.clone(); let handler = nwg::bind_event_handler(&app_rc.frame.handle, &app_rc.window.handle, move |evt, _evt_data, handle| { match evt { nwg::Event::OnComboxBoxSelection => { // Fetch the combobox here let boxes = app.combo_boxes.borrow(); for (index, combo) in boxes.iter().enumerate() { if combo.handle == handle { println!("Accessed combobox #{}", index); } } }, _ => {} } }); *app_rc.combo_box_handler.borrow_mut() = Some(handler); } fn add_combobox(&self) { let mut new_dd: nwg::ComboBox<String> = nwg::ComboBox::<String>::default(); let coll = vec![String::from("one"), String::from("two"), String::from("three")]; nwg::ComboBox::builder() .collection(coll) .parent(&self.frame) .build(&mut new_dd) .expect("Failed to create token"); let style = Style { size: Size { width: Dimension::Percent(1.0), height: Dimension::Points(40.0) }, ..Default::default() }; self.frame_layout .add_child(&new_dd, style) .expect("Failed to add token to layout"); self.combo_boxes.borrow_mut().push(new_dd); } } fn main() { nwg::init().expect("Failed to init Native Windows GUI"); nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font"); let _app = MyApp::build_ui(Default::default()).expect("Failed to build UI"); nwg::dispatch_thread_events(); }
use instant_segment::{Search, Segmenter}; use std::collections::HashMap; fn main() { let mut unigrams = HashMap::default(); unigrams.insert("choose".into(), 80_000.0); unigrams.insert("chooses".into(), 7_000.0); unigrams.insert("spain".into(), 20_000.0); unigrams.insert("pain".into(), 90_000.0); let mut bigrams = HashMap::default(); bigrams.insert(("choose".into(), "spain".into()), 7.0); bigrams.insert(("chooses".into(), "pain".into()), 0.0); let segmenter = Segmenter::from_maps(unigrams, bigrams); let mut search = Search::default(); let words = segmenter.segment("choosespain", &mut search).unwrap(); println!("{:?}", words.collect::<Vec<&str>>()); }
#![crate_name = "cabocha"] #![crate_type = "lib"] #![crate_type = "dylib"] #![crate_type = "rlib"] mod chunk; pub mod consts; pub mod parser; mod sys; mod token; mod tree; mod utils;
rustler::atoms! { ok, error, }
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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. // run-pass // ignore-pretty pretty-printing is unhygienic // aux-build:legacy_interaction.rs #![feature(decl_macro)] #[allow(unused)] extern crate legacy_interaction; // ^ defines // ```rust // macro_rules! m { // () => { // fn f() // (1) // g() // (2) // } // } // ```rust mod def_site { // Unless this macro opts out of hygiene, it should resolve the same wherever it is invoked. pub macro m2() { ::legacy_interaction::m!(); f(); // This should resolve to (1) fn g() {} // We want (2) resolve to this, not to (4) } } mod use_site { fn test() { fn f() -> bool { true } // (3) fn g() -> bool { true } // (4) ::def_site::m2!(); let _: bool = f(); // This should resolve to (3) let _: bool = g(); // This should resolve to (4) } } fn main() {}