text
stringlengths
8
4.13M
#![deny(warnings, unused_must_use)] extern crate log; use std::path::{Path, PathBuf}; use std::sync::Arc; use structopt::StructOpt; use zircon_loader::*; use zircon_object::object::*; #[derive(Debug, StructOpt)] #[structopt()] struct Opt { #[structopt(parse(from_os_str))] prebuilt_path: PathBuf, #[structopt(default_value = "")] cmdline: String, #[structopt(short, long)] debug: bool, } #[async_std::main] async fn main() { kernel_hal_unix::init(); init_logger(); let opt = Opt::from_args(); let images = open_images(&opt.prebuilt_path, opt.debug).expect("failed to read file"); let proc: Arc<dyn KernelObject> = run_userboot(&images, &opt.cmdline); drop(images); proc.wait_signal(Signal::USER_SIGNAL_0).await; } fn open_images(path: &Path, debug: bool) -> std::io::Result<Images<Vec<u8>>> { Ok(Images { userboot: std::fs::read(path.join("userboot-libos.so"))?, vdso: std::fs::read(path.join("libzircon-libos.so"))?, zbi: if debug { std::fs::read(path.join("core-tests.zbi"))? } else { std::fs::read(path.join("bringup.zbi"))? }, }) } fn init_logger() { env_logger::builder() .format(|buf, record| { use env_logger::fmt::Color; use log::Level; use std::io::Write; let (tid, pid) = kernel_hal::Thread::get_tid(); let mut style = buf.style(); match record.level() { Level::Trace => style.set_color(Color::Black).set_intense(true), Level::Debug => style.set_color(Color::White), Level::Info => style.set_color(Color::Green), Level::Warn => style.set_color(Color::Yellow), Level::Error => style.set_color(Color::Red).set_bold(true), }; let now = kernel_hal_unix::timer_now(); let level = style.value(record.level()); let args = record.args(); writeln!(buf, "[{:?} {:>5} {}:{}] {}", now, level, pid, tid, args) }) .init(); } #[cfg(test)] mod tests { use super::*; #[async_std::test] async fn userboot() { kernel_hal_unix::init(); let opt = Opt { #[cfg(target_arch = "x86_64")] prebuilt_path: PathBuf::from("../prebuilt/zircon/x64"), #[cfg(target_arch = "aarch64")] prebuilt_path: PathBuf::from("../prebuilt/zircon/arm64"), cmdline: String::from(""), debug: false, }; let images = open_images(&opt.prebuilt_path, opt.debug).expect("failed to read file"); let proc: Arc<dyn KernelObject> = run_userboot(&images, &opt.cmdline); drop(images); proc.wait_signal(Signal::PROCESS_TERMINATED).await; } }
use std::borrow::Cow; use std::convert::TryFrom; #[cfg(feature = "sender")] use crate::sender; pub struct Uri<'a> { pub(crate) address: bitcoin::Address, pub(crate) amount: bitcoin::Amount, pub(crate) endpoint: Cow<'a, str>, pub(crate) disable_output_substitution: bool, } impl<'a> Uri<'a> { pub fn address(&self) -> &bitcoin::Address { &self.address } pub fn amount(&self) -> bitcoin::Amount { self.amount } pub fn is_output_substitution_disabled(&self) -> bool { self.disable_output_substitution } #[cfg(feature = "sender")] pub fn create_request(self, psbt: bitcoin::util::psbt::PartiallySignedTransaction, params: sender::Params) -> Result<(sender::Request, sender::Context), sender::CreateRequestError> { sender::from_psbt_and_uri(psbt, self, params) } pub fn into_static(self) -> Uri<'static> { Uri { address: self.address, amount: self.amount, endpoint: Cow::Owned(self.endpoint.into()), disable_output_substitution: self.disable_output_substitution, } } } impl<'a> TryFrom<&'a str> for Uri<'a> { type Error = ParseUriError; fn try_from(s: &'a str) -> Result<Self, Self::Error> { fn match_kv<'a, T, E: Into<ParseUriError>, F: FnOnce(&'a str) -> Result<T, E>>(kv: &'a str, prefix: &'static str, out: &mut Option<T>, fun: F) -> Result<(), ParseUriError> where ParseUriError: From<E> { if kv.starts_with(prefix) { let value = fun(&kv[prefix.len()..])?; if out.is_some() { return Err(InternalBip21Error::DuplicateKey(prefix).into()); } *out = Some(value); } Ok(()) } let prefix = "bitcoin:"; if !s.chars().zip(prefix.chars()).all(|(left, right)| left.to_ascii_lowercase() == right) { return Err(InternalBip21Error::BadSchema(s.into()).into()) } let uri_without_prefix = &s[prefix.len()..]; let question_mark_pos = uri_without_prefix.find('?').ok_or(ParseUriError::PjNotPresent)?; let address = uri_without_prefix[..question_mark_pos].parse().map_err(InternalBip21Error::Address)?; let mut amount = None; let mut endpoint = None; let mut disable_pjos = None; for kv in uri_without_prefix[(question_mark_pos + 1)..].split('&') { match_kv(kv, "amount=", &mut amount, |s| bitcoin::Amount::from_str_in(s, bitcoin::Denomination::Bitcoin).map_err(InternalBip21Error::Amount))?; match_kv(kv, "pjos=", &mut disable_pjos, |s| if s == "0" { Ok(true) } else if s == "1" { Ok(false) } else { Err(InternalPjParseError::BadPjos(s.into())) })?; match_kv(kv, "pj=", &mut endpoint, |s| if s.starts_with("https://") || s.starts_with("http://") { Ok(s) } else { Err(InternalPjParseError::BadSchema(s.into())) })?; } match (amount, endpoint, disable_pjos) { (_, None, None) => Err(ParseUriError::PjNotPresent), (Some(amount), Some(endpoint), disable_pjos) => Ok(Uri { address, amount, endpoint: endpoint.into(), disable_output_substitution: disable_pjos.unwrap_or(false), }), (None, Some(_), _) => Err(ParseUriError::PayJoin(PjParseError(InternalPjParseError::MissingAmount))), (None, None, Some(_)) => Err(ParseUriError::PayJoin(PjParseError(InternalPjParseError::MissingAmountAndEndpoint))), (Some(_), None, Some(_)) => Err(ParseUriError::PayJoin(PjParseError(InternalPjParseError::MissingEndpoint))), } } } impl std::str::FromStr for Uri<'static> { type Err = ParseUriError; fn from_str(s: &str) -> Result<Self, Self::Err> { Uri::try_from(s).map(Uri::into_static) } } #[derive(Debug)] pub enum ParseUriError { PjNotPresent, Bip21(Bip21Error), PayJoin(PjParseError), } #[derive(Debug)] pub struct Bip21Error(InternalBip21Error); #[derive(Debug)] pub struct PjParseError(InternalPjParseError); #[derive(Debug)] enum InternalBip21Error { Amount(bitcoin::util::amount::ParseAmountError), DuplicateKey(&'static str), BadSchema(String), Address(bitcoin::util::address::Error), } #[derive(Debug)] enum InternalPjParseError { BadPjos(String), BadSchema(String), MissingAmount, MissingAmountAndEndpoint, MissingEndpoint, } impl From<Bip21Error> for ParseUriError { fn from(value: Bip21Error) -> Self { ParseUriError::Bip21(value) } } impl From<PjParseError> for ParseUriError { fn from(value: PjParseError) -> Self { ParseUriError::PayJoin(value) } } impl From<InternalBip21Error> for ParseUriError { fn from(value: InternalBip21Error) -> Self { Bip21Error(value).into() } } impl From<InternalPjParseError> for ParseUriError { fn from(value: InternalPjParseError) -> Self { PjParseError(value).into() } }
pub fn inverse(self) -> Self {{ let high_bits = (self.bits & ({low_bits})) << 1; let low_bits = (self.bits & ({high_bits})) >> 1; let same_bits = self.bits & ({same_bits}); {type_name} {{ bits: low_bits | high_bits | same_bits}} }}
use std::io::Write; use std::io; use std::io::prelude::*; use std::rc::Rc; use std::env; use std::fs::File; mod tokenizer; mod parser; mod builtins; mod interpreter; macro_rules! perror( ($($arg:tt)*) => { { writeln!(&mut ::std::io::stderr(), $($arg)*).expect("failed printing to stderr"); } } ); fn process_line(interpreter: &mut interpreter::Interpreter, line: &String) -> Result<Vec<Rc<interpreter::Value>>, String> { match tokenizer::Tokenizer::new(&line).collect() { Ok(tokens) => { match parser::Parser::new(tokens).collect() { Ok(nodes) => { let nodes: Vec<parser::Node> = nodes; let mut values: Vec<Rc<interpreter::Value>> = vec![]; for node in nodes { match interpreter.eval(Rc::new(node)) { Ok(value) => values.push(value), Err(e) => { return Err(e); } } } return Ok(values); }, Err(e) => Err(e) } }, Err(e) => Err(e) } } fn process_file(filename: String) { let mut interpreter = interpreter::Interpreter::new(); let mut file = match File::open(filename) { Ok(file) => file, Err(e) => { perror!("{:?}", e); std::process::exit(1); } }; let mut buf = String::new(); match file.read_to_string(&mut buf) { Ok(_) => {}, Err(e) => { perror!("{:?}", e); std::process::exit(1); } }; match tokenizer::Tokenizer::new(&buf).collect() { Ok(tokens) => { match parser::Parser::new(tokens).collect() { Ok(nodes) => { let nodes: Vec<parser::Node> = nodes; for node in nodes { match interpreter.eval(Rc::new(node)) { Ok(_) => {}, Err(e) => { perror!("Error: {:?}", e); std::process::exit(1); } } } }, Err(e) => { perror!("Error: {:?}", e); std::process::exit(1); } } }, Err(e) => { perror!("Error: {:?}", e); std::process::exit(1); } } } fn repl() { println!("yial: REPL (Ctrl+D to exit)"); let mut interpreter = interpreter::Interpreter::new(); loop { print!(">_ "); io::stdout().flush().unwrap(); let mut buf = String::new(); match io::stdin().read_line(&mut buf) { Ok(len) => { if len == 0 { break; } match process_line(&mut interpreter, &buf) { Ok(values) => { let mut i = 0; for value in values { perror!("${} = {:?}", i, value); i += 1; } }, Err(e) => perror!("Error: {:?}", e) } }, Err(e) => { perror!("Error: {:?}", e); std::process::exit(1); } } } println!("\nBye!"); } fn main() { if let Some(filename) = env::args().nth(1) { process_file(filename); } else { repl(); } }
use super::bbox::BBox; use crate::{ geo::{collection::Mesh, HitTemp}, linalg::{Ray, Vct}, Flt, }; #[derive(Clone, Debug)] pub struct Node { pub bbox: BBox, pub data: Data, } #[derive(Clone, Debug)] pub enum Data { A(usize, usize, usize, Flt), // l, r, dim, key B(Vec<usize>), } #[derive(Clone, Debug, Default)] pub struct KDTree { nodes: Vec<Node>, } const K: usize = 10; impl KDTree { fn _hit(&self, ry: &Ray, mesh: &Mesh) -> Option<HitTemp> { let origin = &ry.origin; let inv_direct = &Vct::new(1.0 / ry.direct.x, 1.0 / ry.direct.y, 1.0 / ry.direct.z); let neg_index = &[inv_direct.x < 0.0, inv_direct.y < 0.0, inv_direct.z < 0.0]; macro_rules! bbox { ($x:expr) => { self.nodes[$x].bbox }; } if let Some((t_min, t_max)) = bbox!(0).fast_hit(origin, inv_direct, neg_index) { let mut ans: Option<HitTemp> = None; let mut stk = Vec::new(); stk.push((0, t_min, t_max)); while let Some((mut x, mut t_min, mut t_max)) = stk.pop() { while let Some((min, max)) = bbox!(x).fast_hit(origin, inv_direct, neg_index) { if t_min < min { t_min = min; } if t_max > max { t_max = max; } if let Some((a, _)) = ans { if a < t_max { t_max = a; } } if t_min > t_max { break; } match &self.nodes[x].data { &Data::A(l, r, dim, key) => { let dir = inv_direct[dim]; let t = (key - ry.origin[dim]) * dir; let (l, r) = if dir >= 0.0 { (l, r) } else { (r, l) }; // 考虑在划分的平面那里剪裁光线线段 if t <= t_min { x = r; } else if t >= t_max { x = l; } else { stk.push((r, t, t_max)); x = l; t_max = t; } } &Data::B(ref tri) => { for &i in tri.iter() { mesh.tri_intersect_and_update(i, ry, &mut ans); } break; } } } } return ans; } None } fn new_node(&mut self, p: &Vec<Vct>, tri: &mut Vec<(usize, usize, usize, usize)>) -> usize { macro_rules! free { ($w:expr) => { $w.clear(); $w.shrink_to_fit(); }; } let bbox = { let mut min = Vct::new(1e30, 1e30, 1e30); let mut max = Vct::new(-1e30, -1e30, -1e30); tri.iter().for_each(|&(a, b, c, _)| { min = min.min(p[a]).min(p[b]).min(p[c]); max = max.max(p[a]).max(p[b]).max(p[c]); }); BBox { min, max } }; if tri.len() <= K { self.nodes.push(Node { bbox, data: Data::B(tri.iter().map(|i| i.3).collect()) }); return self.nodes.len() - 1; } let min = |a: usize, b: usize, c: usize, d: usize| p[a][d].min(p[b][d].min(p[c][d])); let max = |a: usize, b: usize, c: usize, d: usize| p[a][d].max(p[b][d].max(p[c][d])); let dim = { let (mut var, mut avg) = ([0.0; 3], [0.0; 3]); tri.iter().for_each(|&(a, b, c, _)| { avg.iter_mut().enumerate().for_each(|(d, t)| *t += max(a, b, c, d)); }); avg.iter_mut().for_each(|a| *a /= tri.len() as Flt); tri.iter().for_each(|&(a, b, c, _)| { let f = |(d, t): (usize, &mut Flt)| *t += (max(a, b, c, d) - avg[d]).powi(2); var.iter_mut().enumerate().for_each(f); }); var.iter().enumerate().max_by(|x, y| x.1.partial_cmp(y.1).unwrap()).unwrap().0 }; tri.sort_by(|&(a, b, c, _), &(x, y, z, _)| { max(a, b, c, dim).partial_cmp(&max(x, y, z, dim)).unwrap() }); let mid = tri[tri.len() / 2]; let key = max(mid.0, mid.1, mid.2, dim); let (mut l, mut r) = (Vec::new(), Vec::new()); tri.iter().for_each(|&(a, b, c, i)| { if min(a, b, c, dim) < key { l.push((a, b, c, i)); } if max(a, b, c, dim) >= key { r.push((a, b, c, i)); } }); if l.len().max(r.len()) == tri.len() { self.nodes.push(Node { bbox, data: Data::B(tri.iter().map(|i| i.3).collect()) }); return self.nodes.len() - 1; } free!(tri); self.nodes.push(Node { bbox, data: Data::A(0, 0, dim, key) }); let ret = self.nodes.len() - 1; let lc = self.new_node(p, &mut l); free!(l); let rc = self.new_node(p, &mut r); free!(r); if let Data::A(ref mut x, ref mut y, _, _) = self.nodes[ret].data { *x = lc; *y = rc; } ret } pub fn build(&mut self, pos: &Vec<Vct>, tri: &Vec<(usize, usize, usize)>) { let mut tri: Vec<_> = tri.iter().enumerate().map(|(i, f)| (f.0, f.1, f.2, i)).collect(); self.new_node(pos, &mut tri); } pub fn hit(&self, r: &Ray, mesh: &Mesh) -> Option<HitTemp> { self._hit(r, mesh) } }
//! Syntax pub mod ast; pub mod codemap; pub mod parse; pub mod pp; use syntax::codemap::Spanned; /// A spanned error pub type Error = Spanned<Error_>; /// Syntax error #[derive(Clone, Copy, Debug)] pub enum Error_ { /// Only a single expression is expected per line. `(+ 1 2) 3` is an error ExpectedEndOfLine, /// ':' EmptyKeyword, /// `(+ 1 2]` IncorrectCloseDelimiter, /// The integer literal doesn't fit in 64 bits IntegerTooLarge, /// `(+ def! 1)` OperatorNotAllowedHere, /// `(+ 1 2` UnclosedDelimiter, /// `"\a"` UnknownCharacterEscape, /// No known token starts with this character UnknownStartOfToken, /// `"Hello` UnterminatedString, }
use crate::database::{Database, HasArguments, HasStatement, HasStatementCache, HasValueRef}; use crate::postgres::arguments::PgArgumentBuffer; use crate::postgres::value::{PgValue, PgValueRef}; use crate::postgres::{ PgArguments, PgColumn, PgConnection, PgQueryResult, PgRow, PgStatement, PgTransactionManager, PgTypeInfo, }; /// PostgreSQL database driver. #[derive(Debug)] pub struct Postgres; impl Database for Postgres { type Connection = PgConnection; type TransactionManager = PgTransactionManager; type Row = PgRow; type QueryResult = PgQueryResult; type Column = PgColumn; type TypeInfo = PgTypeInfo; type Value = PgValue; } impl<'r> HasValueRef<'r> for Postgres { type Database = Postgres; type ValueRef = PgValueRef<'r>; } impl HasArguments<'_> for Postgres { type Database = Postgres; type Arguments = PgArguments; type ArgumentBuffer = PgArgumentBuffer; } impl<'q> HasStatement<'q> for Postgres { type Database = Postgres; type Statement = PgStatement<'q>; } impl HasStatementCache for Postgres {}
use crossbeam::queue::SegQueue; use std::sync::atomic::AtomicBool; use std::sync::Arc; use crate::global::*; use crate::object::Point; use std::sync::atomic::Ordering::{Relaxed, SeqCst}; use crate::calculation::common_step::step; type Work = (usize, usize); type DataPtr = Arc<SharedData>; struct SharedData { queue: SegQueue<Work>, result: SegQueue<Vec<(f64, bool, usize)>>, grid: *const Vec<Point>, flag: AtomicBool } impl SharedData { fn start_apply(ptr: &Arc<Self>) { let mut t = Vec::new(); for _ in 0..*THREAD { let shared = ptr.clone(); t.push( std::thread::spawn(move || { loop { let work = shared.result.pop(); match work { Ok(e) => { for i in e { unsafe { let p = &*shared.grid; let mut p = p[i.2].temperature.borrow_mut(); *p = i.0; } } }, _ => { break; } } } })); } for i in t { i.join().unwrap(); } } } unsafe impl Send for SharedData {} unsafe impl Sync for SharedData {} fn initialize(grid: &Vec<Point>) -> DataPtr { let queue = SegQueue::new(); if *CHUNK == 0 { let mut counter: usize = 0; for i in 0..*THREAD { let _length = grid.len() - i; let length = if _length % *THREAD > 0 { _length / *THREAD + 1 } else { _length / *THREAD }; queue.push((counter, counter + length)); counter += length; } } else { let mut counter = 0; while counter + *CHUNK < grid.len() { queue.push((counter, counter + *CHUNK)); counter += *CHUNK; } if counter < grid.len() { queue.push((counter, grid.len())); } } Arc::new(SharedData { queue, grid: grid as *const _, flag: AtomicBool::new(true), result: SegQueue::new() }) } pub fn sor_go(grid: &Vec<Point>) -> bool { let shared = initialize(grid); let mut t = Vec::new(); for _ in 0..*THREAD { let shared = shared.clone(); t.push( std::thread::spawn(move || { loop { let work = shared.queue.pop(); match work { Ok((s, t)) => { unsafe { let grid = &*shared.grid; let mut w = grid[s].inner.x() as usize; let wt = grid[t - 1].inner.x() as usize; let mut h = grid[s].inner.y() as usize; let ht = grid[t - 1].inner.y() as usize; 'run: while w <= wt { if w & 1 != h & 1 { h += 1; } for h in (h..*HEIGHT).step_by(2) { if w > wt || w == wt && h > ht as usize { break 'run; } let i = w * *HEIGHT + h; let a = step(grid, i, true); shared.flag.fetch_and(a.1, SeqCst); let mut p = grid[i].temperature.borrow_mut(); *p = a.0; drop(p); } h = 0; w += 1; } } }, Err(_) => { break; } } } })); } for i in t { i.join().unwrap(); } let mut t = Vec::new(); let shared = initialize(grid); for _ in 0..*THREAD { let shared = shared.clone(); t.push( std::thread::spawn(move || { loop { let work = shared.queue.pop(); match work { Ok((s, t)) => { unsafe { let grid = &*shared.grid; let mut w = grid[s].inner.x() as usize; let wt = grid[t - 1].inner.x() as usize; let mut h = grid[s].inner.y() as usize; let ht = grid[t - 1].inner.y() as usize; 'run: while w <= wt { if w & 1 == h & 1 { h += 1; } for h in (h..*HEIGHT).step_by(2) { if w > wt || w == wt && h > ht as usize { break 'run; } let i : usize = w * *HEIGHT + h; let a = step(grid, i, true); shared.flag.fetch_and(a.1, SeqCst); let mut p = grid[i].temperature.borrow_mut(); *p = a.0; drop(p); } h = 0; w += 1; } } }, Err(_) => { break; } } } })); } for i in t { i.join().unwrap(); } shared.flag.load(Relaxed) } pub fn jacobi_go(grid: &Vec<Point>) -> bool { let shared = initialize(grid); let mut t = Vec::new(); for _ in 0..*THREAD { let shared = shared.clone(); t.push( std::thread::spawn(move || { loop { let work = shared.queue.pop(); match work { Ok((s, t)) => { let mut update = Vec::new(); for i in s..t { let step : (f64, bool, usize) = unsafe { super::super::common_step::step(&*shared.grid, i, false) }; update.push(step); shared.flag.fetch_and(step.1, SeqCst); } shared.result.push(update); }, Err(_) => { break; } } } })); } for i in t { i.join().unwrap(); } SharedData::start_apply(&shared); shared.flag.load(Relaxed) }
#[cfg(test)] mod test { use crate::data_structures::directed_graph::DirectedGraph; #[test] fn straight_line() { let mut foo = DirectedGraph::with_nodes(4); foo.add_edge(0, 1, 1); foo.add_edge(1, 2, 1); foo.add_edge(2, 3, 1); assert_eq!(foo.distance(0, 1), 1); assert_eq!(foo.distance(0, 2), 2); assert_eq!(foo.distance(0, 3), 3); } #[test] fn diamond() { let mut foo = DirectedGraph::with_nodes(4); foo.add_edge(0, 1, 2); foo.add_edge(1, 2, 2); foo.add_edge(0, 2, 1); foo.add_edge(2, 3, 1); assert_eq!(foo.distance(0, 3), 2); } #[test] fn cycle() { let mut foo = DirectedGraph::with_nodes(4); foo.add_edge(0, 2, 5); foo.add_edge(1, 0, 1); foo.add_edge(2, 1, 1); foo.add_edge(2, 3, 1); assert_eq!(foo.distance(0, 3), 6); } #[test] fn bigger() { let mut foo = DirectedGraph::with_nodes(8); foo.add_edge(0, 1, 1); foo.add_edge(1, 2, 1); foo.add_edge(1, 3, 3); foo.add_edge(3, 5, 2); foo.add_edge(5, 4, 1); foo.add_edge(4, 1, 5); foo.add_edge(2, 3, 2); foo.add_edge(3, 6, 1); foo.add_edge(2, 6, 2); foo.add_edge(2, 7, 6); foo.add_edge(6, 7, 1); foo.add_edge(4, 3, 2); foo.add_edge(3, 7, 3); assert_eq!(foo.distance(0, 7), 5); assert_eq!(foo.distance(5, 7), 5); } }
use super::*; pub enum ConstantValue { Bool(bool), U8(u8), I8(i8), U16(u16), I16(i16), U32(u32), I32(i32), U64(u64), I64(i64), F32(f32), F64(f64), String(String), TypeDef(TypeDef), } impl ConstantValue { pub fn unwrap_u32(&self) -> u32 { match self { Self::U32(value) => *value, _ => unimplemented!(), } } pub fn unwrap_u16(&self) -> u16 { match self { Self::U16(value) => *value, _ => unimplemented!(), } } pub fn unwrap_u8(&self) -> u8 { match self { Self::U8(value) => *value, _ => unimplemented!(), } } pub fn unwrap_string(&self) -> &str { match self { Self::String(value) => value, _ => unimplemented!(), } } pub fn next(&self) -> Self { match self { Self::U32(value) => Self::U32(value + 1), Self::I32(value) => Self::I32(value + 1), _ => unimplemented!(), } } }
extern crate random_access_disk as rad; extern crate random_access_storage; extern crate tempfile; use random_access_storage::RandomAccess; use tempfile::Builder; #[test] fn can_call_new() { let dir = Builder::new() .prefix("random-access-disk") .tempdir() .unwrap(); let _file = rad::RandomAccessDisk::open(dir.path().join("1.db")).unwrap(); } #[test] fn can_open_buffer() { let dir = Builder::new() .prefix("random-access-disk") .tempdir() .unwrap(); let mut file = rad::RandomAccessDisk::open(dir.path().join("2.db")).unwrap(); file.write(0, b"hello").unwrap(); } #[test] fn can_write() { let dir = Builder::new() .prefix("random-access-disk") .tempdir() .unwrap(); let mut file = rad::RandomAccessDisk::open(dir.path().join("3.db")).unwrap(); file.write(0, b"hello").unwrap(); file.write(5, b" world").unwrap(); } #[test] fn can_read() { let dir = Builder::new() .prefix("random-access-disk") .tempdir() .unwrap(); let mut file = rad::RandomAccessDisk::open(dir.path().join("4.db")).unwrap(); file.write(0, b"hello").unwrap(); file.write(5, b" world").unwrap(); let text = file.read(0, 11).unwrap(); assert_eq!(String::from_utf8(text.to_vec()).unwrap(), "hello world"); }
#[doc = "Reader of register MDIOS_DINR2"] pub type R = crate::R<u32, super::MDIOS_DINR2>; #[doc = "Reader of field `DIN2`"] pub type DIN2_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - Input data received from MDIO Master during write frames"] #[inline(always)] pub fn din2(&self) -> DIN2_R { DIN2_R::new((self.bits & 0xffff) as u16) } }
use crate::{ marker_type::{ErasedObject, NonOwningPhantom}, sabi_types::{RMut, RRef}, std_types::{RNone, ROption, RSome, RVec, Tuple2}, traits::IntoReprC, utils::Transmuter, }; /////////////////////////////////////////////////////////////////////////////////// #[repr(C)] #[derive(StableAbi)] pub struct IteratorFns<Item> { pub(super) next: unsafe extern "C" fn(RMut<'_, ErasedObject>) -> ROption<Item>, pub(super) extending_rvec: unsafe extern "C" fn(RMut<'_, ErasedObject>, &mut RVec<Item>, ROption<usize>), pub(super) size_hint: unsafe extern "C" fn(RRef<'_, ErasedObject>) -> Tuple2<usize, ROption<usize>>, pub(super) count: unsafe extern "C" fn(RMut<'_, ErasedObject>) -> usize, pub(super) last: unsafe extern "C" fn(RMut<'_, ErasedObject>) -> ROption<Item>, pub(super) nth: unsafe extern "C" fn(RMut<'_, ErasedObject>, usize) -> ROption<Item>, pub(super) skip_eager: unsafe extern "C" fn(RMut<'_, ErasedObject>, usize), } impl<Item> Copy for IteratorFns<Item> {} impl<Item> Clone for IteratorFns<Item> { fn clone(&self) -> Self { *self } } /////////////////////////////////////////////////////////////////////////////////// pub struct MakeIteratorFns<I>(NonOwningPhantom<I>); impl<I> MakeIteratorFns<I> where I: Iterator, { const ITER: IteratorFns<I::Item> = IteratorFns { next: next::<I>, extending_rvec: extending_rvec::<I>, size_hint: size_hint::<I>, count: count::<I>, last: last::<I>, nth: nth::<I>, skip_eager: skip_eager::<I>, }; pub(super) const NEW: IteratorFns<()> = unsafe { Transmuter { from: Self::ITER }.to }; } /////////////////////////////////////////////////////////////////////////////////// pub(super) unsafe extern "C" fn next<I>(this: RMut<'_, ErasedObject>) -> ROption<I::Item> where I: Iterator, { extern_fn_panic_handling! {no_early_return; let this = unsafe { this.transmute_into_mut::<I>() }; this.next().into_c() } } pub(super) unsafe extern "C" fn extending_rvec<I>( this: RMut<'_, ErasedObject>, vec: &mut RVec<I::Item>, taking: ROption<usize>, ) where I: Iterator, { extern_fn_panic_handling! {no_early_return; let this = unsafe { this.transmute_into_mut::<I>() }; vec.extend( this.take(taking.unwrap_or(!0)) ); } } pub(super) unsafe extern "C" fn size_hint<I>( this: RRef<'_, ErasedObject>, ) -> Tuple2<usize, ROption<usize>> where I: Iterator, { extern_fn_panic_handling! {no_early_return; let this = unsafe { this.transmute_into_ref::<I>() }; let (l,r)=this.size_hint(); Tuple2(l,r.into_c()) } } pub(super) unsafe extern "C" fn count<I>(this: RMut<'_, ErasedObject>) -> usize where I: Iterator, { extern_fn_panic_handling! {no_early_return; let this = unsafe { this.transmute_into_mut::<I>() }; this.count() } } pub(super) unsafe extern "C" fn last<I>(this: RMut<'_, ErasedObject>) -> ROption<I::Item> where I: Iterator, { extern_fn_panic_handling! {no_early_return; let this = unsafe { this.transmute_into_mut::<I>() }; this.last().into_c() } } pub(super) unsafe extern "C" fn nth<I>(this: RMut<'_, ErasedObject>, at: usize) -> ROption<I::Item> where I: Iterator, { extern_fn_panic_handling! {no_early_return; let this = unsafe { this.transmute_into_mut::<I>() }; this.nth(at).into_c() } } pub(super) unsafe extern "C" fn skip_eager<I>(this: RMut<'_, ErasedObject>, skipping: usize) where I: Iterator, { extern_fn_panic_handling! {no_early_return; let this = unsafe { this.transmute_into_mut::<I>() }; if skipping!=0 { let _=this.nth(skipping-1); } } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #[repr(C)] #[derive(StableAbi)] pub struct DoubleEndedIteratorFns<Item> { pub(super) next_back: unsafe extern "C" fn(RMut<'_, ErasedObject>) -> ROption<Item>, pub(super) extending_rvec_back: unsafe extern "C" fn(RMut<'_, ErasedObject>, &mut RVec<Item>, ROption<usize>), pub(super) nth_back: unsafe extern "C" fn(RMut<'_, ErasedObject>, usize) -> ROption<Item>, } impl<Item> Copy for DoubleEndedIteratorFns<Item> {} impl<Item> Clone for DoubleEndedIteratorFns<Item> { fn clone(&self) -> Self { *self } } /////////////////////////////////////////////////////////////////////////////////// pub struct MakeDoubleEndedIteratorFns<I>(NonOwningPhantom<I>); impl<I> MakeDoubleEndedIteratorFns<I> where I: DoubleEndedIterator, { pub(super) const ITER: DoubleEndedIteratorFns<I::Item> = DoubleEndedIteratorFns { next_back: next_back::<I>, extending_rvec_back: extending_rvec_back::<I>, nth_back: nth_back::<I>, }; pub(super) const NEW: DoubleEndedIteratorFns<()> = unsafe { Transmuter { from: Self::ITER }.to }; } /////////////////////////////////////////////////////////////////////////////////// pub(super) unsafe extern "C" fn next_back<I>(this: RMut<'_, ErasedObject>) -> ROption<I::Item> where I: DoubleEndedIterator, { extern_fn_panic_handling! {no_early_return; let this = unsafe { this.transmute_into_mut::<I>() }; this.next_back().into_c() } } pub(super) unsafe extern "C" fn extending_rvec_back<I>( this: RMut<'_, ErasedObject>, vec: &mut RVec<I::Item>, taking: ROption<usize>, ) where I: DoubleEndedIterator, { extern_fn_panic_handling! {no_early_return; let this = unsafe { this.transmute_into_mut::<I>() }; vec.extend( this.rev().take(taking.unwrap_or(!0)) ); } } pub(super) unsafe extern "C" fn nth_back<I>( this: RMut<'_, ErasedObject>, mut at: usize, ) -> ROption<I::Item> where I: DoubleEndedIterator, { extern_fn_panic_handling! { // returns early let this = unsafe { this.transmute_into_mut::<I>() }; for x in this.rev() { if at == 0 { return RSome(x) } at -= 1; } RNone } }
//! Binary clauses. use partial_ref::{partial, PartialRef}; use varisat_formula::Lit; use varisat_internal_proof::{DeleteClauseProof, ProofStep}; use crate::{ context::{parts::*, Context}, proof, }; /// Binary clauses. #[derive(Default)] pub struct BinaryClauses { by_lit: Vec<Vec<Lit>>, count: usize, } impl BinaryClauses { /// Update structures for a new variable count. pub fn set_var_count(&mut self, count: usize) { self.by_lit.resize(count * 2, vec![]); } /// Add a binary clause. pub fn add_binary_clause(&mut self, lits: [Lit; 2]) { for i in 0..2 { self.by_lit[(!lits[i]).code()].push(lits[i ^ 1]); } self.count += 1; } /// Implications of a given literal pub fn implied(&self, lit: Lit) -> &[Lit] { &self.by_lit[lit.code()] } /// Number of binary clauses. pub fn count(&self) -> usize { self.count } } /// Remove binary clauses that have an assigned literal. pub fn simplify_binary<'a>( mut ctx: partial!(Context<'a>, mut BinaryClausesP, mut ProofP<'a>, mut SolverStateP, AssignmentP, VariablesP), ) { let (binary_clauses, mut ctx) = ctx.split_part_mut(BinaryClausesP); let (assignment, mut ctx) = ctx.split_part(AssignmentP); let mut double_count = 0; for (code, implied) in binary_clauses.by_lit.iter_mut().enumerate() { let lit = Lit::from_code(code); if !assignment.lit_is_unk(lit) { if ctx.part(ProofP).is_active() { for &other_lit in implied.iter() { // This check avoids deleting binary clauses twice if both literals are assigned. if (!lit) < other_lit { let lits = [!lit, other_lit]; proof::add_step( ctx.borrow(), true, &ProofStep::DeleteClause { clause: &lits[..], proof: DeleteClauseProof::Satisfied, }, ); } } } implied.clear(); } else { implied.retain(|&other_lit| { let retain = assignment.lit_is_unk(other_lit); // This check avoids deleting binary clauses twice if both literals are assigned. if ctx.part(ProofP).is_active() && !retain && (!lit) < other_lit { let lits = [!lit, other_lit]; proof::add_step( ctx.borrow(), true, &ProofStep::DeleteClause { clause: &lits[..], proof: DeleteClauseProof::Satisfied, }, ); } retain }); double_count += implied.len(); } } binary_clauses.count = double_count / 2; }
use super::icon; use std::fs::File; use std::path::Path; use std::path::PathBuf; #[test] fn load_dmi() { let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); path.push("tests/load_test.dmi"); let path = Path::new(&path); let file = File::open(&path).unwrap_or_else(|_| panic!("No lights dmi: {:?}", path)); let _lights_icon = icon::Icon::load(&file).expect("Unable to load lights dmi"); }
use std::{ future::Future, pin::Pin, task::{Context, Poll}, time::Duration, }; use futures_core::ready; use pin_project_lite::pin_project; use tokio::sync::oneshot; use crate::{ actor::Actor, clock::{sleep, Sleep}, fut::{ActorFuture, ActorStream}, }; #[deprecated( since = "0.11.0", note = "Please use tokio::sync::oneshot::Sender instead." )] pub struct Condition<T> where T: Clone, { waiters: Vec<oneshot::Sender<T>>, } #[allow(deprecated)] impl<T> Condition<T> where T: Clone, { pub fn wait(&mut self) -> oneshot::Receiver<T> { let (tx, rx) = oneshot::channel(); self.waiters.push(tx); rx } pub fn set(self, result: T) { for waiter in self.waiters { let _ = waiter.send(result.clone()); } } } #[allow(deprecated)] impl<T> Default for Condition<T> where T: Clone, { fn default() -> Self { Condition { waiters: Vec::new(), } } } pin_project! { /// An `ActorFuture` that runs a function in the actor's context after a specified amount of time. /// /// Unless you specifically need access to the future, use [`Context::run_later`] instead. /// /// [`Context::run_later`]: ../prelude/trait.AsyncContext.html#method.run_later /// /// ``` /// # use std::io; /// use std::time::Duration; /// use actix::prelude::*; /// use actix::utils::TimerFunc; /// /// struct MyActor; /// /// impl MyActor { /// fn stop(&mut self, context: &mut Context<Self>) { /// System::current().stop(); /// } /// } /// /// impl Actor for MyActor { /// type Context = Context<Self>; /// /// fn started(&mut self, context: &mut Context<Self>) { /// // spawn a delayed future into our context /// TimerFunc::new(Duration::from_millis(100), Self::stop) /// .spawn(context); /// } /// } /// # fn main() { /// # let mut sys = System::new(); /// # let addr = sys.block_on(async { MyActor.start() }); /// # sys.run(); /// # } #[must_use = "future do nothing unless polled"] #[allow(clippy::type_complexity)] pub struct TimerFunc<A: Actor> { f: Option<Box<dyn FnOnce(&mut A, &mut A::Context)>>, #[pin] timeout: Sleep, } } impl<A: Actor> TimerFunc<A> { /// Creates a new `TimerFunc` with the given duration. pub fn new<F>(timeout: Duration, f: F) -> TimerFunc<A> where F: FnOnce(&mut A, &mut A::Context) + 'static, { TimerFunc { f: Some(Box::new(f)), timeout: sleep(timeout), } } } impl<A> ActorFuture<A> for TimerFunc<A> where A: Actor, { type Output = (); fn poll( self: Pin<&mut Self>, act: &mut A, ctx: &mut A::Context, task: &mut Context<'_>, ) -> Poll<Self::Output> { let this = self.project(); ready!(this.timeout.poll(task)); let f = this.f.take().expect("TimerFunc polled after finish"); f(act, ctx); Poll::Ready(()) } } pin_project! { /// An `ActorStream` that periodically runs a function in the actor's context. /// /// Unless you specifically need access to the future, use [`Context::run_interval`] instead. /// /// [`Context::run_interval`]: ../prelude/trait.AsyncContext.html#method.run_interval /// /// ``` /// # use std::io; /// use std::time::Duration; /// use actix::prelude::*; /// use actix::utils::IntervalFunc; /// /// struct MyActor; /// /// impl MyActor { /// fn tick(&mut self, context: &mut Context<Self>) { /// println!("tick"); /// } /// } /// /// impl Actor for MyActor { /// type Context = Context<Self>; /// /// fn started(&mut self, context: &mut Context<Self>) { /// // spawn an interval stream into our context /// IntervalFunc::new(Duration::from_millis(100), Self::tick) /// .finish() /// .spawn(context); /// # context.run_later(Duration::from_millis(200), |_, _| System::current().stop()); /// } /// } /// # fn main() { /// # let mut sys = System::new(); /// # let addr = sys.block_on(async { MyActor.start() }); /// # sys.run(); /// # } /// ``` #[must_use = "future do nothing unless polled"] #[allow(clippy::type_complexity)] pub struct IntervalFunc<A: Actor> { f: Box<dyn FnMut(&mut A, &mut A::Context)>, dur: Duration, #[pin] timer: Sleep, } } impl<A: Actor> IntervalFunc<A> { /// Creates a new `IntervalFunc` with the given interval duration. pub fn new<F>(dur: Duration, f: F) -> IntervalFunc<A> where F: FnMut(&mut A, &mut A::Context) + 'static, { Self { f: Box::new(f), dur, timer: sleep(dur), } } } impl<A: Actor> ActorStream<A> for IntervalFunc<A> { type Item = (); fn poll_next( self: Pin<&mut Self>, act: &mut A, ctx: &mut A::Context, task: &mut Context<'_>, ) -> Poll<Option<Self::Item>> { let mut this = self.project(); loop { ready!(this.timer.as_mut().poll(task)); let now = this.timer.deadline(); this.timer.as_mut().reset(now + *this.dur); (this.f)(act, ctx); } } }
use proconio::input; fn main() { input! { n: usize, x: [usize; n], c: [u64; n], }; let mut seen = vec![false; n]; let mut ans = 0; for v in 0..n { if seen[v] { continue; } let mut route = Vec::new(); let mut v = v; while !seen[v] { seen[v] = true; route.push(v); v = x[v] - 1; } if let Some(p) = route.iter().position(|&u| u == v) { let min = &route[p..].iter().map(|&u| c[u]).min().unwrap(); ans += min; } } println!("{}", ans); }
//mod system_stat; // mod regex_trials; mod mover; fn main() { // system_stat::system_stat(); // regex_trials::regex_em(); mover::mover(); }
// Should display error about no main. mod no_main_mod; // Not sure why no-trans doesn't handle this properly. // end-msg: ERR(check) main function not found // end-msg: NOTE(check) the main function must be defined // end-msg: MSG(check) Note: no_main_mod.rs:1
//! Linux auxv support. //! //! # Safety //! //! This uses raw pointers to locate and read the kernel-provided auxv array. #![allow(unsafe_code)] use crate::backend::c; use crate::backend::elf::*; use crate::fd::OwnedFd; #[cfg(feature = "param")] use crate::ffi::CStr; use crate::fs::{Mode, OFlags}; use crate::utils::{as_ptr, check_raw_pointer}; use alloc::vec::Vec; use core::ffi::c_void; use core::mem::size_of; use core::ptr::{null_mut, read_unaligned, NonNull}; #[cfg(feature = "runtime")] use core::slice; use core::sync::atomic::Ordering::Relaxed; use core::sync::atomic::{AtomicPtr, AtomicUsize}; use linux_raw_sys::general::{ AT_BASE, AT_CLKTCK, AT_EXECFN, AT_HWCAP, AT_HWCAP2, AT_NULL, AT_PAGESZ, AT_PHDR, AT_PHENT, AT_PHNUM, AT_SYSINFO_EHDR, }; #[cfg(feature = "param")] #[inline] pub(crate) fn page_size() -> usize { let mut page_size = PAGE_SIZE.load(Relaxed); if page_size == 0 { init_auxv(); page_size = PAGE_SIZE.load(Relaxed); } page_size } #[cfg(feature = "param")] #[inline] pub(crate) fn clock_ticks_per_second() -> u64 { let mut ticks = CLOCK_TICKS_PER_SECOND.load(Relaxed); if ticks == 0 { init_auxv(); ticks = CLOCK_TICKS_PER_SECOND.load(Relaxed); } ticks as u64 } #[cfg(feature = "param")] #[inline] pub(crate) fn linux_hwcap() -> (usize, usize) { let mut hwcap = HWCAP.load(Relaxed); let mut hwcap2 = HWCAP2.load(Relaxed); if hwcap == 0 || hwcap2 == 0 { init_auxv(); hwcap = HWCAP.load(Relaxed); hwcap2 = HWCAP2.load(Relaxed); } (hwcap, hwcap2) } #[cfg(feature = "param")] #[inline] pub(crate) fn linux_execfn() -> &'static CStr { let mut execfn = EXECFN.load(Relaxed); if execfn.is_null() { init_auxv(); execfn = EXECFN.load(Relaxed); } // SAFETY: We assume the `AT_EXECFN` value provided by the kernel is a // valid pointer to a valid NUL-terminated array of bytes. unsafe { CStr::from_ptr(execfn.cast()) } } #[cfg(feature = "runtime")] #[inline] pub(crate) fn exe_phdrs() -> (*const c::c_void, usize) { let mut phdr = PHDR.load(Relaxed); let mut phnum = PHNUM.load(Relaxed); if phdr.is_null() || phnum == 0 { init_auxv(); phdr = PHDR.load(Relaxed); phnum = PHNUM.load(Relaxed); } (phdr.cast(), phnum) } #[cfg(feature = "runtime")] #[inline] pub(in super::super) fn exe_phdrs_slice() -> &'static [Elf_Phdr] { let (phdr, phnum) = exe_phdrs(); // SAFETY: We assume the `AT_PHDR` and `AT_PHNUM` values provided by the // kernel form a valid slice. unsafe { slice::from_raw_parts(phdr.cast(), phnum) } } /// `AT_SYSINFO_EHDR` isn't present on all platforms in all configurations, /// so if we don't see it, this function returns a null pointer. #[inline] pub(in super::super) fn sysinfo_ehdr() -> *const Elf_Ehdr { let mut ehdr = SYSINFO_EHDR.load(Relaxed); if ehdr.is_null() { init_auxv(); ehdr = SYSINFO_EHDR.load(Relaxed); } ehdr } static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0); static CLOCK_TICKS_PER_SECOND: AtomicUsize = AtomicUsize::new(0); static HWCAP: AtomicUsize = AtomicUsize::new(0); static HWCAP2: AtomicUsize = AtomicUsize::new(0); static SYSINFO_EHDR: AtomicPtr<Elf_Ehdr> = AtomicPtr::new(null_mut()); static PHDR: AtomicPtr<Elf_Phdr> = AtomicPtr::new(null_mut()); static PHNUM: AtomicUsize = AtomicUsize::new(0); static EXECFN: AtomicPtr<c::c_char> = AtomicPtr::new(null_mut()); fn pr_get_auxv() -> crate::io::Result<Vec<u8>> { use super::super::conv::{c_int, pass_usize, ret_usize}; const PR_GET_AUXV: c::c_int = 0x41555856; let mut buffer = alloc::vec![0u8; 512]; let len = unsafe { ret_usize(syscall_always_asm!( __NR_prctl, c_int(PR_GET_AUXV), buffer.as_ptr(), pass_usize(buffer.len()) ))? }; if len <= buffer.len() { buffer.truncate(len); return Ok(buffer); } buffer.resize(len, 0); let len = unsafe { ret_usize(syscall_always_asm!( __NR_prctl, c_int(PR_GET_AUXV), buffer.as_ptr(), pass_usize(buffer.len()) ))? }; assert_eq!(len, buffer.len()); return Ok(buffer); } /// On non-Mustang platforms, we read the aux vector via the `prctl` /// `PR_GET_AUXV`, with a fallback to /proc/self/auxv for kernels that don't /// support `PR_GET_AUXV`. #[cold] fn init_auxv() { match pr_get_auxv() { Ok(buffer) => { // SAFETY: We assume the kernel returns a valid auxv. unsafe { init_from_auxp(buffer.as_ptr().cast()); } return; } Err(_) => { // Fall back to /proc/self/auxv on error. } } // Open "/proc/self/auxv", either because we trust "/proc", or because // we're running inside QEMU and `proc_self_auxv`'s extra checking foils // QEMU's emulation so we need to do a plain open to get the right // auxv records. let file = crate::fs::open("/proc/self/auxv", OFlags::RDONLY, Mode::empty()).unwrap(); let _ = init_from_auxv_file(file); } /// Process auxv entries from the open file `auxv`. #[cold] fn init_from_auxv_file(auxv: OwnedFd) -> Option<()> { let mut buffer = Vec::<u8>::with_capacity(512); loop { let cur = buffer.len(); // Request one extra byte; `Vec` will often allocate more. buffer.reserve(1); // Use all the space it allocated. buffer.resize(buffer.capacity(), 0); // Read up to that many bytes. let n = match crate::io::read(&auxv, &mut buffer[cur..]) { Err(crate::io::Errno::INTR) => 0, Err(_err) => panic!(), Ok(0) => break, Ok(n) => n, }; // Account for the number of bytes actually read. buffer.resize(cur + n, 0_u8); } // SAFETY: We loaded from an auxv file into the buffer. unsafe { init_from_auxp(buffer.as_ptr().cast()) } } /// Process auxv entries from the auxv array pointed to by `auxp`. /// /// # Safety /// /// This must be passed a pointer to an auxv array. /// /// The buffer contains `Elf_aux_t` elements, though it need not be aligned; /// function uses `read_unaligned` to read from it. #[cold] unsafe fn init_from_auxp(mut auxp: *const Elf_auxv_t) -> Option<()> { let mut pagesz = 0; let mut clktck = 0; let mut hwcap = 0; let mut hwcap2 = 0; let mut phdr = null_mut(); let mut phnum = 0; let mut execfn = null_mut(); let mut sysinfo_ehdr = null_mut(); let mut phent = 0; loop { let Elf_auxv_t { a_type, a_val } = read_unaligned(auxp); match a_type as _ { AT_PAGESZ => pagesz = a_val as usize, AT_CLKTCK => clktck = a_val as usize, AT_HWCAP => hwcap = a_val as usize, AT_HWCAP2 => hwcap2 = a_val as usize, AT_PHDR => phdr = check_raw_pointer::<Elf_Phdr>(a_val as *mut _)?.as_ptr(), AT_PHNUM => phnum = a_val as usize, AT_PHENT => phent = a_val as usize, AT_EXECFN => execfn = check_raw_pointer::<c::c_char>(a_val as *mut _)?.as_ptr(), AT_BASE => check_interpreter_base(a_val.cast())?, AT_SYSINFO_EHDR => sysinfo_ehdr = check_vdso_base(a_val as *mut _)?.as_ptr(), AT_NULL => break, _ => (), } auxp = auxp.add(1); } assert_eq!(phent, size_of::<Elf_Phdr>()); // The base and sysinfo_ehdr (if present) matches our platform. Accept // the aux values. PAGE_SIZE.store(pagesz, Relaxed); CLOCK_TICKS_PER_SECOND.store(clktck, Relaxed); HWCAP.store(hwcap, Relaxed); HWCAP2.store(hwcap2, Relaxed); PHDR.store(phdr, Relaxed); PHNUM.store(phnum, Relaxed); EXECFN.store(execfn, Relaxed); SYSINFO_EHDR.store(sysinfo_ehdr, Relaxed); Some(()) } /// Check that `base` is a valid pointer to the program interpreter. /// /// `base` is some value we got from a `AT_BASE` aux record somewhere, /// which hopefully holds the value of the program interpreter in memory. Do a /// series of checks to be as sure as we can that it's safe to use. #[cold] unsafe fn check_interpreter_base(base: *const Elf_Ehdr) -> Option<()> { check_elf_base(base)?; Some(()) } /// Check that `base` is a valid pointer to the kernel-provided vDSO. /// /// `base` is some value we got from a `AT_SYSINFO_EHDR` aux record somewhere, /// which hopefully holds the value of the kernel-provided vDSO in memory. Do a /// series of checks to be as sure as we can that it's safe to use. #[cold] unsafe fn check_vdso_base(base: *const Elf_Ehdr) -> Option<NonNull<Elf_Ehdr>> { // In theory, we could check that we're not attempting to parse our own ELF // image, as an additional check. However, older Linux toolchains don't // support this, and Rust's `#[linkage = "extern_weak"]` isn't stable yet, // so just disable this for now. /* { extern "C" { static __ehdr_start: c::c_void; } let ehdr_start: *const c::c_void = &__ehdr_start; if base == ehdr_start { return None; } } */ let hdr = check_elf_base(base)?; // Check that the ELF is not writable, since that would indicate that this // isn't the ELF we think it is. Here we're just using `clock_getres` just // as an arbitrary system call which writes to a buffer and fails with // `EFAULT` if the buffer is not writable. { use crate::backend::conv::{c_uint, ret}; if ret(syscall!( __NR_clock_getres, c_uint(linux_raw_sys::general::CLOCK_MONOTONIC), base )) != Err(crate::io::Errno::FAULT) { // We can't gracefully fail here because we would seem to have just // mutated some unknown memory. #[cfg(feature = "std")] { std::process::abort(); } #[cfg(all(not(feature = "std"), feature = "rustc-dep-of-std"))] { core::intrinsics::abort(); } } } Some(hdr) } /// Check that `base` is a valid pointer to an ELF image. #[cold] unsafe fn check_elf_base(base: *const Elf_Ehdr) -> Option<NonNull<Elf_Ehdr>> { // If we're reading a 64-bit auxv on a 32-bit platform, we'll see // a zero `a_val` because `AT_*` values are never greater than // `u32::MAX`. Zero is used by libc's `getauxval` to indicate // errors, so it should never be a valid value. if base.is_null() { return None; } let hdr = match check_raw_pointer::<Elf_Ehdr>(base as *mut _) { Some(hdr) => hdr, None => return None, }; let hdr = hdr.as_ref(); if hdr.e_ident[..SELFMAG] != ELFMAG { return None; // Wrong ELF magic } if !matches!(hdr.e_ident[EI_OSABI], ELFOSABI_SYSV | ELFOSABI_LINUX) { return None; // Unrecognized ELF OS ABI } if hdr.e_ident[EI_ABIVERSION] != ELFABIVERSION { return None; // Unrecognized ELF ABI version } if hdr.e_type != ET_DYN { return None; // Wrong ELF type } // If ELF is extended, we'll need to adjust. if hdr.e_ident[EI_VERSION] != EV_CURRENT || hdr.e_ehsize as usize != size_of::<Elf_Ehdr>() || hdr.e_phentsize as usize != size_of::<Elf_Phdr>() { return None; } // We don't currently support extra-large numbers of segments. if hdr.e_phnum == PN_XNUM { return None; } // If `e_phoff` is zero, it's more likely that we're looking at memory that // has been zeroed than that the kernel has somehow aliased the `Ehdr` and // the `Phdr`. if hdr.e_phoff < size_of::<Elf_Ehdr>() { return None; } // Verify that the `EI_CLASS`/`EI_DATA`/`e_machine` fields match the // architecture we're running as. This helps catch cases where we're // running under QEMU. if hdr.e_ident[EI_CLASS] != ELFCLASS { return None; // Wrong ELF class } if hdr.e_ident[EI_DATA] != ELFDATA { return None; // Wrong ELF data } if hdr.e_machine != EM_CURRENT { return None; // Wrong machine type } Some(NonNull::new_unchecked(as_ptr(hdr) as *mut _)) } // ELF ABI #[repr(C)] #[derive(Copy, Clone)] struct Elf_auxv_t { a_type: usize, // Some of the values in the auxv array are pointers, so we make `a_val` a // pointer, in order to preserve their provenance. For the values which are // integers, we cast this to `usize`. a_val: *const c_void, }
#[doc = "Reader of register MPCBB1_VCTR49"] pub type R = crate::R<u32, super::MPCBB1_VCTR49>; #[doc = "Writer for register MPCBB1_VCTR49"] pub type W = crate::W<u32, super::MPCBB1_VCTR49>; #[doc = "Register MPCBB1_VCTR49 `reset()`'s with value 0"] impl crate::ResetValue for super::MPCBB1_VCTR49 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `B1568`"] pub type B1568_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1568`"] pub struct B1568_W<'a> { w: &'a mut W, } impl<'a> B1568_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `B1569`"] pub type B1569_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1569`"] pub struct B1569_W<'a> { w: &'a mut W, } impl<'a> B1569_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `B1570`"] pub type B1570_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1570`"] pub struct B1570_W<'a> { w: &'a mut W, } impl<'a> B1570_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `B1571`"] pub type B1571_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1571`"] pub struct B1571_W<'a> { w: &'a mut W, } impl<'a> B1571_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `B1572`"] pub type B1572_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1572`"] pub struct B1572_W<'a> { w: &'a mut W, } impl<'a> B1572_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `B1573`"] pub type B1573_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1573`"] pub struct B1573_W<'a> { w: &'a mut W, } impl<'a> B1573_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `B1574`"] pub type B1574_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1574`"] pub struct B1574_W<'a> { w: &'a mut W, } impl<'a> B1574_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `B1575`"] pub type B1575_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1575`"] pub struct B1575_W<'a> { w: &'a mut W, } impl<'a> B1575_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `B1576`"] pub type B1576_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1576`"] pub struct B1576_W<'a> { w: &'a mut W, } impl<'a> B1576_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `B1577`"] pub type B1577_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1577`"] pub struct B1577_W<'a> { w: &'a mut W, } impl<'a> B1577_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `B1578`"] pub type B1578_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1578`"] pub struct B1578_W<'a> { w: &'a mut W, } impl<'a> B1578_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `B1579`"] pub type B1579_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1579`"] pub struct B1579_W<'a> { w: &'a mut W, } impl<'a> B1579_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `B1580`"] pub type B1580_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1580`"] pub struct B1580_W<'a> { w: &'a mut W, } impl<'a> B1580_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 `B1581`"] pub type B1581_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1581`"] pub struct B1581_W<'a> { w: &'a mut W, } impl<'a> B1581_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `B1582`"] pub type B1582_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1582`"] pub struct B1582_W<'a> { w: &'a mut W, } impl<'a> B1582_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `B1583`"] pub type B1583_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1583`"] pub struct B1583_W<'a> { w: &'a mut W, } impl<'a> B1583_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `B1584`"] pub type B1584_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1584`"] pub struct B1584_W<'a> { w: &'a mut W, } impl<'a> B1584_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 `B1585`"] pub type B1585_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1585`"] pub struct B1585_W<'a> { w: &'a mut W, } impl<'a> B1585_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 `B1586`"] pub type B1586_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1586`"] pub struct B1586_W<'a> { w: &'a mut W, } impl<'a> B1586_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 `B1587`"] pub type B1587_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1587`"] pub struct B1587_W<'a> { w: &'a mut W, } impl<'a> B1587_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 `B1588`"] pub type B1588_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1588`"] pub struct B1588_W<'a> { w: &'a mut W, } impl<'a> B1588_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `B1589`"] pub type B1589_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1589`"] pub struct B1589_W<'a> { w: &'a mut W, } impl<'a> B1589_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `B1590`"] pub type B1590_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1590`"] pub struct B1590_W<'a> { w: &'a mut W, } impl<'a> B1590_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `B1591`"] pub type B1591_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1591`"] pub struct B1591_W<'a> { w: &'a mut W, } impl<'a> B1591_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `B1592`"] pub type B1592_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1592`"] pub struct B1592_W<'a> { w: &'a mut W, } impl<'a> B1592_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `B1593`"] pub type B1593_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1593`"] pub struct B1593_W<'a> { w: &'a mut W, } impl<'a> B1593_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `B1594`"] pub type B1594_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1594`"] pub struct B1594_W<'a> { w: &'a mut W, } impl<'a> B1594_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `B1595`"] pub type B1595_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1595`"] pub struct B1595_W<'a> { w: &'a mut W, } impl<'a> B1595_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `B1596`"] pub type B1596_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1596`"] pub struct B1596_W<'a> { w: &'a mut W, } impl<'a> B1596_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `B1597`"] pub type B1597_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1597`"] pub struct B1597_W<'a> { w: &'a mut W, } impl<'a> B1597_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `B1598`"] pub type B1598_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1598`"] pub struct B1598_W<'a> { w: &'a mut W, } impl<'a> B1598_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `B1599`"] pub type B1599_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1599`"] pub struct B1599_W<'a> { w: &'a mut W, } impl<'a> B1599_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - B1568"] #[inline(always)] pub fn b1568(&self) -> B1568_R { B1568_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - B1569"] #[inline(always)] pub fn b1569(&self) -> B1569_R { B1569_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - B1570"] #[inline(always)] pub fn b1570(&self) -> B1570_R { B1570_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - B1571"] #[inline(always)] pub fn b1571(&self) -> B1571_R { B1571_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - B1572"] #[inline(always)] pub fn b1572(&self) -> B1572_R { B1572_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - B1573"] #[inline(always)] pub fn b1573(&self) -> B1573_R { B1573_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - B1574"] #[inline(always)] pub fn b1574(&self) -> B1574_R { B1574_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - B1575"] #[inline(always)] pub fn b1575(&self) -> B1575_R { B1575_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - B1576"] #[inline(always)] pub fn b1576(&self) -> B1576_R { B1576_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - B1577"] #[inline(always)] pub fn b1577(&self) -> B1577_R { B1577_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - B1578"] #[inline(always)] pub fn b1578(&self) -> B1578_R { B1578_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - B1579"] #[inline(always)] pub fn b1579(&self) -> B1579_R { B1579_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - B1580"] #[inline(always)] pub fn b1580(&self) -> B1580_R { B1580_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - B1581"] #[inline(always)] pub fn b1581(&self) -> B1581_R { B1581_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - B1582"] #[inline(always)] pub fn b1582(&self) -> B1582_R { B1582_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - B1583"] #[inline(always)] pub fn b1583(&self) -> B1583_R { B1583_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - B1584"] #[inline(always)] pub fn b1584(&self) -> B1584_R { B1584_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - B1585"] #[inline(always)] pub fn b1585(&self) -> B1585_R { B1585_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - B1586"] #[inline(always)] pub fn b1586(&self) -> B1586_R { B1586_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - B1587"] #[inline(always)] pub fn b1587(&self) -> B1587_R { B1587_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - B1588"] #[inline(always)] pub fn b1588(&self) -> B1588_R { B1588_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - B1589"] #[inline(always)] pub fn b1589(&self) -> B1589_R { B1589_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - B1590"] #[inline(always)] pub fn b1590(&self) -> B1590_R { B1590_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - B1591"] #[inline(always)] pub fn b1591(&self) -> B1591_R { B1591_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - B1592"] #[inline(always)] pub fn b1592(&self) -> B1592_R { B1592_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - B1593"] #[inline(always)] pub fn b1593(&self) -> B1593_R { B1593_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - B1594"] #[inline(always)] pub fn b1594(&self) -> B1594_R { B1594_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - B1595"] #[inline(always)] pub fn b1595(&self) -> B1595_R { B1595_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - B1596"] #[inline(always)] pub fn b1596(&self) -> B1596_R { B1596_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - B1597"] #[inline(always)] pub fn b1597(&self) -> B1597_R { B1597_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - B1598"] #[inline(always)] pub fn b1598(&self) -> B1598_R { B1598_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - B1599"] #[inline(always)] pub fn b1599(&self) -> B1599_R { B1599_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - B1568"] #[inline(always)] pub fn b1568(&mut self) -> B1568_W { B1568_W { w: self } } #[doc = "Bit 1 - B1569"] #[inline(always)] pub fn b1569(&mut self) -> B1569_W { B1569_W { w: self } } #[doc = "Bit 2 - B1570"] #[inline(always)] pub fn b1570(&mut self) -> B1570_W { B1570_W { w: self } } #[doc = "Bit 3 - B1571"] #[inline(always)] pub fn b1571(&mut self) -> B1571_W { B1571_W { w: self } } #[doc = "Bit 4 - B1572"] #[inline(always)] pub fn b1572(&mut self) -> B1572_W { B1572_W { w: self } } #[doc = "Bit 5 - B1573"] #[inline(always)] pub fn b1573(&mut self) -> B1573_W { B1573_W { w: self } } #[doc = "Bit 6 - B1574"] #[inline(always)] pub fn b1574(&mut self) -> B1574_W { B1574_W { w: self } } #[doc = "Bit 7 - B1575"] #[inline(always)] pub fn b1575(&mut self) -> B1575_W { B1575_W { w: self } } #[doc = "Bit 8 - B1576"] #[inline(always)] pub fn b1576(&mut self) -> B1576_W { B1576_W { w: self } } #[doc = "Bit 9 - B1577"] #[inline(always)] pub fn b1577(&mut self) -> B1577_W { B1577_W { w: self } } #[doc = "Bit 10 - B1578"] #[inline(always)] pub fn b1578(&mut self) -> B1578_W { B1578_W { w: self } } #[doc = "Bit 11 - B1579"] #[inline(always)] pub fn b1579(&mut self) -> B1579_W { B1579_W { w: self } } #[doc = "Bit 12 - B1580"] #[inline(always)] pub fn b1580(&mut self) -> B1580_W { B1580_W { w: self } } #[doc = "Bit 13 - B1581"] #[inline(always)] pub fn b1581(&mut self) -> B1581_W { B1581_W { w: self } } #[doc = "Bit 14 - B1582"] #[inline(always)] pub fn b1582(&mut self) -> B1582_W { B1582_W { w: self } } #[doc = "Bit 15 - B1583"] #[inline(always)] pub fn b1583(&mut self) -> B1583_W { B1583_W { w: self } } #[doc = "Bit 16 - B1584"] #[inline(always)] pub fn b1584(&mut self) -> B1584_W { B1584_W { w: self } } #[doc = "Bit 17 - B1585"] #[inline(always)] pub fn b1585(&mut self) -> B1585_W { B1585_W { w: self } } #[doc = "Bit 18 - B1586"] #[inline(always)] pub fn b1586(&mut self) -> B1586_W { B1586_W { w: self } } #[doc = "Bit 19 - B1587"] #[inline(always)] pub fn b1587(&mut self) -> B1587_W { B1587_W { w: self } } #[doc = "Bit 20 - B1588"] #[inline(always)] pub fn b1588(&mut self) -> B1588_W { B1588_W { w: self } } #[doc = "Bit 21 - B1589"] #[inline(always)] pub fn b1589(&mut self) -> B1589_W { B1589_W { w: self } } #[doc = "Bit 22 - B1590"] #[inline(always)] pub fn b1590(&mut self) -> B1590_W { B1590_W { w: self } } #[doc = "Bit 23 - B1591"] #[inline(always)] pub fn b1591(&mut self) -> B1591_W { B1591_W { w: self } } #[doc = "Bit 24 - B1592"] #[inline(always)] pub fn b1592(&mut self) -> B1592_W { B1592_W { w: self } } #[doc = "Bit 25 - B1593"] #[inline(always)] pub fn b1593(&mut self) -> B1593_W { B1593_W { w: self } } #[doc = "Bit 26 - B1594"] #[inline(always)] pub fn b1594(&mut self) -> B1594_W { B1594_W { w: self } } #[doc = "Bit 27 - B1595"] #[inline(always)] pub fn b1595(&mut self) -> B1595_W { B1595_W { w: self } } #[doc = "Bit 28 - B1596"] #[inline(always)] pub fn b1596(&mut self) -> B1596_W { B1596_W { w: self } } #[doc = "Bit 29 - B1597"] #[inline(always)] pub fn b1597(&mut self) -> B1597_W { B1597_W { w: self } } #[doc = "Bit 30 - B1598"] #[inline(always)] pub fn b1598(&mut self) -> B1598_W { B1598_W { w: self } } #[doc = "Bit 31 - B1599"] #[inline(always)] pub fn b1599(&mut self) -> B1599_W { B1599_W { w: self } } }
//! Simple consensus runtime. use std::collections::BTreeMap; use oasis_runtime_sdk::{self as sdk, modules, types::token::Denomination, Version}; pub mod runtime; /// Simple consensus runtime. pub struct Runtime; impl sdk::Runtime for Runtime { const VERSION: Version = sdk::version_from_cargo!(); type Modules = ( modules::accounts::Module, runtime::Module<modules::accounts::Module>, modules::core::Module, ); fn genesis_state() -> <Self::Modules as sdk::module::MigrationHandler>::Genesis { ( modules::accounts::Genesis { parameters: modules::accounts::Parameters { debug_disable_nonce_check: true, ..Default::default() }, ..Default::default() }, Default::default(), modules::core::Genesis { parameters: modules::core::Parameters { max_batch_gas: 10_000_000, max_tx_signers: 8, max_multisig_signers: 8, // These are free, in order to simplify benchmarking. gas_costs: Default::default(), min_gas_price: { let mut mgp = BTreeMap::new(); mgp.insert(Denomination::NATIVE, 0); mgp }, }, }, ) } }
use super::cubic_path::CubicPath; use super::design_space::{DPoint, DVec2, ViewPort}; use super::hyper_path::{HyperPath, HyperSegment, HYPERBEZ_LIB_VERSION_KEY}; use super::point::{EntityId, PathPoint}; use super::point_list::{PathPoints, RawSegment}; use druid::kurbo::{ Affine, BezPath, Line, LineIntersection, ParamCurve, ParamCurveNearest, PathSeg, Point, Vec2, }; use druid::Data; use crate::selection::Selection; #[derive(Debug, Clone, Data)] pub enum Path { Cubic(CubicPath), Hyper(HyperPath), } #[derive(Debug, Clone)] pub enum Segment { Cubic(RawSegment), Hyper(HyperSegment), } impl Path { pub fn new(point: DPoint) -> Path { CubicPath::new(point).into() } pub fn new_hyper(point: DPoint) -> Path { Path::Hyper(HyperPath::new(point)) } pub fn from_norad(src: &norad::glyph::Contour) -> Path { if src .lib() .map(|lib| lib.contains_key(HYPERBEZ_LIB_VERSION_KEY)) .unwrap_or(false) { HyperPath::from_norad(src).into() } else { CubicPath::from_norad(src).into() } } pub fn from_raw_parts( id: EntityId, points: Vec<PathPoint>, trailing: Option<DPoint>, closed: bool, ) -> Self { CubicPath::from_raw_parts(id, points, trailing, closed).into() } pub fn to_norad(&self) -> norad::glyph::Contour { match self { Path::Cubic(path) => path.to_norad(), Path::Hyper(path) => path.to_norad(), } } pub(crate) fn is_hyper(&self) -> bool { matches!(self, Path::Hyper(_)) } fn path_points(&self) -> &PathPoints { match self { Path::Cubic(path) => path.path_points(), Path::Hyper(path) => path.path_points(), } } fn path_points_mut(&mut self) -> &mut PathPoints { match self { Path::Cubic(path) => path.path_points_mut(), Path::Hyper(path) => path.path_points_mut(), } } pub fn is_closed(&self) -> bool { self.path_points().closed() } pub fn points(&self) -> &[PathPoint] { match self { Path::Cubic(path) => path.path_points().as_slice(), Path::Hyper(path) => path.path_points().as_slice(), } } pub fn iter_segments(&self) -> impl Iterator<Item = Segment> + '_ { //NOTE: // in order to return `impl Iterator` we need to have a single concrete return type; // we can't branch on the type of the path and return a different iterator for each. // In order to make this work we have a slightly awkward implmenetation here. let hyper_segments = match self { Path::Cubic(_) => None, Path::Hyper(path) => path.hyper_segments(), }; self.path_points() .iter_segments() .enumerate() .map(move |(i, path_seg)| { if let Some(spline_seg) = hyper_segments.and_then(|segs| segs.get(i).cloned()) { Segment::Hyper(HyperSegment { path_seg, spline_seg, }) } else { Segment::Cubic(path_seg) } }) } pub(crate) fn paths_for_selection(&self, selection: &Selection) -> Vec<Path> { let paths = self.path_points().paths_for_selection(selection); paths .into_iter() .map(|pts| { if self.is_hyper() { HyperPath::from(pts).into() } else { CubicPath::from(pts).into() } }) .collect() } /// Scale the selection. /// /// `scale` is the new scale, as a ratio. /// `anchor` is a point on the screen that should remain fixed. pub(crate) fn scale_points(&mut self, points: &[EntityId], scale: Vec2, anchor: DPoint) { let scale_xform = Affine::scale_non_uniform(scale.x, scale.y); self.path_points_mut() .transform_points(points, scale_xform, anchor); self.after_change(); } pub(crate) fn nudge_points(&mut self, points: &[EntityId], v: DVec2) { let affine = Affine::translate(v.to_raw()); let transformed = self .path_points_mut() .transform_points(points, affine, DPoint::ZERO); if self.is_hyper() { for point in points { // if this is an off-curve, and its neighbouring on-curve or // its tangent off-curve are not also nudged, we set it to non-auto if let Some((on_curve, other_handle)) = self.path_points_mut().tangent_handle_opt(*point) { let others_selected = transformed.contains(&on_curve) && other_handle .map(|p| transformed.contains(&p)) .unwrap_or(true); if !others_selected { self.path_points_mut().with_point_mut(*point, |pp| { if pp.is_auto() { pp.toggle_type() } }) } } } } self.after_change(); } pub(crate) fn nudge_all_points(&mut self, v: DVec2) { let affine = Affine::translate(v.to_raw()); self.path_points_mut().transform_all(affine, DPoint::ZERO); self.after_change(); } pub fn trailing(&self) -> Option<DPoint> { self.path_points().trailing() } pub fn clear_trailing(&mut self) { self.path_points_mut().take_trailing(); } pub fn start_point(&self) -> &PathPoint { self.path_points().start_point() } /// Delete a collection of points from this path. /// /// If only a single point was deleted from this path, we will return /// the id of a point in the path that is suitable for setting as the /// new selection. pub fn delete_points(&mut self, points: &[EntityId]) -> Option<EntityId> { let result = self.path_points_mut().delete_points(points); self.after_change(); result.filter(|_| points.len() == 1) } pub fn close(&mut self, smooth: bool) -> EntityId { match self { Path::Cubic(path) => path.path_points_mut().close(), Path::Hyper(path) => { let id = path.close(smooth); self.after_change(); id } } } pub fn reverse_contour(&mut self) { self.path_points_mut().reverse_contour(); self.after_change(); } fn after_change(&mut self) { if let Path::Hyper(path) = self { path.after_change(); } } /// Returns the distance from a point to any point on this path. pub fn screen_dist(&self, vport: ViewPort, point: Point) -> f64 { let screen_bez = vport.affine() * self.bezier(); screen_bez .segments() .map(|seg| seg.nearest(point, 0.1).1) .fold(f64::MAX, |a, b| a.min(b)) } /// Iterate the segments of this path where both the start and end /// of the segment are in the selection. pub(crate) fn segments_for_points<'a>( &'a self, points: &'a Selection, ) -> impl Iterator<Item = Segment> + 'a { self.iter_segments() .filter(move |seg| points.contains(&seg.start_id()) && points.contains(&seg.end_id())) } pub(crate) fn split_segment_at_point(&mut self, seg: Segment, t: f64) { match self { Path::Cubic(path) => { if let Segment::Cubic(seg) = seg { path.split_segment_at_point(seg, t); } } Path::Hyper(path) => { if let Segment::Hyper(seg) = seg { path.split_segment_at_point(seg, t); } } } self.after_change(); } /// Upgrade a line segment to a cubic bezier. /// /// If 'use trailing' is true, this will use the trailing point to populate /// the first handle. pub(crate) fn upgrade_line_seg(&mut self, seg: &Segment, use_trailing: bool) { let cursor = self.path_points_mut().cursor(Some(seg.start_id())); let p0 = *bail!(cursor.point()); let p3 = *bail!(cursor.peek_next(), "segment has correct number of points"); let p1 = p0.point.lerp(p3.point, 1.0 / 3.0); let p1 = if use_trailing { self.path_points_mut().take_trailing().unwrap_or(p1) } else { p1 }; let p2 = p0.point.lerp(p3.point, 2.0 / 3.0); let path = seg.start_id().parent(); let (p1, p2) = if self.is_hyper() { ( PathPoint::hyper_off_curve(path, p1, true), PathPoint::hyper_off_curve(path, p2, true), ) } else { ( PathPoint::off_curve(path, p1), PathPoint::off_curve(path, p2), ) }; self.path_points_mut() .upgrade_line_seg(seg.start_id(), p1, p2); self.after_change(); } /// Upgrade a line segment to a cubic bezier. pub(crate) fn path_point_for_id(&self, point: EntityId) -> Option<PathPoint> { self.path_points().path_point_for_id(point) } pub(crate) fn prev_point(&self, point: EntityId) -> Option<PathPoint> { self.path_points().prev_point(point) } pub(crate) fn next_point(&self, point: EntityId) -> Option<PathPoint> { self.path_points().next_point(point) } pub fn id(&self) -> EntityId { self.path_points().id() } pub(crate) fn append_to_bezier(&self, bez: &mut BezPath) { match self { Path::Cubic(path) => path.append_to_bezier(bez), Path::Hyper(path) => path.append_to_bezier(bez), } } pub fn bezier(&self) -> BezPath { let mut bez = BezPath::new(); self.append_to_bezier(&mut bez); bez } /// Add a new line segment at the end of the path. /// /// This is called when the user clicks with the pen tool. pub fn line_to(&mut self, point: DPoint, smooth: bool) -> EntityId { match self { Path::Cubic(path) => path.path_points_mut().push_on_curve(point), Path::Hyper(path) => { let id = if !smooth { path.path_points_mut().push_on_curve(point) } else { path.spline_to(point, smooth); path.path_points().last_on_curve_point().id }; self.after_change(); id } } } /// Update the curve while the user drags a new control point. pub(crate) fn update_trailing(&mut self, point: EntityId, handle: DPoint) { self.path_points_mut().set_trailing(handle); if self.points().len() > 1 { let is_hyper = self.is_hyper(); let mut cursor = self.path_points_mut().cursor(Some(point)); assert!(cursor .peek_prev() .map(PathPoint::is_off_curve) .unwrap_or(false)); let on_curve_pt = bail!(cursor.point()).point; let new_p = on_curve_pt - (handle - on_curve_pt); cursor.move_prev(); if let Some(prev) = cursor.point_mut() { prev.point = new_p; if prev.is_auto() && is_hyper { prev.toggle_type(); } } self.after_change(); } } /// Set one of a given point's axes to a new value; used when aligning a set /// of points. pub(crate) fn align_point(&mut self, point: EntityId, val: f64, set_x: bool) { self.path_points_mut().with_point_mut(point, |pp| { if set_x { pp.point.x = val } else { pp.point.y = val } }); self.after_change(); } pub fn last_segment_is_curve(&self) -> bool { self.path_points().last_segment_is_curve() } /// Whether we should draw the 'trailing' control point & handle. /// We always do this for the first point, if it exists; otherwise /// we do it for curve points only. pub fn should_draw_trailing(&self) -> bool { self.path_points().len() == 1 || self.path_points().last_segment_is_curve() } // this will return `true` if passed an entity that does not actually // exist in this path but has the same parent id, such as for a point // that has been deleted. I don't think this is an issue in practice? pub(crate) fn contains(&self, id: &EntityId) -> bool { id.is_child_of(self.id()) } pub fn toggle_point_type(&mut self, id: EntityId) { self.path_points_mut() .with_point_mut(id, |pp| pp.toggle_type()); self.after_change(); } /// Only toggles the point type if it is on-curve, and only makes it /// smooth if it has a neighbouring off-curve pub fn toggle_on_curve_point_type(&mut self, id: EntityId) { let mut cursor = self.path_points_mut().cursor(Some(id)); let has_ctrl = cursor .peek_prev() .map(PathPoint::is_off_curve) .or_else(|| cursor.peek_next().map(PathPoint::is_off_curve)) .unwrap_or(false); if let Some(pt) = cursor.point_mut() { if pt.is_smooth() || pt.is_on_curve() && has_ctrl { pt.toggle_type(); } } self.after_change(); } } /// Walk the points in a list and mark those that look like tangent points /// as being tangent points (OnCurveSmooth). pub(crate) fn mark_tangent_handles(points: &mut [PathPoint]) { let len = points.len(); // a closure for calculating indices let prev_and_next_idx = |idx: usize| { let prev = (idx + len).saturating_sub(1) % len; let next = (idx + 1) % len; (prev, next) }; let mut idx = 0; while idx < len { let mut pt = points[idx]; if pt.is_on_curve() { let (prev, next) = prev_and_next_idx(idx); let prev = points[prev]; let next = points[next]; if !prev.is_on_curve() && !next.is_on_curve() { let prev_angle = (prev.point.to_raw() - pt.point.to_raw()).atan2(); let next_angle = (pt.point.to_raw() - next.point.to_raw()).atan2(); let delta_angle = (prev_angle - next_angle).abs(); // if the angle between the control points and the on-curve // point are within ~a degree of each other, consider it a tangent point. if delta_angle <= 0.018 { pt.toggle_type() } } } //pt.id.parent = parent_id; points[idx] = pt; idx += 1; } } impl Segment { pub(crate) fn start(&self) -> PathPoint { match self { Self::Cubic(seg) => seg.start(), Self::Hyper(seg) => seg.path_seg.start(), } } pub(crate) fn end(&self) -> PathPoint { match self { Self::Cubic(seg) => seg.end(), Self::Hyper(seg) => seg.path_seg.end(), } } pub(crate) fn start_id(&self) -> EntityId { self.start().id } pub(crate) fn end_id(&self) -> EntityId { self.end().id } pub(crate) fn raw_segment(&self) -> &RawSegment { match self { Self::Cubic(seg) => seg, Self::Hyper(seg) => &seg.path_seg, } } pub(crate) fn is_line(&self) -> bool { matches!(self.raw_segment(), RawSegment::Line(..)) } pub(crate) fn nearest(&self, point: DPoint) -> (f64, f64) { match self { Self::Cubic(seg) => seg .to_kurbo() .nearest(point.to_raw(), druid::kurbo::DEFAULT_ACCURACY), Self::Hyper(seg) => seg.nearest(point), } } /// This returns a point and not a DPoint because the location may /// not fall on the grid. pub(crate) fn nearest_point(&self, point: DPoint) -> Point { let (t, _) = self.nearest(point); self.eval(t) } pub(crate) fn intersect_line(&self, line: Line) -> Vec<LineIntersection> { match self { Self::Cubic(seg) => seg.to_kurbo().intersect_line(line).into_iter().collect(), Self::Hyper(seg) if self.is_line() => seg .path_seg .to_kurbo() .intersect_line(line) .into_iter() .collect(), Self::Hyper(seg) => seg .kurbo_segments() .enumerate() .flat_map(|(i, kseg)| { let hits = kseg.intersect_line(line); hits.into_iter().map(move |mut hit| { hit.segment_t = -hit.segment_t - i as f64; hit }) }) .collect(), } } /// The position on the segment corresponding to some param, /// generally in the range [0.0, 1.0]. pub(crate) fn eval(&self, param: f64) -> Point { match self { Self::Cubic(seg) => seg.to_kurbo().eval(param), Self::Hyper(seg) => seg.eval(param), } } pub(crate) fn kurbo_segments(&self) -> impl Iterator<Item = PathSeg> + '_ { let (one_iter, two_iter) = match self { Self::Cubic(seg) => (Some(seg.to_kurbo()), None), Self::Hyper(seg) => (None, Some(seg.kurbo_segments())), }; one_iter.into_iter().chain(two_iter.into_iter().flatten()) } //pub(crate) fn subsegment(self, range: Range<f64>) -> Self { //match &self { //Self::Cubic(seg) => Self::Cubic(seg.subsegment(range)), //Self::Hyper(_seg) => { //eprintln!("HyperBezier subsegment unimplemented"); //self //} //} //} } #[derive(Serialize, Deserialize)] #[serde(tag = "type", rename_all = "lowercase")] enum SerializePath { Cubic(PathPoints), Hyper(PathPoints), } use serde::{Deserialize, Deserializer, Serialize, Serializer}; impl Serialize for Path { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let to_ser = match self { Path::Cubic(path) => SerializePath::Cubic(path.path_points().to_owned()), Path::Hyper(path) => SerializePath::Hyper(path.path_points().to_owned()), }; to_ser.serialize(serializer) } } impl<'de> Deserialize<'de> for Path { fn deserialize<D>(deserializer: D) -> Result<Path, D::Error> where D: Deserializer<'de>, { let path: SerializePath = Deserialize::deserialize(deserializer)?; match path { SerializePath::Cubic(path) => Ok(CubicPath::from_path_points_unchecked(path).into()), SerializePath::Hyper(path) => Ok(HyperPath::from_path_points_unchecked(path).into()), } } } impl From<CubicPath> for Path { fn from(src: CubicPath) -> Path { Path::Cubic(src) } } impl From<HyperPath> for Path { fn from(src: HyperPath) -> Path { Path::Hyper(src) } } impl From<RawSegment> for Segment { fn from(src: RawSegment) -> Segment { Segment::Cubic(src) } } impl From<HyperSegment> for Segment { fn from(src: HyperSegment) -> Segment { Segment::Hyper(src) } }
extern crate cassandra; use cassandra::*; struct Pair<'a> { key: &'a str, value: i32, } const CONTACT_POINTS:&'static str = "127.0.0.1"; static CREATE_KEYSPACE:&'static str = "CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { \ \'class\': \'SimpleStrategy\', \'replication_factor\': \ \'3\' };"; static CREATE_TABLE:&'static str = "CREATE TABLE IF NOT EXISTS examples.maps (key text, items \ map<text, int>, PRIMARY KEY (key))"; static SELECT_QUERY:&'static str = "SELECT items FROM examples.maps WHERE key = ?"; static INSERT_QUERY:&'static str ="INSERT INTO examples.maps (key, items) VALUES (?, ?);"; fn insert_into_maps(session: &mut CassSession, key: &str, items: Vec<Pair>) -> Result<(), CassError> { let mut statement = CassStatement::new(INSERT_QUERY, 2); statement.bind_string(0, key).unwrap(); let mut map = CassMap::new(5); for item in items { map.append_string(item.key).unwrap(); map.append_int32(item.value).unwrap(); } try!(statement.bind_map(1, map)); try!(session.execute_statement(&statement).wait()); Ok(()) } fn select_from_maps(session: &mut CassSession, key: &str) -> Result<(), CassError> { let mut statement = CassStatement::new(SELECT_QUERY, 1); try!(statement.bind_string(0, key)); let result = try!(session.execute_statement(&statement).wait()); //println!("{:?}", result); for row in result.iter() { let column = row.get_column(0).unwrap(); //FIXME let items_iterator: MapIterator = column.map_iter().unwrap(); for item in items_iterator { println!("item: {:?}", item); } } Ok(()) } fn main() { match foo() { Ok(()) => {} Err(err) => println!("Error: {:?}",err), } } fn foo() -> Result<(), CassError> { let mut cluster = CassCluster::new(); cluster .set_contact_points(CONTACT_POINTS).unwrap() .set_load_balance_round_robin().unwrap(); let items: Vec<Pair> = vec!( Pair{key:"apple", value:1 }, Pair{key:"orange", value:2 }, Pair{key:"banana", value:3 }, Pair{key:"mango", value:4 } ); let session_future = CassSession::new().connect(&cluster).wait(); match session_future { Ok(mut session) => { try!(session.execute(CREATE_KEYSPACE,0).wait()); try!(session.execute(CREATE_TABLE,0).wait()); try!(insert_into_maps(&mut session, "test", items)); try!(select_from_maps(&mut session, "test")); session.close(); Ok(()) } Err(err) => Err(err), } }
//! A DEFLATE-based stream compression/decompression library //! //! This library is meant to supplement/replace the //! `flate` library that was previously part of the standard rust distribution //! providing a streaming encoder/decoder rather than purely //! an in-memory encoder/decoder. //! //! Like with [`flate`], flate2 is based on [`miniz.c`][1] //! //! [1]: https://github.com/richgel999/miniz //! [`flate`]: https://github.com/rust-lang/rust/tree/1.19.0/src/libflate //! //! # Organization //! //! This crate consists mainly of three modules, [`read`], [`write`], and //! [`bufread`]. Each module contains a number of types used to encode and //! decode various streams of data. //! //! All types in the [`write`] module work on instances of [`Write`][write], //! whereas all types in the [`read`] module work on instances of //! [`Read`][read] and [`bufread`] works with [`BufRead`][bufread]. If you //! are decoding directly from a `&[u8]`, use the [`bufread`] types. //! //! ``` //! use flate2::write::GzEncoder; //! use flate2::Compression; //! use std::io; //! use std::io::prelude::*; //! //! # fn main() { let _ = run(); } //! # fn run() -> io::Result<()> { //! let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); //! encoder.write_all(b"Example")?; //! # Ok(()) //! # } //! ``` //! //! //! Other various types are provided at the top-level of the crate for //! management and dealing with encoders/decoders. Also note that types which //! operate over a specific trait often implement the mirroring trait as well. //! For example a `flate2::read::DeflateDecoder<T>` *also* implements the //! `Write` trait if `T: Write`. That is, the "dual trait" is forwarded directly //! to the underlying object if available. //! //! [`read`]: read/index.html //! [`bufread`]: bufread/index.html //! [`write`]: write/index.html //! [read]: https://doc.rust-lang.org/std/io/trait.Read.html //! [write]: https://doc.rust-lang.org/std/io/trait.Write.html //! [bufread]: https://doc.rust-lang.org/std/io/trait.BufRead.html //! //! # Async I/O //! //! This crate optionally can support async I/O streams with the [Tokio stack] via //! the `tokio` feature of this crate: //! //! [Tokio stack]: https://tokio.rs/ //! //! ```toml //! flate2 = { version = "0.2", features = ["tokio"] } //! ``` //! //! All methods are internally capable of working with streams that may return //! [`ErrorKind::WouldBlock`] when they're not ready to perform the particular //! operation. //! //! [`ErrorKind::WouldBlock`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html //! //! Note that care needs to be taken when using these objects, however. The //! Tokio runtime, in particular, requires that data is fully flushed before //! dropping streams. For compatibility with blocking streams all streams are //! flushed/written when they are dropped, and this is not always a suitable //! time to perform I/O. If I/O streams are flushed before drop, however, then //! these operations will be a noop. #![doc(html_root_url = "https://docs.rs/flate2/0.2")] #![deny(missing_docs)] #![deny(missing_debug_implementations)] #![allow(trivial_numeric_casts)] #![cfg_attr(test, deny(warnings))] extern crate crc32fast; #[cfg(feature = "tokio")] extern crate futures; #[cfg(not(all(target_arch = "wasm32", not(target_os = "emscripten"))))] extern crate libc; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; #[cfg(feature = "tokio")] extern crate tokio_io; // These must currently agree with here -- // https://github.com/Frommi/miniz_oxide/blob/e6c214efd253491ac072c2c9adba87ef5b4cd5cb/src/lib.rs#L14-L19 // // Eventually we'll want to actually move these into `libc` itself for wasm, or // otherwise not use the capi crate for miniz_oxide but rather use the // underlying types. #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))] mod libc { #![allow(non_camel_case_types)] pub type c_ulong = u64; pub type off_t = i64; pub type c_int = i32; pub type c_uint = u32; pub type size_t = usize; } pub use crc::{Crc, CrcReader, CrcWriter}; pub use gz::GzBuilder; pub use gz::GzHeader; pub use mem::{Compress, CompressError, Decompress, DecompressError, Status}; pub use mem::{FlushCompress, FlushDecompress}; mod bufreader; mod crc; mod deflate; mod ffi; mod gz; mod mem; mod zio; mod zlib; /// Types which operate over [`Read`] streams, both encoders and decoders for /// various formats. /// /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html pub mod read { pub use deflate::read::DeflateDecoder; pub use deflate::read::DeflateEncoder; pub use gz::read::GzDecoder; pub use gz::read::GzEncoder; pub use gz::read::MultiGzDecoder; pub use zlib::read::ZlibDecoder; pub use zlib::read::ZlibEncoder; } /// Types which operate over [`Write`] streams, both encoders and decoders for /// various formats. /// /// [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html pub mod write { pub use deflate::write::DeflateDecoder; pub use deflate::write::DeflateEncoder; pub use gz::write::GzDecoder; pub use gz::write::GzEncoder; pub use zlib::write::ZlibDecoder; pub use zlib::write::ZlibEncoder; } /// Types which operate over [`BufRead`] streams, both encoders and decoders for /// various formats. /// /// [`BufRead`]: https://doc.rust-lang.org/std/io/trait.BufRead.html pub mod bufread { pub use deflate::bufread::DeflateDecoder; pub use deflate::bufread::DeflateEncoder; pub use gz::bufread::GzDecoder; pub use gz::bufread::GzEncoder; pub use gz::bufread::MultiGzDecoder; pub use zlib::bufread::ZlibDecoder; pub use zlib::bufread::ZlibEncoder; } fn _assert_send_sync() { fn _assert_send_sync<T: Send + Sync>() {} _assert_send_sync::<read::DeflateEncoder<&[u8]>>(); _assert_send_sync::<read::DeflateDecoder<&[u8]>>(); _assert_send_sync::<read::ZlibEncoder<&[u8]>>(); _assert_send_sync::<read::ZlibDecoder<&[u8]>>(); _assert_send_sync::<read::GzEncoder<&[u8]>>(); _assert_send_sync::<read::GzDecoder<&[u8]>>(); _assert_send_sync::<read::MultiGzDecoder<&[u8]>>(); _assert_send_sync::<write::DeflateEncoder<Vec<u8>>>(); _assert_send_sync::<write::DeflateDecoder<Vec<u8>>>(); _assert_send_sync::<write::ZlibEncoder<Vec<u8>>>(); _assert_send_sync::<write::ZlibDecoder<Vec<u8>>>(); _assert_send_sync::<write::GzEncoder<Vec<u8>>>(); _assert_send_sync::<write::GzDecoder<Vec<u8>>>(); } /// When compressing data, the compression level can be specified by a value in /// this enum. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Compression(u32); impl Compression { /// Creates a new description of the compression level with an explicitly /// specified integer. /// /// The integer here is typically on a scale of 0-9 where 0 means "no /// compression" and 9 means "take as long as you'd like". pub fn new(level: u32) -> Compression { Compression(level) } /// No compression is to be performed, this may actually inflate data /// slightly when encoding. pub fn none() -> Compression { Compression(0) } /// Optimize for the best speed of encoding. pub fn fast() -> Compression { Compression(1) } /// Optimize for the size of data being encoded. pub fn best() -> Compression { Compression(9) } /// Returns an integer representing the compression level, typically on a /// scale of 0-9 pub fn level(&self) -> u32 { self.0 } } impl Default for Compression { fn default() -> Compression { Compression(6) } } #[cfg(test)] fn random_bytes() -> impl Iterator<Item = u8> { use rand::Rng; use std::iter; iter::repeat(()).map(|_| rand::thread_rng().gen()) }
//! Fork of the Arrow Rust FlightSQL client //! <https://github.com/apache/arrow-rs/tree/master/arrow-flight/src/sql/client.rs> //! //! Plan is to upstream much/all of this to arrow-rs //! see <https://github.com/apache/arrow-rs/issues/3301> // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::sync::Arc; use arrow::datatypes::{Schema, SchemaRef}; use arrow_flight::{ decode::FlightRecordBatchStream, error::{FlightError, Result}, sql::{ ActionCreatePreparedStatementRequest, ActionCreatePreparedStatementResult, Any, CommandGetCatalogs, CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys, CommandGetImportedKeys, CommandGetPrimaryKeys, CommandGetSqlInfo, CommandGetTableTypes, CommandGetTables, CommandGetXdbcTypeInfo, CommandPreparedStatementQuery, CommandStatementQuery, ProstMessageExt, }, Action, FlightClient, FlightDescriptor, FlightInfo, IpcMessage, Ticket, }; use bytes::Bytes; use futures_util::TryStreamExt; use prost::Message; use tonic::metadata::MetadataMap; use tonic::transport::Channel; /// A FlightSQLServiceClient handles details of interacting with a /// remote server using the FlightSQL protocol. #[derive(Debug)] pub struct FlightSqlClient { inner: FlightClient, } /// An [Arrow Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html) client /// that can run queries against FlightSql servers. /// /// If you need more low level control, such as access to response /// headers, or redirecting to different endpoints, use the lower /// level [`FlightClient`]. /// /// This client is in the "experimental" stage. It is not guaranteed /// to follow the spec in all instances. Github issues are welcomed. impl FlightSqlClient { /// Creates a new FlightSql client that connects to a server over an arbitrary tonic `Channel` pub fn new(channel: Channel) -> Self { Self::new_from_flight(FlightClient::new(channel)) } /// Create a new client from an existing [`FlightClient`] pub fn new_from_flight(inner: FlightClient) -> Self { FlightSqlClient { inner } } /// Return a reference to the underlying [`FlightClient`] pub fn inner(&self) -> &FlightClient { &self.inner } /// Return a mutable reference to the underlying [`FlightClient`] pub fn inner_mut(&mut self) -> &mut FlightClient { &mut self.inner } /// Consume self and return the inner [`FlightClient`] pub fn into_inner(self) -> FlightClient { self.inner } /// Return a reference to gRPC metadata included with each request pub fn metadata(&self) -> &MetadataMap { self.inner.metadata() } /// Return a reference to gRPC metadata included with each request /// /// This can be used, for example, to include authorization or /// other headers with each request pub fn metadata_mut(&mut self) -> &mut MetadataMap { self.inner.metadata_mut() } /// Add the specified header with value to all subsequent requests pub fn add_header(&mut self, key: &str, value: &str) -> Result<()> { self.inner.add_header(key, value) } /// Send `cmd`, encoded as protobuf, to the FlightSQL server async fn get_flight_info_for_command( &mut self, cmd: arrow_flight::sql::Any, ) -> Result<FlightInfo> { let descriptor = FlightDescriptor::new_cmd(cmd.encode_to_vec()); self.inner.get_flight_info(descriptor).await } /// Execute a SQL query on the server using [`CommandStatementQuery`] /// /// This involves two round trips /// /// Step 1: send a [`CommandStatementQuery`] message to the /// `GetFlightInfo` endpoint of the FlightSQL server to receive a /// FlightInfo descriptor. /// /// Step 2: Fetch the results described in the [`FlightInfo`] /// /// This implementation does not support alternate endpoints pub async fn query( &mut self, query: impl Into<String> + Send, ) -> Result<FlightRecordBatchStream> { let msg = CommandStatementQuery { query: query.into(), transaction_id: None, }; self.do_get_with_cmd(msg.as_any()).await } /// Get information about sql compatibility from this server using [`CommandGetSqlInfo`] /// /// This implementation does not support alternate endpoints /// /// * If omitted, then all metadata will be retrieved. /// /// [`CommandGetSqlInfo`]: https://github.com/apache/arrow/blob/3a6fc1f9eedd41df2d8ffbcbdfbdab911ff6d82e/format/FlightSql.proto#L45-L68 pub async fn get_sql_info(&mut self, info: Vec<u32>) -> Result<FlightRecordBatchStream> { let msg = CommandGetSqlInfo { info }; self.do_get_with_cmd(msg.as_any()).await } /// List the catalogs on this server using a [`CommandGetCatalogs`] message. /// /// This implementation does not support alternate endpoints /// /// [`CommandGetCatalogs`]: https://github.com/apache/arrow/blob/3a6fc1f9eedd41df2d8ffbcbdfbdab911ff6d82e/format/FlightSql.proto#L1125-L1140 pub async fn get_catalogs(&mut self) -> Result<FlightRecordBatchStream> { let msg = CommandGetCatalogs {}; self.do_get_with_cmd(msg.as_any()).await } /// List a description of the foreign key columns in the given foreign key table that /// reference the primary key or the columns representing a unique constraint of the /// parent table (could be the same or a different table) on this server using a /// [`CommandGetCrossReference`] message. /// /// # Parameters /// /// Definition from <https://github.com/apache/arrow/blob/f0c8229f5a09fe53186df171d518430243ddf112/format/FlightSql.proto#L1405-L1477> /// /// pk_catalog: The catalog name where the parent table is. /// An empty string retrieves those without a catalog. /// If omitted the catalog name should not be used to narrow the search. /// /// pk_db_schema: The Schema name where the parent table is. /// An empty string retrieves those without a schema. /// If omitted the schema name should not be used to narrow the search. /// /// pk_table: The parent table name. It cannot be null. /// /// fk_catalog: The catalog name where the foreign table is. /// An empty string retrieves those without a catalog. /// If omitted the catalog name should not be used to narrow the search. /// /// fk_db_schema: The schema name where the foreign table is. /// An empty string retrieves those without a schema. /// If omitted the schema name should not be used to narrow the search. /// /// fk_table: The foreign table name. It cannot be null. /// /// This implementation does not support alternate endpoints pub async fn get_cross_reference( &mut self, pk_catalog: Option<impl Into<String> + Send>, pk_db_schema: Option<impl Into<String> + Send>, pk_table: String, fk_catalog: Option<impl Into<String> + Send>, fk_db_schema: Option<impl Into<String> + Send>, fk_table: String, ) -> Result<FlightRecordBatchStream> { let msg = CommandGetCrossReference { pk_catalog: pk_catalog.map(|s| s.into()), pk_db_schema: pk_db_schema.map(|s| s.into()), pk_table, fk_catalog: fk_catalog.map(|s| s.into()), fk_db_schema: fk_db_schema.map(|s| s.into()), fk_table, }; self.do_get_with_cmd(msg.as_any()).await } /// List the schemas on this server /// /// # Parameters /// /// Definition from <https://github.com/apache/arrow/blob/44edc27e549d82db930421b0d4c76098941afd71/format/FlightSql.proto#L1156-L1173> /// /// catalog: Specifies the Catalog to search for the tables. /// An empty string retrieves those without a catalog. /// If omitted the catalog name should not be used to narrow the search. /// /// db_schema_filter_pattern: Specifies a filter pattern for schemas to search for. /// When no db_schema_filter_pattern is provided, the pattern will not be used to narrow the search. /// In the pattern string, two special characters can be used to denote matching rules: /// - "%" means to match any substring with 0 or more characters. /// - "_" means to match any one character. /// /// This implementation does not support alternate endpoints pub async fn get_db_schemas( &mut self, catalog: Option<impl Into<String> + Send>, db_schema_filter_pattern: Option<impl Into<String> + Send>, ) -> Result<FlightRecordBatchStream> { let msg = CommandGetDbSchemas { catalog: catalog.map(|s| s.into()), db_schema_filter_pattern: db_schema_filter_pattern.map(|s| s.into()), }; self.do_get_with_cmd(msg.as_any()).await } /// List a description of the foreign key columns that reference the given /// table's primary key columns (the foreign keys exported by a table) of a /// table on this server using a [`CommandGetExportedKeys`] message. /// /// # Parameters /// /// Definition from <https://github.com/apache/arrow/blob/0434ab65075ecd1d2ab9245bcd7ec6038934ed29/format/FlightSql.proto#L1307-L1352> /// /// catalog: Specifies the catalog to search for the foreign key table. /// An empty string retrieves those without a catalog. /// If omitted the catalog name should not be used to narrow the search. /// /// db_schema: Specifies the schema to search for the foreign key table. /// An empty string retrieves those without a schema. /// If omitted the schema name should not be used to narrow the search. /// /// table: Specifies the foreign key table to get the foreign keys for. /// /// This implementation does not support alternate endpoints pub async fn get_exported_keys( &mut self, catalog: Option<impl Into<String> + Send>, db_schema: Option<impl Into<String> + Send>, table: String, ) -> Result<FlightRecordBatchStream> { let msg = CommandGetExportedKeys { catalog: catalog.map(|s| s.into()), db_schema: db_schema.map(|s| s.into()), table, }; self.do_get_with_cmd(msg.as_any()).await } /// List the foreign keys of a table on this server using a /// [`CommandGetImportedKeys`] message. /// /// # Parameters /// /// Definition from <https://github.com/apache/arrow/blob/196222dbd543d6931f4a1432845add97be0db802/format/FlightSql.proto#L1354-L1403> /// /// catalog: Specifies the catalog to search for the primary key table. /// An empty string retrieves those without a catalog. /// If omitted the catalog name should not be used to narrow the search. /// /// db_schema: Specifies the schema to search for the primary key table. /// An empty string retrieves those without a schema. /// If omitted the schema name should not be used to narrow the search. /// /// table: Specifies the primary key table to get the foreign keys for. /// /// This implementation does not support alternate endpoints pub async fn get_imported_keys( &mut self, catalog: Option<impl Into<String> + Send>, db_schema: Option<impl Into<String> + Send>, table: String, ) -> Result<FlightRecordBatchStream> { let msg = CommandGetImportedKeys { catalog: catalog.map(|s| s.into()), db_schema: db_schema.map(|s| s.into()), table, }; self.do_get_with_cmd(msg.as_any()).await } /// List the primary keys on this server using a [`CommandGetPrimaryKeys`] message. /// /// # Parameters /// /// Definition from <https://github.com/apache/arrow/blob/2fe17338e2d1f85d0c2685d31d2dd51f138b6b80/format/FlightSql.proto#L1261-L1297> /// /// catalog: Specifies the catalog to search for the table. /// An empty string retrieves those without a catalog. /// If omitted the catalog name should not be used to narrow the search. /// /// db_schema: Specifies the schema to search for the table. /// An empty string retrieves those without a schema. /// If omitted the schema name should not be used to narrow the search. /// /// table: Specifies the table to get the primary keys for. /// /// This implementation does not support alternate endpoints pub async fn get_primary_keys( &mut self, catalog: Option<impl Into<String> + Send>, db_schema: Option<impl Into<String> + Send>, table: String, ) -> Result<FlightRecordBatchStream> { let msg = CommandGetPrimaryKeys { catalog: catalog.map(|s| s.into()), db_schema: db_schema.map(|s| s.into()), table, }; self.do_get_with_cmd(msg.as_any()).await } /// List the tables on this server using a [`CommandGetTables`] message. /// /// This implementation does not support alternate endpoints /// /// [`CommandGetTables`]: https://github.com/apache/arrow/blob/44edc27e549d82db930421b0d4c76098941afd71/format/FlightSql.proto#L1176-L1241 pub async fn get_tables( &mut self, catalog: Option<impl Into<String> + Send>, db_schema_filter_pattern: Option<impl Into<String> + Send>, table_name_filter_pattern: Option<impl Into<String> + Send>, table_types: Vec<String>, include_schema: bool, ) -> Result<FlightRecordBatchStream> { let msg = CommandGetTables { catalog: catalog.map(|s| s.into()), db_schema_filter_pattern: db_schema_filter_pattern.map(|s| s.into()), table_name_filter_pattern: table_name_filter_pattern.map(|s| s.into()), table_types, include_schema, }; self.do_get_with_cmd(msg.as_any()).await } /// List the table types on this server using a [`CommandGetTableTypes`] message. /// /// This implementation does not support alternate endpoints /// /// [`CommandGetTableTypes`]: https://github.com/apache/arrow/blob/44edc27e549d82db930421b0d4c76098941afd71/format/FlightSql.proto#L1243-L1259 pub async fn get_table_types(&mut self) -> Result<FlightRecordBatchStream> { let msg = CommandGetTableTypes {}; self.do_get_with_cmd(msg.as_any()).await } /// List information about data type supported on this server /// using a [`CommandGetXdbcTypeInfo`] message. /// /// # Parameters /// /// Definition from <https://github.com/apache/arrow/blob/9588da967c756b2923e213ccc067378ba6c90a86/format/FlightSql.proto#L1058-L1123> /// /// data_type: Specifies the data type to search for the info. /// /// This implementation does not support alternate endpoints pub async fn get_xdbc_type_info( &mut self, data_type: Option<impl Into<i32> + Send>, ) -> Result<FlightRecordBatchStream> { let msg = CommandGetXdbcTypeInfo { data_type: data_type.map(|dt| dt.into()), }; self.do_get_with_cmd(msg.as_any()).await } /// Implements the canonical interaction for most FlightSQL messages: /// /// 1. Call `GetFlightInfo` with the provided message, and get a /// [`FlightInfo`] and embedded ticket. /// /// 2. Call `DoGet` with the provided ticket. /// /// TODO: example calling with GetDbSchemas pub async fn do_get_with_cmd( &mut self, cmd: arrow_flight::sql::Any, ) -> Result<FlightRecordBatchStream> { let FlightInfo { schema: _, flight_descriptor: _, mut endpoint, total_records: _, total_bytes: _, ordered: _, } = self.get_flight_info_for_command(cmd).await?; let flight_endpoint = endpoint.pop().ok_or_else(|| { FlightError::protocol("No endpoint specifed in CommandStatementQuery response") })?; // "If the list is empty, the expectation is that the // ticket can only be redeemed on the current service // where the ticket was generated." // // https://github.com/apache/arrow-rs/blob/a0a5880665b1836890f6843b6b8772d81c463351/format/Flight.proto#L292-L294 if !flight_endpoint.location.is_empty() { return Err(FlightError::NotYetImplemented(format!( "FlightEndpoint with non empty 'location' not supported ({:?})", flight_endpoint.location, ))); } if !endpoint.is_empty() { return Err(FlightError::NotYetImplemented(format!( "Multiple endpoints returned in CommandStatementQuery response ({})", endpoint.len() + 1, ))); } // Get the underlying ticket let ticket = flight_endpoint .ticket .ok_or_else(|| { FlightError::protocol( "No ticket specifed in CommandStatementQuery's FlightInfo response", ) })? .ticket; self.inner.do_get(Ticket { ticket }).await } /// Create a prepared statement for execution. /// /// Sends a [`ActionCreatePreparedStatementRequest`] message to /// the `DoAction` endpoint of the FlightSQL server, and returns /// the handle from the server. /// /// See [`Self::execute`] to run a previously prepared statement pub async fn prepare(&mut self, query: String) -> Result<PreparedStatement> { let cmd = ActionCreatePreparedStatementRequest { query, transaction_id: None, }; let request = Action { r#type: "CreatePreparedStatement".into(), body: cmd.as_any().encode_to_vec().into(), }; let mut results: Vec<Bytes> = self.inner.do_action(request).await?.try_collect().await?; if results.len() != 1 { return Err(FlightError::ProtocolError(format!( "Expected 1 response for preparing a statement, got {}", results.len() ))); } let result = results.pop().unwrap(); // decode the response let response: arrow_flight::sql::Any = Message::decode(result.as_ref()) .map_err(|e| FlightError::ExternalError(Box::new(e)))?; let ActionCreatePreparedStatementResult { prepared_statement_handle, dataset_schema, parameter_schema, } = Any::unpack(&response)?.ok_or_else(|| { FlightError::ProtocolError(format!( "Expected ActionCreatePreparedStatementResult message but got {} instead", response.type_url )) })?; Ok(PreparedStatement::new( prepared_statement_handle, schema_bytes_to_schema(dataset_schema)?, schema_bytes_to_schema(parameter_schema)?, )) } /// Execute a SQL query on the server using [`CommandStatementQuery`] /// /// This involves two round trips /// /// Step 1: send a [`CommandStatementQuery`] message to the /// `GetFlightInfo` endpoint of the FlightSQL server to receive a /// FlightInfo descriptor. /// /// Step 2: Fetch the results described in the [`FlightInfo`] /// /// This implementation does not support alternate endpoints pub async fn execute( &mut self, statement: PreparedStatement, ) -> Result<FlightRecordBatchStream> { let PreparedStatement { prepared_statement_handle, dataset_schema: _, parameter_schema: _, } = statement; // TODO handle parameters (via DoPut) let cmd = CommandPreparedStatementQuery { prepared_statement_handle, }; self.do_get_with_cmd(cmd.as_any()).await } } fn schema_bytes_to_schema(schema: Bytes) -> Result<SchemaRef> { let schema = if schema.is_empty() { Schema::empty() } else { Schema::try_from(IpcMessage(schema))? }; Ok(Arc::new(schema)) } /// represents a "prepared statement handle" on the server #[derive(Debug, Clone)] pub struct PreparedStatement { /// The handle returned from the server prepared_statement_handle: Bytes, /// Schema for the result of the query dataset_schema: SchemaRef, /// Schema of parameters, if any parameter_schema: SchemaRef, } impl PreparedStatement { /// The handle returned from the server /// Schema for the result of the query /// Schema of parameters, if any fn new( prepared_statement_handle: Bytes, dataset_schema: SchemaRef, parameter_schema: SchemaRef, ) -> Self { Self { prepared_statement_handle, dataset_schema, parameter_schema, } } /// Return the schema of the query pub fn get_dataset_schema(&self) -> SchemaRef { Arc::clone(&self.dataset_schema) } /// Return the schema needed for the parameters pub fn get_parameter_schema(&self) -> SchemaRef { Arc::clone(&self.parameter_schema) } }
macro_rules! check_roundtrip { ( $funcs:ident, $initial_int:expr, ($($ret_val:ident=$composite:expr),* $(,)*), $ret_fn:ident, $take_fn:ident $(,)* ) => { #[allow(unused_parens)] { let res=($funcs.$ret_fn)($initial_int); let composite=($($composite),*); if res!=composite { return Err(make_invalid_cabi_err(composite.clone(),res.clone())); } let ($($ret_val),*)=res.clone(); let int=($funcs.$take_fn)($($ret_val),*); if int!=$initial_int { return Err(make_invalid_cabi_err( (composite.clone(),$initial_int), (res.clone(),int), )); } }} } macro_rules! anon_struct { ( $($fname:ident : $fval:expr),* $(,)* ) => {{ #[allow(non_camel_case_types)] struct Anonymous<$($fname),*>{ $($fname:$fname,)* } Anonymous{ $($fname:$fval,)* } }}; }
/// Packed points within a Tuple Variation Store use otspec::types::*; use otspec::{deserialize_visitor, read_field, read_field_counted}; use serde::de::SeqAccess; use serde::de::Visitor; use serde::ser::SerializeSeq; use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// An array of packed points /// /// If the option is None, then this represents all points within the glyph. /// (Including phantom points.) This must be decoded with reference to the /// glyph's contour and component information. If the option is Some, a vector /// of the point numbers for which delta information is provided. #[derive(Debug, PartialEq)] pub struct PackedPoints { /// the array of points pub points: Option<Vec<uint16>>, } deserialize_visitor!( PackedPoints, PackedPointsVisitor, fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> { let mut count: u16 = read_field!(seq, u8, "a packed point count (first byte)") as u16; if count > 127 { let count2: u16 = read_field!(seq, u8, "a packed point count (second byte)") as u16; count = (count & 0xff) << 8 | count2; } if count == 0 { // All of them return Ok(PackedPoints { points: None }); } let mut res = vec![]; while res.len() < count as usize { let control_byte = read_field!(seq, u8, "a packed point control byte"); let points_are_words = (control_byte & 0x80) > 0; // "The low 7 bits specify the number of elements in the run minus 1." // MINUS ONE. let run_count = (control_byte & 0x7f) + 1; let deltas: Vec<u16>; if points_are_words { deltas = read_field_counted!(seq, run_count, "packed points"); } else { let delta_bytes: Vec<u8> = read_field_counted!(seq, run_count, "packed points"); deltas = delta_bytes.iter().map(|x| *x as u16).collect(); } res.extend(deltas); } let cumsum: Vec<u16> = res .iter() .scan(0, |acc, &x| { *acc += x; Some(*acc) }) .collect(); Ok(PackedPoints { points: Some(cumsum), }) } ); impl Serialize for PackedPoints { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_seq(None)?; if self.points.is_none() { seq.serialize_element::<u8>(&0)?; return seq.end(); } let points = self.points.as_ref().unwrap(); let num_points = points.len() as uint16; if num_points <= 0x80 { seq.serialize_element::<u8>(&(num_points as u8))?; } else { seq.serialize_element::<u16>(&(num_points | 0x8000))?; } let mut pos = 0; let mut last_value = 0; while pos < points.len() { let mut run: Vec<u8> = vec![0]; let mut use_bytes: Option<bool> = None; while pos < points.len() && run.len() < 127 { let current = points[pos]; let delta = current - last_value; if use_bytes.is_none() { use_bytes = Some((0..=0xff).contains(&delta)); } if use_bytes.unwrap() && !(0..=0xff).contains(&delta) { break; } if use_bytes.unwrap() { run.push(delta as u8); } else { run.push((delta >> 8) as u8); run.push((delta & 0xff) as u8); } last_value = current; pos += 1; } if use_bytes.unwrap() { run[0] = (run.len() as u8) - 2; // Don't count control byte } else { run[0] = (run.len() as u8 - 2) | 0x80; } seq.serialize_element(&run)?; } seq.end() } } #[cfg(test)] mod tests { use crate::otvar::PackedPoints; #[test] fn test_packed_point_de() { let packed = vec![ 0x0b, 0x0a, 0x00, 0x03, 0x01, 0x03, 0x01, 0x03, 0x01, 0x03, 0x02, 0x02, 0x02, ]; let expected = PackedPoints { points: Some(vec![0, 3, 4, 7, 8, 11, 12, 15, 17, 19, 21]), }; let deserialized: PackedPoints = otspec::de::from_bytes(&packed).unwrap(); assert_eq!(deserialized, expected); } #[test] fn test_packed_point_ser() { let expected = vec![ 0x0b, 0x0a, 0x00, 0x03, 0x01, 0x03, 0x01, 0x03, 0x01, 0x03, 0x02, 0x02, 0x02, ]; let object = PackedPoints { points: Some(vec![0, 3, 4, 7, 8, 11, 12, 15, 17, 19, 21]), }; let serialized = otspec::ser::to_bytes(&object).unwrap(); assert_eq!(serialized, expected); } }
// Copyright 2015 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. // This code produces a CFG with critical edges that, if we don't // handle properly, will cause invalid codegen. #![feature(rustc_attrs)] enum State { Both, Front, Back } pub struct Foo<A: Iterator, B: Iterator> { state: State, a: A, b: B } impl<A, B> Foo<A, B> where A: Iterator, B: Iterator<Item=A::Item> { // This is the function we care about fn next(&mut self) -> Option<A::Item> { match self.state { State::Both => match self.a.next() { elt @ Some(..) => elt, None => { self.state = State::Back; self.b.next() } }, State::Front => self.a.next(), State::Back => self.b.next(), } } } // Make sure we actually codegen a version of the function pub fn do_stuff(mut f: Foo<Box<Iterator<Item=u32>>, Box<Iterator<Item=u32>>>) { let _x = f.next(); } fn main() {}
pub mod vim_help; use paths::truncate_absolute_path; use std::fs::File; use std::io::Read; use std::path::Path; use utils::bytelines::ByteLines; use utils::read_first_lines; /// Preview of a file. #[derive(Clone, Debug)] pub struct FilePreview { /// Line number of source file at which the preview starts (exclusive). pub start: usize, /// Line number of source file at which the preview ends (inclusive). pub end: usize, /// Total lines in the source file. pub total: usize, /// Line number of the line that should be highlighed in the preview window. pub highlight_lnum: usize, /// [start, end] of the source file. pub lines: Vec<String>, } /// Returns the lines that can fit into the preview window given its window height. /// /// Center the line at `target_line_number` in the preview window if possible. /// (`target_line` - `size`, `target_line` - `size`). pub fn get_file_preview<P: AsRef<Path>>( path: P, target_line_number: usize, winheight: usize, ) -> std::io::Result<FilePreview> { let mid = winheight / 2; let (start, end, highlight_lnum) = if target_line_number > mid { (target_line_number - mid, target_line_number + mid, mid) } else { (0, winheight, target_line_number) }; let total = utils::count_lines(std::fs::File::open(path.as_ref())?)?; let lines = read_preview_lines(path, start, end)?; let end = end.min(total); Ok(FilePreview { start, end, total, highlight_lnum, lines, }) } // Copypasted from stdlib. /// Indicates how large a buffer to pre-allocate before reading the entire file. fn initial_buffer_size(file: &File) -> usize { // Allocate one extra byte so the buffer doesn't need to grow before the // final `read` call at the end of the file. Don't worry about `usize` // overflow because reading will fail regardless in that case. file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0) } fn read_preview_lines<P: AsRef<Path>>( path: P, start: usize, end: usize, ) -> std::io::Result<Vec<String>> { let mut filebuf: Vec<u8> = Vec::new(); File::open(path) .and_then(|mut file| { // XXX: is megabyte enough for any text file? const MEGABYTE: usize = 32 * 1_048_576; let filesize = initial_buffer_size(&file); if filesize > MEGABYTE { return Err(std::io::Error::new( std::io::ErrorKind::Other, "maximum preview file buffer size reached", )); } filebuf.reserve_exact(filesize); file.read_to_end(&mut filebuf) }) .map(|_| { ByteLines::new(&filebuf) .skip(start) .take(end - start) // trim_end() to get rid of ^M on Windows. .map(|l| l.trim_end().to_string()) .collect() }) } #[inline] fn as_absolute_path<P: AsRef<Path>>(path: P) -> std::io::Result<String> { if path.as_ref().is_absolute() { Ok(path.as_ref().to_string_lossy().into()) } else { // Somehow the absolute path on Windows is problematic using `canonicalize`: // C:\Users\liuchengxu\AppData\Local\nvim\init.vim // \\?\C:\Users\liuchengxu\AppData\Local\nvim\init.vim Ok(std::fs::canonicalize(path.as_ref())? .into_os_string() .to_string_lossy() .into()) } } /// Truncates the lines that are awfully long as vim can not handle them properly. /// /// Ref https://github.com/liuchengxu/vim-clap/issues/543 pub fn truncate_lines( lines: impl Iterator<Item = String>, max_width: usize, ) -> impl Iterator<Item = String> { lines.map(move |line| { if line.len() > max_width { let mut line = line; // https://github.com/liuchengxu/vim-clap/pull/544#discussion_r506281014 let replace_start = (0..max_width + 1) .rev() .find(|idx| line.is_char_boundary(*idx)) .unwrap_or_default(); // truncate to 0 line.replace_range(replace_start.., "……"); line } else { line } }) } pub fn preview_file<P: AsRef<Path>>( path: P, size: usize, max_width: usize, ) -> std::io::Result<(Vec<String>, String)> { if !path.as_ref().is_file() { return Err(std::io::Error::new( std::io::ErrorKind::Other, "Can not preview if the object is not a file", )); } let abs_path = as_absolute_path(path.as_ref())?; let lines_iter = read_first_lines(path.as_ref(), size)?; let lines = std::iter::once(abs_path.clone()) .chain(truncate_lines(lines_iter, max_width)) .collect::<Vec<_>>(); Ok((lines, abs_path)) } pub fn preview_file_with_truncated_title<P: AsRef<Path>>( path: P, size: usize, max_line_width: usize, max_title_width: usize, ) -> std::io::Result<(Vec<String>, String)> { let abs_path = as_absolute_path(path.as_ref())?; let truncated_abs_path = truncate_absolute_path(&abs_path, max_title_width).into_owned(); let lines_iter = read_first_lines(path.as_ref(), size)?; let lines = std::iter::once(truncated_abs_path.clone()) .chain(truncate_lines(lines_iter, max_line_width)) .collect::<Vec<_>>(); Ok((lines, truncated_abs_path)) } pub fn preview_file_at<P: AsRef<Path>>( path: P, winheight: usize, max_width: usize, lnum: usize, ) -> std::io::Result<(Vec<String>, usize)> { tracing::debug!(path = %path.as_ref().display(), lnum, "Previewing file"); let FilePreview { lines, highlight_lnum, .. } = get_file_preview(path.as_ref(), lnum, winheight)?; let lines = std::iter::once(format!("{}:{lnum}", path.as_ref().display())) .chain(truncate_lines(lines.into_iter(), max_width)) .collect::<Vec<_>>(); Ok((lines, highlight_lnum)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_file_preview_contains_multi_byte() { let test_txt = std::env::current_dir() .unwrap() .parent() .unwrap() .parent() .unwrap() .join("test") .join("testdata") .join("test_673.txt"); let FilePreview { lines, .. } = get_file_preview(test_txt, 2, 10).unwrap(); assert_eq!( lines, [ "test_ddd", "test_ddd //1����ˤ��ϡ�����1", "test_ddd //2����ˤ��ϡ�����2", "test_ddd //3����ˤ��ϡ�����3", "test_ddd //hello" ] ); } }
use std::path::PathBuf; pub fn download(steamcmd_path: &PathBuf) { std::fs::create_dir_all(steamcmd_path.parent().unwrap()).unwrap(); let response = reqwest::blocking::Client::new().get({ #[cfg(windows)] { "https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip" } #[cfg(unix)] { "https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz" } }).timeout(std::time::Duration::from_secs(30)).send().expect("Failed to get SteamCMD"); let response = match response.status().as_u16() { 200..=299 => response.bytes().expect("Failed to decode bytes"), code @ _ => panic!("HTTP {} from SteamCMD CDN", code) }; let dir = steamcmd_path.parent().unwrap(); #[cfg(windows)] { let mut zip = zip::ZipArchive::new(std::io::Cursor::new(response)).expect("Failed to read zip header"); zip.extract(dir).expect("Failed to extract zip"); } #[cfg(unix)] { let tar = flate2::read::GzDecoder::new(std::io::Cursor::new(response)); let mut archive = tar::Archive::new(tar); archive.unpack(dir).expect("Failed to extract zip"); } }
extern crate reqwest; fn fetch_text(url: &str) -> Result<(String), reqwest::Error> { let body = reqwest::get(url)? .text()?; Ok(body) } fn main() { let result = fetch_text("https://www.rust-lang.org"); let count = result.unwrap(); println!("{}", count); }
use buffer; use error; use image; use memory; use MemoryRequirements; /// Trait for resource creation, memory allocation and mapping. pub trait Device: memory::Device + Sized { /// Image sampler. type Sampler: 'static; /// Buffer type that can be used with this device. /// `UnboundedBuffer` can be converted to `Buffer` by `bind_buffer`. type Buffer: 'static; /// Unbounded buffer type that can be used with this device. /// `UnboundBuffer` hasn't been associated with memory yet. type UnboundBuffer: 'static; /// View to the buffer. type BufferView: 'static; /// Memory type that can be used with this device. /// `UnboundedImage` can be converted to `Image` by `bind_image`. type Image: 'static; /// Unbounded image type that can be used with this device. /// `UnboundImage` hasn't been associated with memory yet. type UnboundImage: 'static; /// View to the image. type ImageView: 'static; /// Create new unbound buffer object. fn create_buffer( &self, info: buffer::CreateInfo, ) -> Result<Self::UnboundBuffer, memory::OutOfMemoryError>; /// Fetch buffer memory requirements. fn buffer_requirements(&self, buffer: &Self::UnboundBuffer) -> MemoryRequirements; /// Bind memory range to the buffer. /// /// # Safety /// /// `offset` must be less than the size of memory. /// memory must have been allocated using one of the memory types allowed in the `mask` member of the `MemoryRequirements` structure returned from a call to `buffer_requirements` with buffer. /// `offset` must be an integer multiple of the alignment member of the `MemoryRequirements` structure returned from a call to `buffer_requirements` with buffer. /// The size member of the `MemoryRequirements` structure returned from a call to `buffer_requirements` with buffer must be less than or equal to the size of memory minus `offset`. unsafe fn bind_buffer( &self, buffer: Self::UnboundBuffer, memory: &Self::Memory, offset: u64, ) -> Result<Self::Buffer, error::BindError>; /// Destroy buffer object. unsafe fn destroy_buffer(&self, buffer: Self::Buffer); /// Create new unbound image object. fn create_image( &self, info: image::CreateInfo, ) -> Result<Self::UnboundImage, error::ImageCreationError>; /// Fetch image memory requirements. fn image_requirements(&self, image: &Self::UnboundImage) -> MemoryRequirements; /// Bind memory to the image. /// /// # Safety /// /// `offset` must be less than the size of memory. /// memory must have been allocated using one of the memory types allowed in the `mask` member of the `MemoryRequirements` structure returned from a call to `image_requirements` with image. /// `offset` must be an integer multiple of the alignment member of the `MemoryRequirements` structure returned from a call to `image_requirements` with image. /// The size member of the `MemoryRequirements` structure returned from a call to `image_requirements` with image must be less than or equal to the size of memory minus `offset`. unsafe fn bind_image( &self, image: Self::UnboundImage, memory: &Self::Memory, offset: u64, ) -> Result<Self::Image, error::BindError>; /// Destroy image object. unsafe fn destroy_image(&self, image: Self::Image); }
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Compatible layer to receive different types of errors from meta-service. /// /// It allows the server side to switch to return a smaller error type, e.g., from KVAppError to MetaAPIError. /// /// Currently: /// - Meta service kv_api returns KVAppError, while the client only consume the MetaApiError variants #[derive(thiserror::Error, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] #[serde(untagged)] pub enum Compatible<Outer, Inner> where Outer: From<Inner>, Outer: TryInto<Inner>, { Outer(Outer), Inner(Inner), } impl<Outer, Inner> Compatible<Outer, Inner> where Outer: From<Inner>, Outer: TryInto<Inner>, { pub fn into_inner(self) -> Inner where Inner: From<<Outer as TryInto<Inner>>::Error> { match self { Compatible::Outer(o) => { let i: Inner = o.try_into().unwrap_or_else(|e| Inner::from(e)); i } Compatible::Inner(i) => i, } } } #[cfg(test)] mod tests { use common_meta_types::ForwardToLeader; use common_meta_types::MembershipNode; use common_meta_types::MetaAPIError; use common_meta_types::MetaError; use crate::compat_errors::Compatible; use crate::kv_app_error::KVAppError; #[test] fn test_read_api_err_from_api_err() -> anyhow::Result<()> { let me = MetaAPIError::ForwardToLeader(ForwardToLeader { leader_id: Some(1), leader_node: Some(MembershipNode {}), }); let s = serde_json::to_string(&me)?; let ge: Compatible<KVAppError, MetaAPIError> = serde_json::from_str(&s)?; if let MetaAPIError::ForwardToLeader(f) = ge.clone().into_inner() { assert_eq!(Some(1), f.leader_id); } else { unreachable!("expect ForwardToLeader but: {:?}", ge); } Ok(()) } #[test] fn test_read_api_err_from_kv_app_err() -> anyhow::Result<()> { let me = KVAppError::MetaError(MetaError::APIError(MetaAPIError::ForwardToLeader( ForwardToLeader { leader_id: Some(1), leader_node: Some(MembershipNode {}), }, ))); let s = serde_json::to_string(&me)?; let ge: Compatible<KVAppError, MetaAPIError> = serde_json::from_str(&s)?; if let MetaAPIError::ForwardToLeader(f) = ge.clone().into_inner() { assert_eq!(Some(1), f.leader_id); } else { unreachable!("expect ForwardToLeader but: {:?}", ge); } Ok(()) } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::sync::Arc; use spin::Mutex; use core::ops::Deref; use core::fmt; use super::super::SignalDef::*; use super::super::qlib::common::*; use super::super::qlib::linux_def::*; use super::super::qlib::linux::time::*; use super::super::threadmgr::thread::*; use super::timer::timer::Clock; use super::timer::timer; #[derive(Default)] pub struct IntervalTimerInternal { pub timer: Option<timer::Timer>, // If target is not nil, it receives signo from timer expirations. If group // is true, these signals are thread-group-directed. These fields are // immutable. pub target: Option<Thread>, pub signo: Signal, pub id: TimerID, pub sigval: u64, pub group: bool, // If sigpending is true, a signal to target is already queued, and timer // expirations should increment overrunCur instead of sending another // signal. sigpending is protected by target's signal mutex. (If target is // nil, the timer will never send signals, so sigpending will be unused.) pub sigpending: bool, // If sigorphan is true, timer's setting has been changed since sigpending // last became true, such that overruns should no longer be counted in the // pending signals si_overrun. sigorphan is protected by target's signal // mutex. pub sigorphan: bool, // overrunCur is the number of overruns that have occurred since the last // time a signal was sent. overrunCur is protected by target's signal // mutex. pub overrunCur: u64, // Consider the last signal sent by this timer that has been dequeued. // overrunLast is the number of overruns that occurred between when this // signal was sent and when it was dequeued. Equivalently, overrunLast was // the value of overrunCur when this signal was dequeued. overrunLast is // protected by target's signal mutex. pub overrunLast: u64, } impl fmt::Debug for IntervalTimerInternal { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("IntervalTimerInternal") .field("signo", &self.signo) .field("id", &self.id) .finish() } } impl IntervalTimerInternal { pub fn Timer(&self) -> timer::Timer { return self.timer.clone().unwrap(); } pub fn Target(&self) -> Thread { return self.target.clone().unwrap(); } pub fn timerSettingChanged(&mut self) { if self.target.is_none() { return } let target = self.target.clone().unwrap(); let tg = target.ThreadGroup(); let pidns = tg.PIDNamespace(); let owner = pidns.lock().owner.clone(); let _r = owner.ReadLock(); let lock = tg.lock().signalLock.clone(); let _l = lock.lock(); self.sigorphan = true; self.overrunCur = 0; self.overrunLast = 0; } pub fn updateDequeuedSignalLocked(&mut self, si: &mut SignalInfo) { self.sigpending = false; if self.sigorphan { return } self.overrunLast = self.overrunCur; self.overrunCur = 0; si.SigTimer().overrun = saturateI32FromU64(self.overrunLast); } pub fn signalRejectedLocked(&mut self) { self.sigpending = false; if self.sigorphan { return } self.overrunCur += 1; } } #[derive(Debug, Clone)] pub struct IntervalTimer(Arc<Mutex<IntervalTimerInternal>>); impl Deref for IntervalTimer { type Target = Arc<Mutex<IntervalTimerInternal>>; fn deref(&self) -> &Arc<Mutex<IntervalTimerInternal>> { &self.0 } } impl timer::TimerListener for IntervalTimer { fn Notify(&self, exp: u64) { let mut it = self.lock(); if it.target.is_none() { return } let target = it.target.clone().unwrap(); let tg = target.lock().tg.clone(); let pidns = tg.PIDNamespace(); let owner = pidns.lock().owner.clone(); let _r = owner.ReadLock(); let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); if it.sigpending { it.overrunCur += exp; return } // sigpending must be set before sendSignalTimerLocked() so that it can be // unset if the signal is discarded (in which case sendSignalTimerLocked() // will return nil). it.sigpending = true; it.sigorphan = false; it.overrunCur += exp - 1; let mut si = SignalInfo { Signo: it.signo.0, Code: SignalInfo::SIGNAL_INFO_TIMER, ..Default::default() }; let timer = si.SigTimer(); timer.tid = it.id; timer.sigval = it.sigval; // si_overrun is set when the signal is dequeued. let target = it.Target(); let group = it.group; core::mem::drop(it); let err = target.sendSignalTimerLocked(&si, group, Some(self.clone())); let mut it = self.lock(); match err { Err(_) => { it.signalRejectedLocked(); } _ => (), } } fn Destroy(&self) {} } impl IntervalTimer { pub fn New(id: TimerID, sigval: u64) -> Self { let internal = IntervalTimerInternal { id: id, sigval: sigval, ..Default::default() }; return Self(Arc::new(Mutex::new(internal))) } pub fn DestroyTimer(&self) { let mut t = self.lock(); t.Timer().Destroy(); t.timerSettingChanged(); t.timer = None; } pub fn PauseTimer(&self) { self.lock().Timer().Pause(); } pub fn ResumeTimer(&self) { self.lock().Timer().Resume(); } } fn saturateI32FromU64(x: u64) -> i32 { if x > core::i32::MAX as u64 { return core::i32::MAX } return x as i32; } impl Thread { pub fn IntervalTimerCreate(&self, c: &Clock, sigev: &mut Sigevent) -> Result<TimerID> { let tg = self.lock().tg.clone(); let timerMu = tg.TimerMu(); let _tm = timerMu.lock(); let mut id: TimerID; let end = tg.lock().nextTimerID; loop { let mut tg = tg.lock(); id = tg.nextTimerID; let ok = tg.timers.contains_key(&id); tg.nextTimerID += 1; if tg.nextTimerID < 0 { tg.nextTimerID = 0; } if !ok { break; } if tg.nextTimerID == end { return Err(Error::SysError(SysErr::EAGAIN)) } } //todo: fix this // "The implementation of the default case where evp [sic] is NULL is // handled inside glibc, which invokes the underlying system call with a // suitably populated sigevent structure." - timer_create(2). This is // misleading; the timer_create syscall also handles a NULL sevp as // described by the man page // (kernel/time/posix-timers.c:sys_timer_create(), do_timer_create()). This // must be handled here instead of the syscall wrapper since sigval is the // timer ID, which isn't available until we allocate it in this function. //if sigev is none let it = IntervalTimer::New(id, sigev.Value); match sigev.Notify { SIGEV_NONE => (), SIGEV_SIGNAL | SIGEV_THREAD => { it.lock().target = tg.lock().leader.Upgrade(); it.lock().group = true; } SIGEV_THREAD_ID => { let pidns = tg.lock().pidns.clone(); { let owner = pidns.lock().owner.clone(); let _r = owner.ReadLock(); match pidns.lock().tasks.get(&sigev.Tid).clone() { None => return Err(Error::SysError(SysErr::EINVAL)), Some(t) => { let targettg = t.ThreadGroup(); if targettg != tg { return Err(Error::SysError(SysErr::EINVAL)) } it.lock().target = Some(t.clone()) }, } }; } _ => return Err(Error::SysError(SysErr::EINVAL)), } if sigev.Notify != SIGEV_NONE { it.lock().signo = Signal(sigev.Signo); if !it.lock().signo.IsValid() { return Err(Error::SysError(SysErr::EINVAL)); } } it.lock().timer = Some(timer::Timer::New(c, &Arc::new(it.clone()))); tg.lock().timers.insert(id, it); return Ok(id) } // IntervalTimerDelete implements timer_delete(2). pub fn IntervalTimerDelete(&self, id: TimerID) -> Result<()> { let tg = self.lock().tg.clone(); let timerMu = tg.TimerMu(); let _tm = timerMu.lock(); let it = match tg.lock().timers.remove(&id) { None => { return Err(Error::SysError(SysErr::EINVAL)); } Some(it) => it, }; it.DestroyTimer(); return Ok(()) } // IntervalTimerSettime implements timer_settime(2). pub fn IntervalTimerSettime(&self, id: TimerID, its: &Itimerspec, abs: bool) -> Result<Itimerspec> { let tg = self.lock().tg.clone(); let timerMu = tg.TimerMu(); let _tm = timerMu.lock(); let it = match tg.lock().timers.get(&id).clone() { None => return Err(Error::SysError(SysErr::EINVAL)), Some(it) => it.clone(), }; let timer = it.lock().timer.clone().unwrap(); let clock = timer.Clock(); let newS = timer::Setting::FromItimerspec(its, abs, &clock)?; let (tm, oldS) = timer.SwapAnd(&newS, || { it.lock().timerSettingChanged(); }); let its = timer::ItimerspecFromSetting(tm, oldS); return Ok(its) } // IntervalTimerGettime implements timer_gettime(2). pub fn IntervalTimerGettime(&self, id: TimerID) -> Result<Itimerspec> { let tg = self.lock().tg.clone(); let timerMu = tg.TimerMu(); let _tm = timerMu.lock(); let it = match tg.lock().timers.get(&id).clone() { None => return Err(Error::SysError(SysErr::EINVAL)), Some(it) => it.clone(), }; let (tm, s) = it.lock().timer.clone().unwrap().Get(); let its = timer::ItimerspecFromSetting(tm, s); return Ok(its) } // IntervalTimerGetoverrun implements timer_getoverrun(2). // // Preconditions: The caller must be running on the task context. pub fn IntervalTimerGetoverrun(&self, id: TimerID) -> Result<i32> { let tg = self.lock().tg.clone(); let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); let timerMu = tg.TimerMu(); let _tm = timerMu.lock(); let it = match tg.lock().timers.get(&id).clone() { None => return Err(Error::SysError(SysErr::EINVAL)), Some(it) => it.clone(), }; let overrunLast = it.lock().overrunLast; return Ok(saturateI32FromU64(overrunLast)) } }
use crate::{HdbError, HdbResult, HdbValue}; use bigdecimal::{BigDecimal, Zero}; use byteorder::{ByteOrder, LittleEndian}; use num_bigint::{BigInt, Sign}; use serde_db::ser::SerializationError; // MANTISSA 113-bit Integer mantissa // (byte 0; byte 14, lowest bit) // EXPONENT 14-bit Exponent, biased with 6176, leading to a range -6143 to +6144 // (byte 14, above lowest bit; byte 15, below highest bit) // SIGN 1-bit Sign: 0 is positive, 1 is negative // (byte 15, highest bit) // // The represented number is (10^EXPONENT)*MANTISSA. // It is expected that MANTISSA is not a multiple of 10. // Intermediate representation of HANA's DECIMAL type; is only used when reading // from or writing to the wire. #[derive(Clone, Debug)] pub struct HdbDecimal { raw: [u8; 16], } impl HdbDecimal { pub fn new(raw: [u8; 16]) -> Self { Self { raw } } #[cfg(feature = "sync")] pub fn parse_hdb_decimal_sync( nullable: bool, scale: i16, rdr: &mut dyn std::io::Read, ) -> HdbResult<HdbValue<'static>> { let mut raw = [0_u8; 16]; rdr.read_exact(&mut raw[..])?; if raw[15] == 112 && raw[0..=14].iter().all(|el| *el == 0) { // it's a NULL! if nullable { Ok(HdbValue::NULL) } else { Err(HdbError::Impl("received null value for not-null column")) } } else { trace!("parse DECIMAL"); let bd = Self::new(raw).into_bigdecimal_with_scale(scale); Ok(HdbValue::DECIMAL(bd)) } } #[cfg(feature = "async")] pub async fn parse_hdb_decimal_async<R: std::marker::Unpin + tokio::io::AsyncReadExt>( nullable: bool, scale: i16, rdr: &mut R, ) -> HdbResult<HdbValue<'static>> { let mut raw = [0_u8; 16]; rdr.read_exact(&mut raw[..]).await?; if raw[15] == 112 && raw[0..=14].iter().all(|el| *el == 0) { // it's a NULL! if nullable { Ok(HdbValue::NULL) } else { Err(HdbError::Impl("received null value for not-null column")) } } else { trace!("parse DECIMAL"); let bd = Self::new(raw).into_bigdecimal_with_scale(scale); Ok(HdbValue::DECIMAL(bd)) } } // Creates an HdbDecimal from a BigDecimal. #[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_sign_loss)] pub fn from_bigdecimal(bigdecimal: &BigDecimal) -> Result<Self, SerializationError> { let ten = BigInt::from(10_u8); let (sign, mantissa, exponent) = { let (mut bigint, neg_exponent) = bigdecimal.as_bigint_and_exponent(); let mut exponent = -neg_exponent; // HANA does not like mantissas that are multiples of 10 while !bigint.is_zero() && (&bigint % &ten).is_zero() { bigint /= 10; exponent += 1; } // HANA accepts only mantissas up to 113 bits, so we round if necessary loop { let (_, mantissa) = bigint.to_bytes_le(); let l = mantissa.len(); if (l > 15) || ((l == 15) && (mantissa[14] & 0b1111_1110) != 0) { bigint /= 10; exponent += 1; } else { break; } } if !(-6143..=6144).contains(&exponent) { return Err(SerializationError::Serde(format!( "exponent '{exponent}' out of range", ))); } let (sign, mantissa) = bigint.to_bytes_le(); (sign, mantissa, exponent) }; let mut raw = [0_u8; 16]; mantissa.iter().enumerate().for_each(|(i, b)| raw[i] = *b); let biased_exponent: u16 = (exponent + 6176) as u16; // bounds are checked above LittleEndian::write_u16(&mut raw[14..=15], biased_exponent * 2); if let Sign::Minus = sign { raw[15] |= 0b_1000_0000_u8; } Ok(Self { raw }) } pub fn into_bigdecimal_with_scale(self, scale: i16) -> BigDecimal { let mut bd = self.into_bigdecimal(); if scale < i16::max_value() { bd = bd.with_scale(i64::from(scale)); } bd } fn into_bigdecimal(self) -> BigDecimal { let (is_negative, mantissa, exponent) = self.into_elements(); if is_negative { -BigDecimal::new(mantissa, -exponent) } else { BigDecimal::new(mantissa, -exponent) } } // Retrieve the ingredients of the HdbDecimal pub fn into_elements(mut self) -> (bool, BigInt, i64) { let is_negative = (self.raw[15] & 0b_1000_0000_u8) != 0; self.raw[15] &= 0b_0111_1111_u8; let exponent = i64::from(LittleEndian::read_u16(&self.raw[14..=15]) >> 1) - 6176; self.raw[14] &= 0b_0000_0001_u8; let mantissa = BigInt::from_bytes_le(Sign::Plus, &self.raw[0..=14]); (is_negative, mantissa, exponent) } pub fn into_raw(self) -> [u8; 16] { self.raw } } #[cfg(test)] mod tests { use super::HdbDecimal; use bigdecimal::BigDecimal; use num::bigint::BigInt; use std::str::FromStr; #[test] fn test_all() { flexi_logger::Logger::try_with_str("info") .unwrap() .start() .unwrap(); str_2_big_2_hdb_2_big("1234.56780000"); str_2_big_2_hdb_2_big("1234.5678"); str_2_big_2_hdb_2_big("-1234.5678"); str_2_big_2_hdb_2_big("123456789"); str_2_big_2_hdb_2_big("123456789.0000"); str_2_big_2_hdb_2_big("0.1234567890000"); str_2_big_2_hdb_2_big( "0.000000000000000000000000000000000000000000000000000001234567890000", ); str_2_big_2_hdb_2_big("-123456789"); str_2_big_2_hdb_2_big("-123456789.0000"); str_2_big_2_hdb_2_big("-0.1234567890000"); str_2_big_2_hdb_2_big( "-0.000000000000000000000000000000000000000000000000000001234567890000", ); str_2_big_2_hdb_2_big("123456789123456789"); str_2_big_2_hdb_2_big("1234567890012345678900000"); str_2_big_2_hdb_2_big("1234567890000000000000000123456789"); me_2_big_2_hdb_2_big(BigInt::from_str("0").unwrap(), 0); me_2_big_2_hdb_2_big(BigInt::from_str("1234567890").unwrap(), -5); me_2_big_2_hdb_2_big(BigInt::from_str("1234567890000").unwrap(), -8); me_2_big_2_hdb_2_big( BigInt::from_str("123456789012345678901234567890").unwrap(), 0, ); me_2_big_2_hdb_2_big( BigInt::from_str("1234567890123456789012345678901234000").unwrap(), 0, ); me_2_big_2_hdb_2_big( BigInt::from_str("1234567890123456789012345678901234").unwrap(), 3, ); } fn str_2_big_2_hdb_2_big(input: &str) { debug!("input: {}", input); let bigdec = BigDecimal::from_str(input).unwrap(); big_2_hdb_2_big(&bigdec); } fn me_2_big_2_hdb_2_big(mantissa: BigInt, exponent: i64) { debug!("mantissa: {}, exponent: {}", mantissa, exponent); let bigdec = BigDecimal::new(mantissa, -exponent); big_2_hdb_2_big(&bigdec); } fn big_2_hdb_2_big(bigdec: &BigDecimal) { let hdbdec = HdbDecimal::from_bigdecimal(bigdec).unwrap(); let (s, m, e) = hdbdec.clone().into_elements(); let bigdec2 = hdbdec.clone().into_bigdecimal(); debug!("bigdec: {:?}", bigdec); debug!("hdbdec: {:?}", hdbdec); debug!("s: {:?}, m: {}, e: {}", s, m, e); debug!("bigdec2: {:?}\n", bigdec2); assert_eq!(*bigdec, bigdec2, "start != end"); } }
#[doc = "Reader of register PP"] pub type R = crate::R<u32, super::PP>; #[doc = "Maximum Conversion Rate\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum MCR_A { #[doc = "7: Full conversion rate (FCONV) as defined by TADC and NSH"] FULL = 7, } impl From<MCR_A> for u8 { #[inline(always)] fn from(variant: MCR_A) -> Self { variant as _ } } #[doc = "Reader of field `MCR`"] pub type MCR_R = crate::R<u8, MCR_A>; impl MCR_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, MCR_A> { use crate::Variant::*; match self.bits { 7 => Val(MCR_A::FULL), i => Res(i), } } #[doc = "Checks if the value of the field is `FULL`"] #[inline(always)] pub fn is_full(&self) -> bool { *self == MCR_A::FULL } } #[doc = "Reader of field `CH`"] pub type CH_R = crate::R<u8, u8>; #[doc = "Reader of field `DC`"] pub type DC_R = crate::R<u8, u8>; #[doc = "ADC Architecture\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum TYPE_A { #[doc = "0: SAR"] SAR = 0, } impl From<TYPE_A> for u8 { #[inline(always)] fn from(variant: TYPE_A) -> Self { variant as _ } } #[doc = "Reader of field `TYPE`"] pub type TYPE_R = crate::R<u8, TYPE_A>; impl TYPE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, TYPE_A> { use crate::Variant::*; match self.bits { 0 => Val(TYPE_A::SAR), i => Res(i), } } #[doc = "Checks if the value of the field is `SAR`"] #[inline(always)] pub fn is_sar(&self) -> bool { *self == TYPE_A::SAR } } #[doc = "Reader of field `RSL`"] pub type RSL_R = crate::R<u8, u8>; #[doc = "Reader of field `TS`"] pub type TS_R = crate::R<bool, bool>; #[doc = "Reader of field `APSHT`"] pub type APSHT_R = crate::R<bool, bool>; impl R { #[doc = "Bits 0:3 - Maximum Conversion Rate"] #[inline(always)] pub fn mcr(&self) -> MCR_R { MCR_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:9 - ADC Channel Count"] #[inline(always)] pub fn ch(&self) -> CH_R { CH_R::new(((self.bits >> 4) & 0x3f) as u8) } #[doc = "Bits 10:15 - Digital Comparator Count"] #[inline(always)] pub fn dc(&self) -> DC_R { DC_R::new(((self.bits >> 10) & 0x3f) as u8) } #[doc = "Bits 16:17 - ADC Architecture"] #[inline(always)] pub fn type_(&self) -> TYPE_R { TYPE_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bits 18:22 - Resolution"] #[inline(always)] pub fn rsl(&self) -> RSL_R { RSL_R::new(((self.bits >> 18) & 0x1f) as u8) } #[doc = "Bit 23 - Temperature Sensor"] #[inline(always)] pub fn ts(&self) -> TS_R { TS_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - Application-Programmable Sample-and-Hold Time"] #[inline(always)] pub fn apsht(&self) -> APSHT_R { APSHT_R::new(((self.bits >> 24) & 0x01) != 0) } }
// An "interner" is a data structure that associates values with uint tags and // allows bidirectional lookup; i.e. given a value, one can easily find the // type, and vice versa. import std::ivec; import std::map; import std::map::hashmap; import std::map::hashfn; import std::map::eqfn; import std::option; import std::option::none; import std::option::some; type interner[T] = {map: hashmap[T, uint], mutable vect: T[], hasher: hashfn[T], eqer: eqfn[T]}; fn mk[@T](hasher: hashfn[T], eqer: eqfn[T]) -> interner[T] { let m = map::mk_hashmap[T, uint](hasher, eqer); ret {map: m, mutable vect: ~[], hasher: hasher, eqer: eqer}; } fn intern[@T](itr: &interner[T], val: &T) -> uint { alt itr.map.find(val) { some(idx) { ret idx; } none. { let new_idx = ivec::len[T](itr.vect); itr.map.insert(val, new_idx); itr.vect += ~[val]; ret new_idx; } } } fn get[T](itr: &interner[T], idx: uint) -> T { ret itr.vect.(idx); }
mod url_array_validator; pub use self::url_array_validator::validate_urls; use validator::*; pub fn append_validation_error( validation_errors: Result<(), ValidationErrors>, field: &'static str, validation_error: Result<(), ValidationError>, ) -> Result<(), ValidationErrors> { if let Err(validation_error) = validation_error { let mut validation_errors = match validation_errors { Ok(_) => ValidationErrors::new(), Err(mut validation_errors) => validation_errors, }; validation_errors.add(field, validation_error); Err(validation_errors) } else { validation_errors } }
// Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } } use std::cell::RefCell; use std::rc::Rc; struct Solution {} impl Solution { pub fn find_tilt(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { let (_, tilt) = Solution::compute_tilt(&root); tilt } /// return: total weight, and total tilt pub fn compute_tilt(root: &Option<Rc<RefCell<TreeNode>>>) -> (i32, i32) { match root { None => (0, 0), Some(node) => Solution::_compute_tilt(Rc::clone(node)), } } /// leaf nodes return: (val, 0) pub fn _compute_tilt(root: Rc<RefCell<TreeNode>>) -> (i32, i32) { let node = (*root).borrow(); let (lft_weight, lft_tilt) = Solution::compute_tilt(&node.left); let (rgt_weight, rgt_tilt) = Solution::compute_tilt(&node.right); let weight = lft_weight + rgt_weight + node.val; let tilt = if lft_weight >= rgt_weight { lft_weight - rgt_weight } else { rgt_weight - lft_weight }; (weight, tilt + lft_tilt + rgt_tilt) } } fn main() { println!("Hello, world!"); }
#![allow(dead_code, collapsible_if)] #![allow(trivial_casts, trivial_numeric_casts)] use super::root::*; use mask::*; use mask::masks::*; use side::*; use piece::*; use castle; use color::*; bitflags! { pub struct Assessment: u32 { const VALID = 0 ; const HAS_NO_WHITE_KING = 1; const HAS_MORE_THAN_ONE_WHITE_KING = 1 << 1; const HAS_NO_BLACK_KING = 1 << 2; const HAS_MORE_THAN_ONE_BLACK_KING = 1 << 3; const WHITE_PAWNS_ON_PROMOTION_RANK = 1 << 4; const BLACK_PAWNS_ON_PROMOTION_RANK = 1 << 5; const EN_PASSANT_WITHOUT_PAWN = 1 << 6; const EN_PASSANT_SQUARE_OCCUPIED = 1 << 7; const CASTLING_WITHOUT_ROOK_A1 = 1 << 8; const CASTLING_WITHOUT_ROOK_H1 = 1 << 9; const CASTLING_WITHOUT_ROOK_A8 = 1 << 10; const CASTLING_WITHOUT_ROOK_H8 = 1 << 11; const CASTLING_WITHOUT_KING_E1 = 1 << 12; const CASTLING_WITHOUT_KING_E8 = 1 << 13; const WTF= 1 << 20; } } impl Position { fn validate(&self) -> Assessment { self.white_pawns_on_promotion_rank() | self.black_pawns_on_promotion_rank() | self.has_more_than_one_white_king() | self.has_no_white_king() | self.has_more_than_one_black_king() | self.has_no_black_king() | self.validate_en_passant() | self.validate_castling() } fn white_pawns_on_promotion_rank(&self) -> Assessment { if self.board.pawns::<White>().0 & _8 != EMPTY { WHITE_PAWNS_ON_PROMOTION_RANK } else { VALID } } fn black_pawns_on_promotion_rank(&self) -> Assessment { if self.board.pawns::<Black>().0 & _1 != EMPTY { BLACK_PAWNS_ON_PROMOTION_RANK } else { VALID } } fn has_more_than_one_white_king(&self) -> Assessment { if self.board.kings::<White>().0.count() > 1 { HAS_MORE_THAN_ONE_WHITE_KING } else { VALID } } fn has_no_white_king(&self) -> Assessment { if self.board.kings::<White>().0.count() == 0 { HAS_NO_WHITE_KING } else { VALID } } fn has_more_than_one_black_king(&self) -> Assessment { if self.board.kings::<Black>().0.count() > 1 { HAS_MORE_THAN_ONE_BLACK_KING } else { VALID } } fn has_no_black_king(&self) -> Assessment { if self.board.kings::<Black>().0.count() == 0 { HAS_NO_BLACK_KING } else { VALID } } fn validate_en_passant(&self) -> Assessment { use ::rank::*; if let Some(file) = self.en_passant { let pawn_rank = if self.active == Color::White { _5 } else { _4 }; let pawn_square = Mask::from_file_rank(file, pawn_rank); let pawns_of_inactive = self.board.pawns_of(self.active.invert()); if pawns_of_inactive & pawn_square == EMPTY { return EN_PASSANT_WITHOUT_PAWN } let target_rank = if self.active == Color::White { _6 } else { _3 }; let target_square = Mask::from_file_rank(file, target_rank); if self.board.get_piece(target_square) != VOID { return EN_PASSANT_SQUARE_OCCUPIED } } VALID } fn validate_castling(&self) -> Assessment { if self.available.contains(castle::WQ) { if self.board.rooks::<White>().0 & A1 == EMPTY { return CASTLING_WITHOUT_ROOK_A1 } } if self.available.contains(castle::WK) { if self.board.rooks::<White>().0 & H1 == EMPTY { return CASTLING_WITHOUT_ROOK_H1 } } if self.available.contains(castle::BQ) { if self.board.rooks::<Black>().0 & A8 == EMPTY { return CASTLING_WITHOUT_ROOK_A8 } } if self.available.contains(castle::BK) { if self.board.rooks::<Black>().0 & H8 == EMPTY { return CASTLING_WITHOUT_ROOK_H8 } } if self.available.intersects(castle::W) { if self.board.kings::<White>().0 & E1 == EMPTY { return CASTLING_WITHOUT_KING_E1 } } if self.available.intersects(castle::B) { if self.board.kings::<Black>().0 & E8 == EMPTY { return CASTLING_WITHOUT_KING_E8 } } VALID } } #[cfg(test)] mod tests { use super::*; #[test] fn valid_position() { assert_assessment( "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", VALID); } #[test] fn has_no_white_king() { assert_assessment( "8/8/8/k7/8/8/8/8 w - - 0 1", HAS_NO_WHITE_KING); } #[test] fn two_white_kings() { assert_assessment( "8/K7/8/8/K7/8/8/k7 w - - 0 1", HAS_MORE_THAN_ONE_WHITE_KING); } #[test] fn has_no_black_king() { assert_assessment( "8/8/K7/8/8/8/8/8 w - - 0 1", HAS_NO_BLACK_KING); } #[test] fn two_black_kings() { assert_assessment( "8/k7/8/8/k7/8/K7/8 w - - 0 1", HAS_MORE_THAN_ONE_BLACK_KING); } #[test] fn white_pawns_on_promotion_rank() { assert_assessment( "P7/8/8/8/k7/8/K7/8 w - - 0 1", WHITE_PAWNS_ON_PROMOTION_RANK); } #[test] fn black_pawns_on_promotion_rank() { assert_assessment( "8/8/8/8/k7/8/K7/p7 w - - 0 1", BLACK_PAWNS_ON_PROMOTION_RANK); } #[test] fn valid_en_passant() { assert_assessment( "8/8/8/p7/8/8/K7/7k w - a 0 1", VALID); } #[test] fn white_en_passant_without_pawn() { assert_assessment( "8/8/8/8/8/8/K7/7k w - a 0 1", EN_PASSANT_WITHOUT_PAWN); } #[test] fn black_en_passant_without_pawn() { assert_assessment( "8/8/8/8/8/8/K7/7k b - e 0 1", EN_PASSANT_WITHOUT_PAWN); } #[test] fn white_en_passant_square_occupied() { assert_assessment( "8/8/n7/p7/8/8/K7/7k w - a 0 1", EN_PASSANT_SQUARE_OCCUPIED); } #[test] fn black_en_passant_square_occupied() { assert_assessment( "8/8/8/8/4P3/4n3/K7/7k b - e 0 1", EN_PASSANT_SQUARE_OCCUPIED); } #[test] fn valid_all_castling_available() { assert_assessment( "r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1", VALID); } #[test] fn castling_without_king_e1() { assert_assessment( "r3k2r/8/8/8/8/8/8/R2K3R w KQkq - 0 1", CASTLING_WITHOUT_KING_E1); } #[test] fn castling_without_king_e8() { assert_assessment( "r2k3r/8/8/8/8/8/8/R3K2R w KQkq - 0 1", CASTLING_WITHOUT_KING_E8); } #[test] fn valid_no_castling_available_no_rooks() { assert_assessment( "4k3/8/8/8/8/8/8/4K3 w - - 0 1", VALID); } #[test] fn castling_without_rook_h8() { assert_assessment( "r3k3/8/8/8/8/8/8/R3K2R w KQkq - 0 1", CASTLING_WITHOUT_ROOK_H8); } #[test] fn castling_without_rook_a8() { assert_assessment( "4k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1", CASTLING_WITHOUT_ROOK_A8); } #[test] fn castling_without_rook_h1() { assert_assessment( "r3k2r/8/8/8/8/8/8/R3K3 w KQkq - 0 1", CASTLING_WITHOUT_ROOK_H1); } #[test] fn castling_without_rook_a1() { assert_assessment( "r3k2r/8/8/8/8/8/8/4K2R w KQkq - 0 1", CASTLING_WITHOUT_ROOK_A1); } fn assert_assessment(fen: &str, expected: Assessment) { assert_eq!(Position::parse(fen).validate(), expected); } }
mod with_big_integer_dividend; mod with_small_integer_dividend; use proptest::prop_assert_eq; use proptest::strategy::{BoxedStrategy, Just}; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; use crate::erlang::rem_2::result; use crate::runtime::scheduler::SchedulerDependentAlloc; use crate::test::with_process; use crate::test::{external_arc_node, strategy}; #[test] fn without_integer_dividend_errors_badarith() { crate::test::without_integer_dividend_errors_badarith(file!(), result); } #[test] fn with_integer_dividend_without_integer_divisor_errors_badarith() { crate::test::with_integer_dividend_without_integer_divisor_errors_badarith(file!(), result); } #[test] fn with_integer_dividend_with_zero_divisor_errors_badarith() { crate::test::with_integer_dividend_with_zero_divisor_errors_badarith(file!(), result); } #[test] fn with_atom_dividend_errors_badarith() { with_dividend_errors_badarith(|_| Atom::str_to_term("dividend")); } #[test] fn with_local_reference_dividend_errors_badarith() { with_dividend_errors_badarith(|process| process.next_reference()); } #[test] fn with_empty_list_dividend_errors_badarith() { with_dividend_errors_badarith(|_| Term::NIL); } #[test] fn with_list_dividend_errors_badarith() { with_dividend_errors_badarith(|process| process.cons(process.integer(0), process.integer(1))); } #[test] fn with_local_pid_dividend_errors_badarith() { with_dividend_errors_badarith(|_| Pid::make_term(0, 1).unwrap()); } #[test] fn with_external_pid_dividend_errors_badarith() { with_dividend_errors_badarith(|process| { process.external_pid(external_arc_node(), 2, 3).unwrap() }); } #[test] fn with_tuple_dividend_errors_badarith() { with_dividend_errors_badarith(|process| process.tuple_from_slice(&[])); } #[test] fn with_map_is_dividend_errors_badarith() { with_dividend_errors_badarith(|process| process.map_from_slice(&[])); } #[test] fn with_heap_binary_dividend_errors_badarith() { with_dividend_errors_badarith(|process| process.binary_from_bytes(&[])); } #[test] fn with_subbinary_dividend_errors_badarith() { with_dividend_errors_badarith(|process| { let original = process.binary_from_bytes(&[0b0000_00001, 0b1111_1110, 0b1010_1011]); process.subbinary_from_original(original, 0, 7, 2, 1) }); } fn with_dividend_errors_badarith<M>(dividend: M) where M: FnOnce(&Process) -> Term, { errors_badarith(|process| { let dividend = dividend(&process); let divisor = process.integer(0); result(&process, dividend, divisor) }); } fn errors_badarith<F>(actual: F) where F: FnOnce(&Process) -> exception::Result<Term>, { with_process(|process| assert_badarith!(actual(&process))) }
use std::io; fn main() { println!("Welcome to Dhrumil's epic Armstrong number verifier."); println!("My regards go to Brigadier General Armstrong and Edward Elric."); loop { println!("Please input the Armstrong number you'd like to verify."); let mut str_number = String::new(); io::stdin().read_line(&mut str_number) .expect("Failed to read line"); str_number = str_number.trim().to_string(); let number: u32 = match str_number.trim().parse() { Ok(num) => num, Err(_) => { println!("That was not a number. Please give me the Armstrong number you'd like to verify."); break; } }; let numlength = str_number.len() as u32; let mut armsum = 0; for digit in str_number.chars() { const RADIX: u32 = 10; let digit : u32 = digit.to_digit(RADIX).unwrap(); armsum += digit.pow(numlength); }; if armsum == number { println!("True"); } else { println!("False"); } println!("Would you like to test more numbers? y/n"); let mut again = String::new(); io::stdin().read_line(&mut again) .expect("Failed to read line"); if again.trim() == "N" || again.trim() == "n" || again.trim() == "no" || again.trim() == "No" { println!("Thanks for checking out my Armstrong number checker!"); break; } } }
use aoc_runner_derive::{aoc, aoc_generator}; #[aoc_generator(day1)] pub fn gen(input: &str) -> Vec<i32> { input.lines().map(|l| l.parse::<i32>().unwrap()).collect() } #[aoc(day1, part1)] pub fn solve_part1(input: &Vec<i32>) -> i32 { let mut i = 0; while i < input.len() - 1 { let mut j = i + 1; while j < input.len() { if input[i] + input[j] == 2020 { print!("{} x {}", input[i], input[j]); return input[i] * input[j]; } j = j + 1; } i = i + 1; } panic!("Not found") } #[aoc(day1, part2)] pub fn solve_part2(input: &Vec<i32>) -> i32 { let mut i = 0; while i < input.len() - 1 { let mut j = i + 1; while j < input.len() { let mut k = j + 1; while k < input.len() { if input[i] + input[j] + input[k] == 2020 { println!("{} x {} x {}", input[i], input[j], input[k]); return input[i] * input[j] * input[k]; } k = k + 1; } j = j + 1; } i = i + 1; } panic!("Not found") }
pub mod prelude { pub use climer::Timer; pub use deathframe::handles::SpriteSheetHandles; pub use super::best_time::BestTime; pub use super::checkpoint::{CheckpointData, CheckpointRes}; pub use super::insert_resources; pub use super::player_deaths::PlayerDeaths; pub use super::reset_level::ResetLevel; pub use super::savefile_data::SavefileDataRes; pub use super::should_display_timer::ShouldDisplayTimer; pub use super::should_save::ShouldSave; pub use super::stop_audio::StopAudio; pub use super::timer::TimerRes; pub use super::to_main_menu::ToMainMenu; pub use super::win_game::WinGame; pub use super::win_level::WinLevel; pub use crate::audio::Music; pub use crate::level_manager::LevelManager; } mod best_time; mod checkpoint; mod player_deaths; mod reset_level; mod savefile_data; mod should_display_timer; mod should_save; mod stop_audio; mod timer; mod to_main_menu; mod win_game; mod win_level; use amethyst::ecs::World; use crate::helpers::resource; use crate::settings::Settings; pub fn insert_resources(world: &mut World) { use prelude::*; world.insert(load_settings()); world.insert(SpriteSheetHandles::default()); world.insert(ResetLevel::default()); world.insert(CheckpointRes::default()); world.insert(WinLevel::default()); world.insert(WinGame::default()); world.insert(StopAudio::default()); world.insert(ShouldSave::default()); world.insert(PlayerDeaths::default()); world.insert(TimerRes::default()); world.insert(ToMainMenu::default()); world.insert(ShouldDisplayTimer::default()); world.insert(BestTime::default()); world.insert(SavefileDataRes::default()); } fn load_settings() -> Settings { use std::fs::File; let file = File::open(resource("config/settings.ron")) .expect("Couldn't open settings.ron file"); ron::de::from_reader(file).expect("Failed parsing settings.ron file") }
extern crate rucaja; extern crate tinkerpop_rs; use rucaja::{Jvm, JvmAttachment, JvmString}; use tinkerpop_rs::graph::Graph; fn main() { // The class path must contain the fat JAR. let class_path = "-Djava.class.path=../java/build/libs/tinkerpop.jar"; let jvm_options = [class_path]; // Instantiate the embedded JVM. let jvm = Jvm::new(&jvm_options); // Attach the current native thread to the JVM. let jvm_attachment = JvmAttachment::new(jvm.jvm()); // Instantiate a `TinkerGraph`. let graph = Graph::new(&jvm_attachment).expect("Could not instantiate graph"); // Add vertices. let v1 = graph.add_vertex().expect("Could not add vertex to graph"); let v2 = graph.add_vertex().expect("Could not add vertex to graph"); // Add an edge between those vertices. let p = JvmString::new(&jvm_attachment, "likes").expect("Could not create string"); graph.add_edge(&v1, &p, &v2).expect("Could not add edge"); // Print the graph using Java's `System.out.println()`. graph.println(); }
pub mod mutations; pub mod queries; pub mod service; use super::datastore::prelude::*; use chrono::prelude::*; use juniper::ID; #[derive(juniper::GraphQLObject)] #[graphql(description = "Independent project")] pub struct Project { id: ID, /// project name name: String, /// project description description: String, created_at: DateTime<Utc>, updated_at: DateTime<Utc>, } impl From<&Entity> for Project { fn from(entity: &Entity) -> Self { Self { id: DbValue::Id(entity).into(), name: DbValue::Str("name", entity).into(), description: DbValue::Str("description", entity).into(), created_at: DbValue::Timestamp("created_at", entity).into(), updated_at: DbValue::Timestamp("updated_at", entity).into(), } } } #[derive(juniper::GraphQLInputObject)] pub struct NewProjectInput { name: String, description: String, } #[derive(juniper::GraphQLInputObject)] pub struct UpdateProjectInput { name: Option<String>, description: Option<String>, } impl Project { fn new(project: NewProjectInput) -> DbProperties { fields_to_db_values(&[ AppValue::Str("name", Some(project.name)), AppValue::Str("description", Some(project.description)), ]) } fn update(project: UpdateProjectInput) -> DbProperties { fields_to_db_values(&[ AppValue::Str("name", project.name), AppValue::Str("description", project.description), ]) } }
//! # Note //! This is a 'cat' program based on Rust. //! @auhtor: Mrbanana //! @date: 2021-7-25 //! @license: The MIT License //! //! Usage: //! //! ```bash //! rust-cat [files ...] //! ``` //! //! # Knowledge you will learn //! - How to read a file in Rust //! - How to get argv[] from enviroment variable use std::env; fn main() { // 1. Check argv[] status let argv: Vec<String> = env::args().collect(); if argv.len() == 1 { eprintln!("Usage: rust-cat [files ...]"); std::process::exit(1); } // 2. Run with Config if let Err(e) = rust_cat::get_args().and_then(rust_cat::run) { eprintln!("{:?}", e); std::process::exit(1); } }
use hal::register::Register; pub enum Mode { Input, Output, Alternate, Analog } pub enum PullUpPullDown { None, PullUp, PullDown, } pub struct Port { moder: Register<u32>, otyper: Register<u32>, ospeedr: Register<u32>, pupdr: Register<u32>, idr: Register<u32>, odr: Register<u32>, bsrrl: Register<u16>, bsrrh: Register<u16>, lckr: Register<u32>, afrl: Register<u32>, afrh: Register<u32>, brr: Register<u32> } impl Port { pub fn get(&self) -> u16 { self.idr.read() as u16 } pub fn set(&mut self, data: u16) { self.odr.write(data as u32); } pub fn set_pin_mode(&mut self, pin: u8, mode: Mode) { // Each pin's in/out configuration takes 2 bits. let shift = pin * 2; let mask = !(0b11 << shift); let val = match mode { Mode::Input => 0b00, Mode::Output => 0b01, Mode::Alternate => 0b10, Mode::Analog => 0b11 }; // Clear the bits we are interested in. let masked = self.moder.read() & mask; // Set them to the new value. self.moder.write(masked | (val << shift)); } pub fn set_pin_pupd(&mut self, pin: u8, pupd: PullUpPullDown) { // Each pin's pupd configuration takes 2 bits. let shift = pin * 2; let mask = !(0b11 << shift); let val = match pupd { PullUpPullDown::None => 0b00, PullUpPullDown::PullUp => 0b01, PullUpPullDown::PullDown => 0b10 }; // Clear the bits we are interested in. let masked = self.moder.read() & mask; // Set them to the new value. self.moder.write(masked | (val << shift)); } pub fn get_pin(&self, pin: u8) -> bool { self.get() & (1 << pin) != 0 } pub fn set_pin(&mut self, pin: u8) { self.bsrrl.write(1 << pin); } pub fn clear_pin(&mut self, pin: u8) { self.bsrrh.write(1 << pin); } pub fn toggle_pin(&mut self, pin: u8) { let current = self.get_pin(pin); if current { self.clear_pin(pin); } else { self.set_pin(pin); } } pub fn set_pin_af(&mut self, pin: u8, mode: u8) { // 4 bits per pin AF. let bits = (mode as u32) << (pin as u32 * 4); if pin <= 7 { self.afrl.write(bits); } else if pin >= 8 && pin <= 15 { self.afrh.write(bits); } } }
use crate::{ resource::Resource, scheme::{Gemini, Http, Https, Log, Null, Random, Zero}, *, }; use log::debug; use std::cell::RefCell; use std::io::{Read, Write}; use url::Url; use wasmer_runtime::{Array, Ctx, WasmPtr}; pub fn open(ctx: &mut Ctx, ptr: WasmPtr<u8, Array>, len: u32) -> Result<i32, error::Error> { let (memory, env) = Process::get_memory_and_environment(ctx, 0); env.log_call("resource_open".to_string()); let violations = RefCell::new(Vec::new()); let raw_uri = ptr .get_utf8_string(memory, len) .ok_or(error::Error::InvalidArgument)?; let uri = Url::options() .syntax_violation_callback(Some(&|v| violations.borrow_mut().push(v))) .parse(&raw_uri); env.log_url(raw_uri.to_string()); match uri { Ok(uri) => { let fd = env.get_fd(); return match uri.scheme() { "gemini" => match Gemini::new(uri) { Ok(res) => { env.resources.insert(fd, Box::new(res)); return Ok(fd as i32); } Err(why) => Ok(why as i32), }, "http" => match Http::new(uri) { Ok(res) => { env.resources.insert(fd, Box::new(res)); return Ok(fd as i32); } Err(why) => Ok(why as i32), }, "https" => match Https::new(uri) { Ok(res) => { env.resources.insert(fd, Box::new(res)); return Ok(fd as i32); } Err(why) => Ok(why as i32), }, "log" => { env.resources.insert(fd, Box::new(Log::new(uri).unwrap())); Ok(fd as i32) } "null" => { env.resources.insert(fd, Box::new(Null::new(uri).unwrap())); Ok(fd as i32) } "random" => { env.resources .insert(fd, Box::new(Random::new(uri).unwrap())); Ok(fd as i32) } "zero" => { env.resources.insert(fd, Box::new(Zero::new(uri).unwrap())); Ok(fd as i32) } _ => Ok(error::Error::InvalidArgument as i32), }; } Err(why) => { log::error!("URL parsing error {}: {:?}", &raw_uri, why); Ok(error::Error::InvalidArgument as i32) } } } pub fn close(ctx: &mut Ctx, fd: u32) -> Result<(), ()> { let (_, env) = Process::get_memory_and_environment(ctx, 0); env.log_call("resource_close".to_string()); if !env.resources.contains_key(&fd) { return Err(()); } let resources = &mut env.resources.as_mut(); let res = &mut resources.get_mut(&fd); let res = &mut res.as_mut().expect("wanted mutable ref"); res.close(); resources.remove(&fd); Ok(()) } pub fn read( ctx: &mut Ctx, fd: u32, ptr: WasmPtr<u8, Array>, len: u32, ) -> Result<i32, std::option::NoneError> { let (memory, env) = Process::get_memory_and_environment(ctx, 0); env.log_call("resource_read".to_string()); if !env.resources.contains_key(&fd) { return Ok(error::Error::InvalidArgument as i32); } let res = &mut env.resources.as_mut().get_mut(&fd); let res = res.as_mut()?; let mut data = vec![0; len as usize]; match res.read(&mut data) { Err(why) => { log::error!("File read error: {:?}", why); Ok(error::Error::Unknown as i32) } Ok(read_len) => { if read_len == 0 { return Ok(error::Error::EOF as i32); } unsafe { let memory_writer = ptr.deref_mut(memory, 0, len)?; for (i, b) in data.bytes().enumerate() { memory_writer[i].set(b.unwrap()); } } Ok(len as i32) } } } pub fn write( ctx: &mut Ctx, fd: u32, ptr: WasmPtr<u8, Array>, len: u32, ) -> Result<i32, std::option::NoneError> { let (memory, env) = Process::get_memory_and_environment(ctx, 0); env.log_call("resource_write".to_string()); debug!("write: {:?} {} {}", ptr, len, fd); if !env.resources.contains_key(&fd) { return Ok(error::Error::InvalidArgument as i32); } let res = &mut env.resources.as_mut().get_mut(&fd); let res = &mut res.as_mut()?; let reader = ptr.deref(memory, 0, len)?; let mut data = vec![0; len as usize]; for (i, b) in reader.iter().enumerate() { data[i] = b.get(); } if let Err(why) = res.write(&data) { log::error!("File write error: {:?}", why); return Ok(error::Error::Unknown as i32); } Ok(len as i32) } pub fn flush(ctx: &mut Ctx, fd: u32) -> Result<i32, std::option::NoneError> { let (_, env) = Process::get_memory_and_environment(ctx, 0); env.log_call("resource_flush".to_string()); if !env.resources.contains_key(&fd) { return Ok(error::Error::InvalidArgument as i32); } let res = &mut env.resources.as_mut().get_mut(&fd); let res = &mut res.as_mut()?; if let Err(why) = res.flush() { log::error!("File flush error: {:?}", why); } Ok(0) }
//! Read information about the operating system from `/proc`. use std::collections::HashMap; use std::fs; use std::io::{Error, ErrorKind, Result}; use std::str::FromStr; use std::{thread, time}; use PID; #[derive(Debug)] pub struct VirtualMemory { /// Amount of total memory pub total: u64, /// Amount of memory available for new processes pub available: u64, /// Percent of memory used pub percent: f32, /// Memory currently in use pub used: u64, /// Memory not being used pub free: u64, /// Memory currently in use pub active: u64, /// Memory that is not in use pub inactive: u64, /// Temporary storage for raw disk blocks pub buffers: u64, /// Memory used by the page cache pub cached: u64, /// Amount of memory consumed by tmpfs filesystems pub shared: u64, } impl VirtualMemory { pub fn new( total: u64, available: u64, shared: u64, free: u64, buffers: u64, cached: u64, active: u64, inactive: u64, ) -> VirtualMemory { let used = total - free - cached - buffers; VirtualMemory { total, available, shared, free, buffers, cached, active, inactive, used, percent: (total as f32 - available as f32) / total as f32 * 100., } } } #[derive(Debug)] pub struct SwapMemory { /// Amount of total swap memory pub total: u64, /// Amount of used swap memory pub used: u64, /// Amount of free swap memory pub free: u64, /// Percent of sway memory used pub percent: f32, /// Amount of memory swapped in from disk pub sin: u64, /// Amount of memory swapped to disk pub sout: u64, } impl SwapMemory { pub fn new(total: u64, free: u64, sin: u64, sout: u64) -> SwapMemory { let used = total - free; let percent = (used as f32 / total as f32) * 100.0; SwapMemory { total, used, free, percent, sin, sout, } } } #[derive(Debug)] pub struct LoadAverage { /// number of jobs in the run queue averaged over 1 minute pub one: f32, /// number of jobs in the run queue averaged over 5 minute pub five: f32, /// number of jobs in the run queue averaged over 15 minute pub fifteen: f32, /// current number of runnable kernel entities pub runnable: i32, /// total number of runnable kernel entities pub total_runnable: i32, /// pid for the most recently created process pub last_pid: PID, } #[derive(Debug, Clone)] pub struct CpuTimes { /// Time spent by normal processes executing in user mode; /// on Linux this also includes guest time pub user: u64, /// Time spent by niced (prioritized) processes executing in user mode; /// on Linux this also includes guest_nice time pub nice: u64, /// Time spent by processes executing in kernel mode pub system: u64, /// Time spent doing nothing pub idle: u64, /// Time spent waiting for I/O to complete pub iowait: u64, /// Time spent for servicing hardware interrupts pub irq: u64, /// Time spent for servicing software interrupts pub softirq: u64, /// Time spent by other operating systems running in a virtualized environment pub steal: u64, /// Time spent running a virtual CPU for guest operating systems /// under the control of the Linux kernel pub guest: u64, /// Time spent running a niced guest /// (virtual CPU for guest operating systems /// under the control of the Linux kernel) pub guest_nice: u64, } impl CpuTimes { /// Calculate the total time of CPU utilization. /// guest time and guest_nice time are respectively include /// on user and nice times fn total_time(&self) -> u64 { self.user + self.nice + self.system + self.idle + self.iowait + self.irq + self.softirq + self.steal } /// Return the CpuTimesPercent object that contains the detailed /// CPU times percentage of CPU utilization between two instants. fn cpu_percent_since(&self, past_cpu_times: &CpuTimes) -> CpuTimesPercent { if self.total_time() > past_cpu_times.total_time() { let diff_total = (self.total_time() - past_cpu_times.total_time()) as f64; CpuTimesPercent { user: delta_percentage(self.user, past_cpu_times.user, diff_total), nice: delta_percentage(self.nice, past_cpu_times.nice, diff_total), system: delta_percentage(self.system, past_cpu_times.system, diff_total), idle: delta_percentage(self.idle, past_cpu_times.idle, diff_total), iowait: delta_percentage(self.iowait, past_cpu_times.iowait, diff_total), irq: delta_percentage(self.irq, past_cpu_times.irq, diff_total), softirq: delta_percentage(self.softirq, past_cpu_times.softirq, diff_total), steal: delta_percentage(self.steal, past_cpu_times.steal, diff_total), guest: delta_percentage(self.guest, past_cpu_times.guest, diff_total), guest_nice: delta_percentage( self.guest_nice, past_cpu_times.guest_nice, diff_total, ), } } else { CpuTimesPercent { user: 0., nice: 0., system: 0., idle: 0., iowait: 0., irq: 0., softirq: 0., steal: 0., guest: 0., guest_nice: 0., } } } } #[derive(Debug)] pub struct CpuTimesPercent { /// Percentage of time spent by normal processes executing in user mode /// between two instants; /// on Linux this also includes guest time pub user: f64, /// Percentage of time spent by niced (prioritized) processes /// executing in user mode between two instants; /// on Linux this also includes guest_nice time pub nice: f64, /// Percentage of time spent by processes executing in kernel /// mode between two instants pub system: f64, /// Percentage of time spent doing nothing between two instants pub idle: f64, /// Percentage of time spent waiting for I/O to complete between two instants pub iowait: f64, /// Percentage of time spent for servicing hardware interrupts /// between two instants pub irq: f64, /// Percentage of time spent for servicing software interrupts /// between two instants pub softirq: f64, /// Percentage of time spent by other operating systems running /// in a virtualized environment between two instants pub steal: f64, /// Percentage of time spent running a virtual CPU for guest operating systems /// under the control of the Linux kernel between two instants pub guest: f64, /// Percentage of time spent running a niced guest /// (virtual CPU for guest operating systems /// under the control of the Linux kernel) between two instants pub guest_nice: f64, } impl CpuTimesPercent { /// Caculculate the busy time in percent of a CPU /// Guest and guest_nice are count in user and nice. /// We ignore the CPU time in idle and iowait. fn busy_times(&self) -> f64 { self.user + self.nice + self.system + self.irq + self.softirq + self.steal } } /// To get a CpuPercent struct in non-blocking mode. /// /// Example : /// /// let mut cpu_percent_collector = match psutil::system::CpuPercentCollector::new() { /// Ok(cpu_percent_collector) => cpu_percent_collector, /// Err(_) => { /// println!("Could not initialize cpu_percent_collector"); /// return; /// }, /// }; /// /// // {... Your programme ...} /// /// let cpu_times_percent = cpu_percent_collector.cpu_times_percent(); /// let cpu_times_percent_percpu = cpu_percent_collector.cpu_times_percent_percpu(); /// /// See an other example in examples/cpu_percent. #[derive(Clone, Debug)] pub struct CpuPercentCollector { /// Store the CPU times informations of the last call /// of class method cpu_times_percent or cpu_times_percent_percpu /// for the global CPU last_statement_cpu: CpuTimes, /// Store the CPU times informations of the last call /// of class method cpu_times_percent or cpu_times_percent_percpu per CPU. last_statement_percpu: Vec<CpuTimes>, } impl CpuPercentCollector { /// Initialize the CpuPercentCollector struct with the cpu_times informations. pub fn new() -> Result<CpuPercentCollector> { let last_statement_cpu = cpu_times()?; let last_statement_percpu = cpu_times_percpu()?; Ok(CpuPercentCollector { last_statement_cpu, last_statement_percpu, }) } /// Returns a Result of CpuTimesPercent calculate /// since the last call of the method. /// For the first call it is since the object creation. /// /// The CpuTimesPercent object contains the detailed CPU utilization /// as percentage. pub fn cpu_times_percent(&mut self) -> Result<CpuTimesPercent> { let current_cpu_times = cpu_times()?; let cpu_percent_since = current_cpu_times.cpu_percent_since(&self.last_statement_cpu); self.last_statement_cpu = current_cpu_times; Ok(cpu_percent_since) } /// Returns a Result of vector of CpuTimesPercent /// calculate since the last call of the method. /// For the first call it is since the object creation. /// /// Each element of the vector reprensents the detailed /// CPU utilization as percentage per CPU. pub fn cpu_times_percent_percpu(&mut self) -> Result<Vec<CpuTimesPercent>> { let current_cpu_times_percpu = cpu_times_percpu()?; let mut cpu_times_percent_vector: Vec<CpuTimesPercent> = Vec::new(); let current_cpu_times_percpu_copy = current_cpu_times_percpu.clone(); for (iter, cpu_times) in current_cpu_times_percpu.iter().enumerate() { cpu_times_percent_vector .push(cpu_times.cpu_percent_since(&self.last_statement_percpu[iter])); } self.last_statement_percpu = current_cpu_times_percpu_copy; Ok(cpu_times_percent_vector) } } /// Returns the system uptime in seconds. /// /// `/proc/uptime` contains the system uptime and idle time. pub fn uptime() -> isize { let data = fs::read_to_string("/proc/uptime").unwrap(); uptime_internal(&data) } /// Returns the system uptime in seconds. /// /// Input should be in the format '12489513.08 22906637.29\n' fn uptime_internal(data: &str) -> isize { let numbers: Vec<&str> = data.split(' ').collect(); let uptime: Vec<&str> = numbers[0].split('.').collect(); FromStr::from_str(uptime[0]).unwrap() } /// Returns the system load average /// /// `/proc/loadavg` contains the system load average pub fn loadavg() -> Result<LoadAverage> { let data = fs::read_to_string("/proc/loadavg")?; loadavg_internal(&data) } fn loadavg_internal(data: &str) -> Result<LoadAverage> { // strips off any trailing new line as well let fields: Vec<&str> = data.split_whitespace().collect(); let one = try_parse!(fields[0]); let five = try_parse!(fields[1]); let fifteen = try_parse!(fields[2]); let last_pid = try_parse!(fields[4]); let entities = fields[3].split('/').collect::<Vec<&str>>(); let runnable = try_parse!(entities[0]); let total_runnable = try_parse!(entities[1]); Ok(LoadAverage { one, five, fifteen, runnable, total_runnable, last_pid, }) } fn not_found(key: &str) -> Error { Error::new(ErrorKind::NotFound, format!("{} not found", key)) } /// Returns information about virtual memory usage /// /// `/proc/meminfo` contains the virtual memory statistics pub fn virtual_memory() -> Result<VirtualMemory> { let data = fs::read_to_string("/proc/meminfo")?; let mem_info = make_map(&data)?; let total = *mem_info .get("MemTotal:") .ok_or_else(|| not_found("MemTotal"))?; let free = *mem_info .get("MemFree:") .ok_or_else(|| not_found("MemFree"))?; let buffers = *mem_info .get("Buffers:") .ok_or_else(|| not_found("Buffers"))?; let cached = *mem_info.get("Cached:").ok_or_else(|| not_found("Cached"))? // "free" cmdline utility sums reclaimable to cached. // Older versions of procps used to add slab memory instead. // This got changed in: // https://gitlab.com/procps-ng/procps/commit/05d751c4f076a2f0118b914c5e51cfbb4762ad8e + *mem_info .get("SReclaimable:") .ok_or_else(|| not_found("SReclaimable"))?; // since kernel 2.6.19 let active = *mem_info.get("Active:").ok_or_else(|| not_found("Active"))?; let inactive = *mem_info .get("Inactive:") .ok_or_else(|| not_found("Inactive"))?; // MemAvailable was introduced in kernel 3.14. The original psutil computes it if it's not // found, but since 3.14 has already reached EOL, let's assume that it's there. let available = *mem_info .get("MemAvailable:") .ok_or_else(|| not_found("MemAvailable"))?; // Shmem was introduced in 2.6.19 let shared = *mem_info.get("Shmem:").ok_or_else(|| not_found("Shmem"))?; Ok(VirtualMemory::new( total, available, shared, free, buffers, cached, active, inactive, )) } /// Returns information about swap memory usage /// /// `/proc/meminfo` and `/proc/vmstat` contains the information pub fn swap_memory() -> Result<SwapMemory> { let data = fs::read_to_string("/proc/meminfo")?; let swap_info = make_map(&data)?; let vmstat = fs::read_to_string("/proc/vmstat")?; let vmstat_info = make_map(&vmstat)?; let total = *swap_info .get("SwapTotal:") .ok_or_else(|| not_found("SwapTotal"))?; let free = *swap_info .get("SwapFree:") .ok_or_else(|| not_found("SwapFree"))?; let sin = *vmstat_info .get("pswpin") .ok_or_else(|| not_found("pswpin"))?; let sout = *vmstat_info .get("pswpout") .ok_or_else(|| not_found("pswpout"))?; Ok(SwapMemory::new(total, free, sin, sout)) } fn get_multiplier(fields: &mut Vec<&str>) -> Option<u64> { if let Some(ext) = fields.pop() { let multiplier = match ext { "kB" => Some(1024), _ => None, }; fields.push(ext); multiplier } else { None } } fn make_map(data: &str) -> Result<HashMap<&str, u64>> { let lines: Vec<&str> = data.lines().collect(); let mut map = HashMap::new(); for line in lines { let mut fields: Vec<&str> = line.split_whitespace().collect(); let key = fields[0]; let mut value = match fields[1].parse::<u64>() { Ok(v) => v, Err(_) => { return Err(Error::new( ErrorKind::InvalidData, format!("failed to parse {}", key), )); } }; if let Some(multiplier) = get_multiplier(&mut fields) { value *= multiplier; } map.insert(key, value); } Ok(map) } /// Calculate a percentage from two values and a diff_total /// /// Use in cpu_percent_since method fn delta_percentage(current_value: u64, past_value: u64, total_diff: f64) -> f64 { if past_value <= current_value { let percentage = (100. * (current_value - past_value) as f64) / total_diff; if percentage > 100. { 100. } else { percentage } } else { 0. } } /// Test interval value validity fn test_interval(interval: f64) -> Result<f64> { if interval <= 0. { Err(Error::new( ErrorKind::InvalidData, format!("Interval must be greater than 0 : {}", interval), )) } else { Ok(interval) } } /// Convert a cpu line from /proc/stat into a Vec<u64>. fn info_cpu_line(cpu_line: &str) -> Result<Vec<u64>> { let mut fields: Vec<&str> = cpu_line.split_whitespace().collect(); if fields.len() < 2 { return Err(Error::new( ErrorKind::InvalidData, format!("Wrong line use from /proc/stat : {}", cpu_line), )); } if fields.len() < 10 { return Err(Error::new( ErrorKind::InvalidData, format!("Wrong format of /proc/stat line : {}, Maybe the kernel version is too old (Linux 2.6.33)", cpu_line), )); } // The first element of the line contains "cpux", we remove it. fields.remove(0); let mut values: Vec<u64> = Vec::new(); for elt in fields { let value = match elt.parse::<u64>() { Ok(v) => v, Err(_) => { return Err(Error::new( ErrorKind::InvalidData, format!("failed to parse {}", elt), )); } }; values.push(value); } Ok(values) } /// Return the CpuTimes object from the Vec<u64> obtain by info_cpu_line. fn cpu_line_to_cpu_times(cpu_info: &[u64]) -> CpuTimes { let user = cpu_info[0]; let nice = cpu_info[1]; let system = cpu_info[2]; let idle = cpu_info[3]; let iowait = cpu_info[4]; let irq = cpu_info[5]; let softirq = cpu_info[6]; let steal = cpu_info[7]; let guest = cpu_info[8]; let guest_nice = cpu_info[9]; CpuTimes { user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice, } } /// Returns information about cpu times usage. /// /// `/proc/stat` contains the cpu times statistics pub fn cpu_times() -> Result<CpuTimes> { let data = fs::read_to_string("/proc/stat")?; let lines: Vec<&str> = data.lines().collect(); let cpu_info = match info_cpu_line(lines[0]) { Ok(cpu_info) => cpu_info, Err(error) => return Err(error), }; Ok(cpu_line_to_cpu_times(&cpu_info)) } /// Returns information about cpu time usage on a Vec /// that contains information per cpu /// /// '/proc/stat' contains the cpu times statistics pub fn cpu_times_percpu() -> Result<Vec<CpuTimes>> { let data = fs::read_to_string("/proc/stat")?; let mut lines: Vec<&str> = data.lines().collect(); let mut cpu_times_vector: Vec<CpuTimes> = Vec::new(); // Remove the first line that contain the total cpu: "cpu" lines.remove(0); for line in lines { if line.starts_with("cpu") { let cpu_info = match info_cpu_line(line) { Ok(cpu_info) => cpu_info, Err(error) => return Err(error), }; let cpu_time = cpu_line_to_cpu_times(&cpu_info); cpu_times_vector.push(cpu_time); } } Ok(cpu_times_vector) } /// Return a float representing the current system-wide /// CPU utilization as percentage. /// /// Interval must be > 0 seconds. /// If interval < 0.1, the result of this function will be meaningless. /// The function compares system CPU times elapsed before and after /// the interval (blocking). /// /// Use information contains in '/proc/stat' pub fn cpu_percent(interval: f64) -> Result<f64> { Ok(cpu_times_percent(interval)?.busy_times()) } /// Return a vector of floats representing the current system-wide /// CPU utilization as percentage. /// /// Interval must be > 0.0 seconds. /// If interval < 0.1, the result of this function will be meaningless. /// The function compares system CPU times per CPU elapsed before and after /// the interval (blocking). /// /// Use information contains in '/proc/stat' pub fn cpu_percent_percpu(interval: f64) -> Result<Vec<f64>> { let cpu_percent_percpu = cpu_times_percent_percpu(interval)?; let mut cpu_percents: Vec<f64> = Vec::new(); for cpu_percent in cpu_percent_percpu { cpu_percents.push(cpu_percent.busy_times()); } Ok(cpu_percents) } /// Return a CpuTimesPercent representing the current detailed /// CPU utilization as a percentage. /// /// Interval must be > 0.0 seconds. /// If interval is < 0.1, the result of this function will be meaningless. /// The function compares all CPU times elapsed before and after /// the interval (blocking). /// /// Use informations contains in '/proc/stat' pub fn cpu_times_percent(interval: f64) -> Result<CpuTimesPercent> { let mut cpu_percent_last_call = CpuPercentCollector::new()?; let interval = (test_interval(interval)? * 1000.) as u64; let block_time = time::Duration::from_millis(interval); thread::sleep(block_time); cpu_percent_last_call.cpu_times_percent() } /// Return a vector of CpuTimesPercent representing the current detailed /// CPU utilization as percentage per cpu. /// /// Interval must be > 0.0 seconds. /// If interval is < 0.1, the result of this function will be meaningless. /// The function compares all CPU times per CPU elapsed before and after /// the interval(blocking). /// /// Use informations contains in '/proc/stat' pub fn cpu_times_percent_percpu(interval: f64) -> Result<Vec<CpuTimesPercent>> { let mut cpu_percent_last_call = CpuPercentCollector::new()?; let interval = (test_interval(interval)? * 1000.) as u64; let block_time = time::Duration::from_millis(interval); thread::sleep(block_time); cpu_percent_last_call.cpu_times_percent_percpu() } #[cfg(test)] mod unit_tests { use super::*; #[test] fn uptime_parses() { assert_eq!(uptime_internal("12489513.08 22906637.29\n"), 12_489_513); } #[test] fn loadavg_parses() { let input = "0.49 0.70 0.84 2/519 1454\n"; let out = loadavg_internal(input).unwrap(); assert_eq!(out.one, 0.49); assert_eq!(out.five, 0.70); assert_eq!(out.fifteen, 0.84); assert_eq!(out.total_runnable, 519); assert_eq!(out.runnable, 2); assert_eq!(out.last_pid, 1454); } #[test] fn make_map_spaces() { let input = "field1: 23\nfield2: 45\nfield3: 100\n"; let out = make_map(&input).unwrap(); assert_eq!(out.get("field1:"), Some(&23)); assert_eq!(out.get("field2:"), Some(&45)); } #[test] fn make_map_tabs() { let input = "field1:\t\t\t45\nfield2:\t\t100\nfield4:\t\t\t\t4\n"; let out = make_map(&input).unwrap(); assert_eq!(out.get("field1:"), Some(&45)); assert_eq!(out.get("field2:"), Some(&100)); } #[test] fn make_map_with_ext() { let input = "field1: 100 kB\n field2: 200"; let out = make_map(&input).unwrap(); assert_eq!(out.get("field1:"), Some(&102400)); assert_eq!(out.get("field2:"), Some(&200)); } #[test] fn make_map_error() { let input = "field1: 2\nfield2: four"; let out = make_map(&input); assert!(out.is_err()) } #[test] fn multipler_kb() { assert_eq!(get_multiplier(&mut vec!["100", "kB"]), Some(1024)); } #[test] fn multiplier_none() { assert_eq!(get_multiplier(&mut vec!["100", "200"]), None); } #[test] fn multiplier_last() { assert_eq!( get_multiplier(&mut vec!["100", "200", "400", "700", "kB"]), Some(1024) ); } #[test] fn info_cpu_line_test() { let input = "cpu0 61286 322 19182 1708940 323 0 322 0 0 0 "; let result = match info_cpu_line(input) { Ok(r) => r, Err(e) => panic!("{}", e), }; assert_eq!( result, vec![61286, 322, 19182, 1_708_940, 323, 0, 322, 0, 0, 0] ); } #[test] fn cpu_line_to_cpu_times_test() { let input = vec![62972, 178, 18296, 349_198, 163, 0, 493, 0, 0, 0]; let result = cpu_line_to_cpu_times(&input); assert_eq!(result.user, 62972); assert_eq!(result.nice, 178); assert_eq!(result.system, 18296); assert_eq!(result.idle, 349_198); assert_eq!(result.iowait, 163); assert_eq!(result.irq, 0); assert_eq!(result.softirq, 493); assert_eq!(result.steal, 0); assert_eq!(result.guest, 0); assert_eq!(result.guest_nice, 0); } #[test] fn cpu_time_percent_test() { let input1 = vec![62972, 178, 18296, 349_198, 163, 0, 493, 0, 0, 0]; let input2 = vec![61286, 322, 19182, 1_708_940, 323, 0, 322, 0, 0, 0]; let result1 = cpu_line_to_cpu_times(&input1); let result2 = cpu_line_to_cpu_times(&input2); let percent = result2.cpu_percent_since(&result1); assert!(percent.user >= 0.); assert!(percent.user <= 100.); assert!(percent.nice >= 0.); assert!(percent.nice <= 100.); assert!(percent.system >= 0.); assert!(percent.system <= 100.); assert!(percent.idle >= 0.); assert!(percent.idle <= 100.); assert!(percent.iowait >= 0.); assert!(percent.iowait <= 100.); assert!(percent.irq >= 0.); assert!(percent.irq <= 100.); assert!(percent.softirq >= 0.); assert!(percent.softirq <= 100.); assert!(percent.guest >= 0.); assert!(percent.guest <= 100.); assert!(percent.guest_nice >= 0.); assert!(percent.guest_nice <= 100.); assert!(percent.steal >= 0.); assert!(percent.steal <= 100.); } }
use std::ops::Range; use candy_frontend::position::Offset; use enumset::{EnumSet, EnumSetType}; use lazy_static::lazy_static; use lsp_types::{Position, SemanticToken, SemanticTokensLegend}; use rustc_hash::FxHashMap; use strum::IntoEnumIterator; use strum_macros::EnumIter; use crate::utils::range_to_lsp_range_raw; #[derive(Debug, EnumIter, Hash, PartialEq, Eq, Clone, Copy)] pub enum SemanticTokenType { Module, Parameter, Variable, Symbol, Function, Comment, Text, Int, Operator, Address, Constant, } lazy_static! { static ref TOKEN_TYPE_MAPPING: FxHashMap<SemanticTokenType, u32> = SemanticTokenType::iter() .enumerate() .map(|(index, it)| (it, index as u32)) .collect(); } impl SemanticTokenType { pub fn as_lsp(&self) -> lsp_types::SemanticTokenType { match self { SemanticTokenType::Module => lsp_types::SemanticTokenType::NAMESPACE, SemanticTokenType::Parameter => lsp_types::SemanticTokenType::PARAMETER, SemanticTokenType::Variable => lsp_types::SemanticTokenType::VARIABLE, SemanticTokenType::Symbol => lsp_types::SemanticTokenType::ENUM_MEMBER, SemanticTokenType::Function => lsp_types::SemanticTokenType::FUNCTION, SemanticTokenType::Comment => lsp_types::SemanticTokenType::COMMENT, SemanticTokenType::Text => lsp_types::SemanticTokenType::STRING, SemanticTokenType::Int => lsp_types::SemanticTokenType::NUMBER, SemanticTokenType::Operator => lsp_types::SemanticTokenType::OPERATOR, SemanticTokenType::Address => lsp_types::SemanticTokenType::EVENT, SemanticTokenType::Constant => lsp_types::SemanticTokenType::VARIABLE, } } } #[derive(Debug, EnumIter, EnumSetType)] #[enumset(repr = "u32")] pub enum SemanticTokenModifier { Definition, Readonly, Builtin, } lazy_static! { pub static ref LEGEND: SemanticTokensLegend = SemanticTokensLegend { token_types: SemanticTokenType::iter().map(|it| it.as_lsp()).collect(), token_modifiers: SemanticTokenModifier::iter() .map(|it| it.as_lsp()) .collect(), }; } impl SemanticTokenModifier { pub fn as_lsp(&self) -> lsp_types::SemanticTokenModifier { match self { SemanticTokenModifier::Definition => lsp_types::SemanticTokenModifier::DEFINITION, SemanticTokenModifier::Readonly => lsp_types::SemanticTokenModifier::READONLY, SemanticTokenModifier::Builtin => lsp_types::SemanticTokenModifier::DEFAULT_LIBRARY, } } } pub struct SemanticTokensBuilder<'a> { text: &'a str, line_start_offsets: &'a [Offset], tokens: Vec<SemanticToken>, cursor: Position, } impl<'a> SemanticTokensBuilder<'a> { pub fn new<S, L>(text: &'a S, line_start_offsets: &'a L) -> Self where S: AsRef<str>, L: AsRef<[Offset]>, { Self { text: text.as_ref(), line_start_offsets: line_start_offsets.as_ref(), tokens: Vec::new(), cursor: Position::new(0, 0), } } pub fn add( &mut self, range: Range<Offset>, type_: SemanticTokenType, modifiers: EnumSet<SemanticTokenModifier>, ) { // Reduce the token to multiple single-line tokens. let mut range = range_to_lsp_range_raw(self.text, self.line_start_offsets, &range); if range.start.line != range.end.line { while range.start.line != range.end.line { assert!(range.start.line < range.end.line); let line_length = *self.line_start_offsets[(range.start.line as usize) + 1] - *self.line_start_offsets[range.start.line as usize] - 1; self.add_single_line(range.start, line_length as u32, type_, modifiers); range.start = Position { line: range.start.line + 1, character: 0, }; } } assert_eq!(range.start.line, range.end.line); self.add_single_line( range.start, range.end.character - range.start.character, type_, modifiers, ); } fn add_single_line( &mut self, start: Position, length: u32, type_: SemanticTokenType, mut modifiers: EnumSet<SemanticTokenModifier>, ) { assert!( start >= self.cursor, "Tokens must be added with increasing positions. The cursor was as {:?}, but the new token starts at {start:?}.", self.cursor, ); if type_ == SemanticTokenType::Variable { modifiers.insert(SemanticTokenModifier::Definition); } modifiers.insert(SemanticTokenModifier::Readonly); self.tokens.push(SemanticToken { delta_line: start.line - self.cursor.line, delta_start: if start.line == self.cursor.line { start.character - self.cursor.character } else { start.character }, length, token_type: TOKEN_TYPE_MAPPING[&type_], token_modifiers_bitset: modifiers.as_repr(), }); self.cursor.line = start.line; self.cursor.character = start.character; } pub fn finish(self) -> Vec<SemanticToken> { self.tokens } }
use core::fmt; use pins; use spin; use svd; const BAUDRATE_9600_BAUD: u32 = 0x00275000; const UART_ENABLE: u32 = 0x00000004; lazy_static! { pub static ref SERIAL: spin::Mutex<Serial> = spin::Mutex::new(Serial::new()); } pub struct Serial(); impl Serial { fn new() -> Serial { unsafe { pins::RX.input_pullup(); pins::TX.output_pullup(); svd::uart0().baudrate.write_bits(BAUDRATE_9600_BAUD); svd::uart0().enable.write_bits(UART_ENABLE); svd::uart0().tasks_starttx.write(1); svd::uart0().tasks_startrx.write(1); // Dummy write needed or TXDRDY trails write rather than leads write. // Pins are disconnected so nothing is physically transmitted on the wire. svd::uart0().txd.write_bits(0); svd::uart0().pselrxd.write(u32::from(pins::RX.0)); svd::uart0().pseltxd.write(u32::from(pins::TX.0)); } Serial() } pub fn writable(&self) -> bool { unsafe { svd::uart0().events_txdrdy.read() == 1 } } pub fn readable(&self) -> bool { unsafe { svd::uart0().events_rxdrdy.read() == 1 } } pub fn write_byte(&mut self, byte: u8) { while !self.writable() {} unsafe { svd::uart0().events_txdrdy.write(0); svd::uart0().txd.write_bits(u32::from(byte)); } } #[allow(dead_code)] pub fn read_byte(&mut self) -> u8 { while !self.readable() {} unsafe { svd::uart0().events_rxdrdy.write(0); svd::uart0().rxd.read_bits() as u8 } } } impl fmt::Write for Serial { fn write_str(&mut self, s: &str) -> fmt::Result { for b in s.bytes() { self.write_byte(b) } Ok(()) } }
// Copyright 2017 Dasein Phaos aka. Luxko // // 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. //! stream output descriptions use smallvec::SmallVec; use std::os::raw::c_char; use std::marker::PhantomData; use std::ffi::CStr; use resource::{RawResource, GpuVAddress}; /// stream output buffer view #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct StreamOutputBufferView { pub loc: GpuVAddress, pub size: u64, pub filled_size: u64, // TODO: change type to GPUVAddress? } // TODO: find out a nicer way to deal with resources impl StreamOutputBufferView { pub fn new(resource: &mut RawResource, size: u64, filled_size: u64) -> Self { StreamOutputBufferView{ loc: resource.get_gpu_vaddress(), size, filled_size, } } } impl Default for StreamOutputBufferView { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } /// stream output description #[derive(Clone, Debug)] pub struct DescBuilder<'a> { pub entries: SmallVec<[DeclarationEntry<'a>; 8]>, /// buffer strides pub strides: SmallVec<[u32; 8]>, /// index of the stream to be sent to the rasterizer stage pub rasterized_stream: u32, } impl<'a> DescBuilder<'a> { /// construction #[inline] pub fn new(rasterized_stream: u32) -> DescBuilder<'a> { DescBuilder{ entries: Default::default(), strides: Default::default(), rasterized_stream, } } /// finalization #[inline] pub fn build(&self) -> (::winapi::D3D12_STREAM_OUTPUT_DESC, PhantomData<&DescBuilder>) { (::winapi::D3D12_STREAM_OUTPUT_DESC{ pSODeclaration: self.entries.as_ptr() as *const _, NumEntries: self.entries.len() as u32, pBufferStrides: self.strides.as_ptr(), NumStrides: self.strides.len() as u32, RasterizedStream: self.rasterized_stream, }, Default::default()) } } impl<'a> Default for DescBuilder<'a> { fn default() -> Self { DescBuilder::new(0) } } /// describes an entry in a stream output slot #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct DeclarationEntry<'a> { /// zero based stream index pub stream: u32, /// `0` ended semantic name of the element semantic_name: *const c_char, /// zero based element index pub semantic_index: u32, /// component of the entry to begin writing to. valid in [0..3] pub start_component: u8, /// number of components of the entry to writing to. valid in [1..4] pub component_count: u8, /// associated stream output buffer that is bound to the pipeline. valid in [0..3] pub output_slot: u8, _pd: PhantomData<&'a CStr>, // TODO: check if legit }
extern crate day04; use std::io; use std::io::BufRead; use day04::is_valid_passphrase; fn main() { let stdin = io::stdin(); let handle = stdin.lock(); let mut count = 0; for line in handle.lines() { match line { Ok(line) => { if is_valid_passphrase(line) { count += 1; } }, Err(err) => { eprintln!("Could not read input: {}", err); std::process::exit(1); } } } println!("{}", count); }
use super::circular_unit::CircularUnit; use super::faction::Faction; use super::unit::Unit; #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] pub enum Type { Unknown = -1, MagicMissile = 0, FrostBolt = 1, Fireball = 2, Dart = 3, Count = 4, } #[derive(Clone, Debug, PartialEq)] pub struct Projectile { id: i64, x: f64, y: f64, speed_x: f64, speed_y: f64, angle: f64, faction: Faction, radius: f64, type_: Type, owner_unit_id: i64, owner_player_id: i64, } impl Projectile { pub fn new() -> Self { Projectile { id: 0, x: 0.0, y: 0.0, speed_x: 0.0, speed_y: 0.0, angle: 0.0, faction: Faction::Unknown, radius: 0.0, type_: Type::Unknown, owner_unit_id: 0, owner_player_id: 0, } } pub fn id(&self) -> i64 { self.id } pub fn set_id(&mut self, value: i64) -> &mut Self { self.id = value; self } pub fn x(&self) -> f64 { self.x } pub fn set_x(&mut self, value: f64) -> &mut Self { self.x = value; self } pub fn y(&self) -> f64 { self.y } pub fn set_y(&mut self, value: f64) -> &mut Self { self.y = value; self } pub fn speed_x(&self) -> f64 { self.speed_x } pub fn set_speed_x(&mut self, value: f64) -> &mut Self { self.speed_x = value; self } pub fn speed_y(&self) -> f64 { self.speed_y } pub fn set_speed_y(&mut self, value: f64) -> &mut Self { self.speed_y = value; self } pub fn angle(&self) -> f64 { self.angle } pub fn set_angle(&mut self, value: f64) -> &mut Self { self.angle = value; self } pub fn faction(&self) -> Faction { self.faction } pub fn set_faction(&mut self, value: Faction) -> &mut Self { self.faction = value; self } pub fn radius(&self) -> f64 { self.radius } pub fn set_radius(&mut self, value: f64) -> &mut Self { self.radius = value; self } pub fn type_(&self) -> Type { self.type_ } pub fn set_type(&mut self, value: Type) -> &mut Self { self.type_ = value; self } pub fn owner_unit_id(&self) -> i64 { self.owner_unit_id } pub fn set_owner_unit_id(&mut self, value: i64) -> &mut Self { self.owner_unit_id = value; self } pub fn owner_player_id(&self) -> i64 { self.owner_player_id } pub fn set_owner_player_id(&mut self, value: i64) -> &mut Self { self.owner_player_id = value; self } } unit_impl!(Projectile); circular_unit_impl!(Projectile);
// 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 std::fs::ReadDir; use std::future::Future; use std::path::Path; use std::time::Instant; use clap::Parser; use client::ClickhouseHttpClient; use futures_util::stream; use futures_util::StreamExt; use sqllogictest::default_column_validator; use sqllogictest::default_validator; use sqllogictest::parse_file; use sqllogictest::DBOutput; use sqllogictest::DefaultColumnType; use sqllogictest::Record; use sqllogictest::Runner; use sqllogictest::TestError; use crate::arg::SqlLogicTestArgs; use crate::client::Client; use crate::client::ClientType; use crate::client::HttpClient; use crate::client::MySQLClient; use crate::error::DSqlLogicTestError; use crate::error::Result; use crate::util::get_files; mod arg; mod client; mod error; mod util; const HANDLER_MYSQL: &str = "mysql"; const HANDLER_HTTP: &str = "http"; const HANDLER_CLICKHOUSE: &str = "clickhouse"; pub struct Databend { client: Client, } impl Databend { pub fn create(client: Client) -> Self { Databend { client } } } #[async_trait::async_trait] impl sqllogictest::AsyncDB for Databend { type Error = DSqlLogicTestError; type ColumnType = DefaultColumnType; async fn run(&mut self, sql: &str) -> Result<DBOutput<Self::ColumnType>> { self.client.query(sql).await } fn engine_name(&self) -> &str { self.client.engine_name() } } #[tokio::main] pub async fn main() -> Result<()> { env_logger::init(); let args = SqlLogicTestArgs::parse(); let handlers = match &args.handlers { Some(hs) => hs.iter().map(|s| s.as_str()).collect(), None => vec![HANDLER_MYSQL, HANDLER_HTTP, HANDLER_CLICKHOUSE], }; for handler in handlers.iter() { match *handler { HANDLER_MYSQL => { run_mysql_client().await?; } HANDLER_HTTP => { run_http_client().await?; } HANDLER_CLICKHOUSE => { run_ck_http_client().await?; } _ => { return Err(format!("Unknown test handler: {handler}").into()); } } } Ok(()) } async fn run_mysql_client() -> Result<()> { println!( "MySQL client starts to run with: {:?}", SqlLogicTestArgs::parse() ); let suits = SqlLogicTestArgs::parse().suites; let suits = std::fs::read_dir(suits).unwrap(); run_suits(suits, ClientType::MySQL).await?; Ok(()) } async fn run_http_client() -> Result<()> { println!( "Http client starts to run with: {:?}", SqlLogicTestArgs::parse() ); let suits = SqlLogicTestArgs::parse().suites; let suits = std::fs::read_dir(suits).unwrap(); run_suits(suits, ClientType::Http).await?; Ok(()) } async fn run_ck_http_client() -> Result<()> { println!( "Clickhouse http client starts to run with: {:?}", SqlLogicTestArgs::parse() ); let suits = SqlLogicTestArgs::parse().suites; let suits = std::fs::read_dir(suits).unwrap(); run_suits(suits, ClientType::Clickhouse).await?; Ok(()) } // Create new databend with client type async fn create_databend(client_type: &ClientType) -> Result<Databend> { let mut client: Client; let args = SqlLogicTestArgs::parse(); match client_type { ClientType::MySQL => { let mut mysql_client = MySQLClient::create().await?; if args.tpch { mysql_client.enable_tpch(); } client = Client::MySQL(mysql_client); } ClientType::Http => { client = Client::Http(HttpClient::create()?); } ClientType::Clickhouse => { client = Client::Clickhouse(ClickhouseHttpClient::create()?); } } if args.enable_sandbox { client.create_sandbox().await?; } if args.debug { client.enable_debug(); } Ok(Databend::create(client)) } async fn run_suits(suits: ReadDir, client_type: ClientType) -> Result<()> { // Todo: set validator to process regex let args = SqlLogicTestArgs::parse(); let mut tasks = vec![]; let mut num_of_tests = 0; let start = Instant::now(); // Walk each suit dir and read all files in it // After get a slt file, set the file name to databend for suit in suits { // Get a suit and find all slt files in the suit let suit = suit.unwrap().path(); // Parse the suit and find all slt files let files = get_files(suit)?; for file in files.into_iter() { let file_name = file .as_ref() .unwrap() .path() .file_name() .unwrap() .to_str() .unwrap() .to_string(); if let Some(ref specific_file) = args.file { if !file_name.contains(specific_file) { continue; } } num_of_tests += parse_file::<DefaultColumnType>(file.as_ref().unwrap().path()) .unwrap() .len(); if args.complete { let col_separator = " "; let validator = default_validator; let column_validator = default_column_validator; let mut runner = Runner::new(create_databend(&client_type).await?); runner .update_test_file( file.unwrap().path(), col_separator, validator, column_validator, ) .await .unwrap(); } else { tasks.push(async move { run_file_async(&client_type, file.unwrap().path()).await }); } } } if args.complete { return Ok(()); } // Run all tasks parallel run_parallel_async(tasks, num_of_tests).await?; let duration = start.elapsed(); println!( "Run all tests[{}] using {} ms", num_of_tests, duration.as_millis() ); Ok(()) } async fn run_parallel_async( tasks: Vec<impl Future<Output = std::result::Result<Vec<TestError>, TestError>>>, num_of_tests: usize, ) -> Result<()> { let args = SqlLogicTestArgs::parse(); let jobs = tasks.len().clamp(1, args.parallel); let tasks = stream::iter(tasks).buffer_unordered(jobs); let no_fail_fast = args.no_fail_fast; if !no_fail_fast { let errors = tasks .filter_map(|result| async { result.err() }) .collect() .await; handle_error_records(errors, no_fail_fast, num_of_tests)?; } else { let errors: Vec<Vec<TestError>> = tasks .filter_map(|result| async { result.ok() }) .collect() .await; handle_error_records( errors.into_iter().flatten().collect(), no_fail_fast, num_of_tests, )?; } Ok(()) } async fn run_file_async( client_type: &ClientType, filename: impl AsRef<Path>, ) -> std::result::Result<Vec<TestError>, TestError> { let start = Instant::now(); println!( "Running {} test for file: {} ...", client_type, filename.as_ref().display() ); let mut error_records = vec![]; let no_fail_fast = SqlLogicTestArgs::parse().no_fail_fast; let records = parse_file(&filename).unwrap(); let mut runner = Runner::new(create_databend(client_type).await.unwrap()); for record in records.into_iter() { if let Record::Halt { .. } = record { break; } // Capture error record and continue to run next records if let Err(e) = runner.run_async(record).await { if no_fail_fast { error_records.push(e); } else { return Err(e); } } } let run_file_status = match error_records.is_empty() { true => "✅", false => "❌", }; if !SqlLogicTestArgs::parse().tpch { println!( "Completed {} test for file: {} {} ({:?})", client_type, filename.as_ref().display(), run_file_status, start.elapsed(), ); } Ok(error_records) } fn handle_error_records( error_records: Vec<TestError>, no_fail_fast: bool, num_of_tests: usize, ) -> Result<()> { if error_records.is_empty() { return Ok(()); } println!( "Test finished, fail fast {}, {} out of {} records failed to run", if no_fail_fast { "disabled" } else { "enabled" }, error_records.len(), num_of_tests ); for (idx, error_record) in error_records.iter().enumerate() { println!("{idx}: {}", error_record.display(true)); } Err(DSqlLogicTestError::SelfError( "sqllogictest failed".to_string(), )) }
// ar_enb: LTE eNodeB implementation in Rust #[allow(dead_code)] #[allow(non_snake_case)] #[allow(unused_variables)] #[allow(non_upper_case_globals)] #[allow(unused_imports)] extern crate ngr; // use ngr::rrc; // use ngr::pdcp; // use ngr::phy; use ngr::security::*; fn main() { // let mut l1 = phy::PhysicalLayer::new(); // println!("\nBefore\ncodeword: {:?}\nscrambled bits {:?}", l1.codeword, l1.scrambled_bits); // phy::scrambling::run(&mut l1); // println!("\nAfter\ncodeword: {:?}\nscrambled bits {:?}", l1.codeword, l1.scrambled_bits); let kenb: Vec<u128> = vec![45; 2]; let k: u64; k = kdf(kenb, ALGO_TYPE_RRC_INT, ALGO_ID_128_EIA2); println!("k: 0x0{:x}", k); }
use crate::clist::*; use crate::mailimf_types::*; use crate::x::*; pub const STATE_WORD: libc::c_uint = 1; pub const STATE_SPACE: libc::c_uint = 2; pub const STATE_BEGIN: libc::c_uint = 0; /* mailimf_string_write writes a string to a given stream @param f is the stream @param col (* col) is the column number where we will start to write the text, the ending column will be stored in (* col) @param str is the string to write */ pub unsafe fn mailimf_string_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut str: *const libc::c_char, mut length: size_t, ) -> libc::c_int { let mut r: libc::c_int = 0; let mut count: size_t = 0; let mut block_begin: *const libc::c_char = 0 as *const libc::c_char; let mut p: *const libc::c_char = 0 as *const libc::c_char; let mut done: libc::c_int = 0; p = str; block_begin = str; count = 0i32 as size_t; while length > 0i32 as libc::size_t { if count >= 998i32 as libc::size_t { r = flush_buf(do_write, data, block_begin, count); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = do_write.expect("non-null function pointer")( data, b"\r\n\x00" as *const u8 as *const libc::c_char, (::std::mem::size_of::<[libc::c_char; 3]>() as libc::size_t) .wrapping_sub(1i32 as libc::size_t), ); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } count = 0i32 as size_t; block_begin = p; *col = 0i32 } match *p as libc::c_int { 10 => { r = flush_buf(do_write, data, block_begin, count); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = do_write.expect("non-null function pointer")( data, b"\r\n\x00" as *const u8 as *const libc::c_char, (::std::mem::size_of::<[libc::c_char; 3]>() as libc::size_t) .wrapping_sub(1i32 as libc::size_t), ); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } p = p.offset(1isize); length = length.wrapping_sub(1); count = 0i32 as size_t; block_begin = p; *col = 0i32 } 13 => { done = 0i32; if length >= 2i32 as libc::size_t { if *p.offset(1isize) as libc::c_int == '\n' as i32 { r = flush_buf(do_write, data, block_begin, count); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = do_write.expect("non-null function pointer")( data, b"\r\n\x00" as *const u8 as *const libc::c_char, (::std::mem::size_of::<[libc::c_char; 3]>() as libc::size_t) .wrapping_sub(1i32 as libc::size_t), ); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } p = p.offset(2isize); length = (length as libc::size_t).wrapping_sub(2i32 as libc::size_t) as size_t as size_t; count = 0i32 as size_t; block_begin = p; *col = 0i32; done = 1i32 } } if 0 == done { r = flush_buf(do_write, data, block_begin, count); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = do_write.expect("non-null function pointer")( data, b"\r\n\x00" as *const u8 as *const libc::c_char, (::std::mem::size_of::<[libc::c_char; 3]>() as libc::size_t) .wrapping_sub(1i32 as libc::size_t), ); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } p = p.offset(1isize); length = length.wrapping_sub(1); count = 0i32 as size_t; block_begin = p; *col = 0i32 } } _ => { p = p.offset(1isize); count = count.wrapping_add(1); length = length.wrapping_sub(1) } } } r = flush_buf(do_write, data, block_begin, count); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *col = (*col as libc::size_t).wrapping_add(count) as libc::c_int as libc::c_int; return MAILIMF_NO_ERROR as libc::c_int; } /* ************************ */ #[inline] unsafe fn flush_buf( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut str: *const libc::c_char, mut length: size_t, ) -> libc::c_int { if length != 0i32 as libc::size_t { let mut r: libc::c_int = 0; if length > 0i32 as libc::size_t { r = do_write.expect("non-null function pointer")(data, str, length); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } } } return MAILIMF_NO_ERROR as libc::c_int; } /* mailimf_fields_write writes the fields to a given stream @param f is the stream @param col (* col) is the column number where we will start to write the text, the ending column will be stored in (* col) @param fields is the fields to write */ pub unsafe fn mailimf_fields_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut fields: *mut mailimf_fields, ) -> libc::c_int { let mut cur: *mut clistiter = 0 as *mut clistiter; cur = (*(*fields).fld_list).first; while !cur.is_null() { let mut r: libc::c_int = 0; r = mailimf_field_write_driver( do_write, data, col, (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut mailimf_field, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } return MAILIMF_NO_ERROR as libc::c_int; } /* mailimf_field_write writes a field to a given stream @param f is the stream @param col (* col) is the column number where we will start to write the text, the ending column will be stored in (* col) @param field is the field to write */ pub unsafe fn mailimf_field_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut field: *mut mailimf_field, ) -> libc::c_int { let mut r: libc::c_int = 0; match (*field).fld_type { 1 => { r = mailimf_return_write_driver(do_write, data, col, (*field).fld_data.fld_return_path) } 2 => { r = mailimf_resent_date_write_driver( do_write, data, col, (*field).fld_data.fld_resent_date, ) } 3 => { r = mailimf_resent_from_write_driver( do_write, data, col, (*field).fld_data.fld_resent_from, ) } 4 => { r = mailimf_resent_sender_write_driver( do_write, data, col, (*field).fld_data.fld_resent_sender, ) } 5 => { r = mailimf_resent_to_write_driver(do_write, data, col, (*field).fld_data.fld_resent_to) } 6 => { r = mailimf_resent_cc_write_driver(do_write, data, col, (*field).fld_data.fld_resent_cc) } 7 => { r = mailimf_resent_bcc_write_driver( do_write, data, col, (*field).fld_data.fld_resent_bcc, ) } 8 => { r = mailimf_resent_msg_id_write_driver( do_write, data, col, (*field).fld_data.fld_resent_msg_id, ) } 9 => { r = mailimf_orig_date_write_driver(do_write, data, col, (*field).fld_data.fld_orig_date) } 10 => r = mailimf_from_write_driver(do_write, data, col, (*field).fld_data.fld_from), 11 => r = mailimf_sender_write_driver(do_write, data, col, (*field).fld_data.fld_sender), 12 => { r = mailimf_reply_to_write_driver(do_write, data, col, (*field).fld_data.fld_reply_to) } 13 => r = mailimf_to_write_driver(do_write, data, col, (*field).fld_data.fld_to), 14 => r = mailimf_cc_write_driver(do_write, data, col, (*field).fld_data.fld_cc), 15 => r = mailimf_bcc_write_driver(do_write, data, col, (*field).fld_data.fld_bcc), 16 => { r = mailimf_message_id_write_driver( do_write, data, col, (*field).fld_data.fld_message_id, ) } 17 => { r = mailimf_in_reply_to_write_driver( do_write, data, col, (*field).fld_data.fld_in_reply_to, ) } 18 => { r = mailimf_references_write_driver( do_write, data, col, (*field).fld_data.fld_references, ) } 19 => r = mailimf_subject_write_driver(do_write, data, col, (*field).fld_data.fld_subject), 20 => { r = mailimf_comments_write_driver(do_write, data, col, (*field).fld_data.fld_comments) } 21 => { r = mailimf_keywords_write_driver(do_write, data, col, (*field).fld_data.fld_keywords) } 22 => { r = mailimf_optional_field_write_driver( do_write, data, col, (*field).fld_data.fld_optional_field, ) } _ => r = MAILIMF_ERROR_INVAL as libc::c_int, } if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_optional_field_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut field: *mut mailimf_optional_field, ) -> libc::c_int { let mut r: libc::c_int = 0; if strlen((*field).fld_name).wrapping_add(2i32 as libc::size_t) > 998i32 as libc::size_t { return MAILIMF_ERROR_INVAL as libc::c_int; } r = mailimf_string_write_driver( do_write, data, col, (*field).fld_name, strlen((*field).fld_name), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b": \x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_header_string_write_driver( do_write, data, col, (*field).fld_value, strlen((*field).fld_value), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } /* mailimf_header_string_write writes a header value and fold the header if needed. @param f is the stream @param col (* col) is the column number where we will start to write the text, the ending column will be stored in (* col) @param str is the string to write */ pub unsafe fn mailimf_header_string_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut str: *const libc::c_char, mut length: size_t, ) -> libc::c_int { let mut state: libc::c_int = 0; let mut p: *const libc::c_char = 0 as *const libc::c_char; let mut word_begin: *const libc::c_char = 0 as *const libc::c_char; let mut first: libc::c_int = 0; state = STATE_BEGIN as libc::c_int; p = str; word_begin = p; first = 1i32; while length > 0i32 as libc::size_t { match state { 0 => match *p as libc::c_int { 13 | 10 | 32 | 9 => { p = p.offset(1isize); length = length.wrapping_sub(1) } _ => { word_begin = p; state = STATE_WORD as libc::c_int } }, 2 => match *p as libc::c_int { 13 | 10 | 32 | 9 => { p = p.offset(1isize); length = length.wrapping_sub(1) } _ => { word_begin = p; state = STATE_WORD as libc::c_int } }, 1 => match *p as libc::c_int { 13 | 10 | 32 | 9 => { if p.wrapping_offset_from(word_begin) as libc::c_long + *col as libc::c_long + 1i32 as libc::c_long > 72i32 as libc::c_long { mailimf_string_write_driver( do_write, data, col, b"\r\n \x00" as *const u8 as *const libc::c_char, (::std::mem::size_of::<[libc::c_char; 4]>() as libc::size_t) .wrapping_sub(1i32 as libc::size_t), ); } else if 0 == first { mailimf_string_write_driver( do_write, data, col, b" \x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); } first = 0i32; mailimf_string_write_driver( do_write, data, col, word_begin, p.wrapping_offset_from(word_begin) as libc::c_long as size_t, ); state = STATE_SPACE as libc::c_int } _ => { if p.wrapping_offset_from(word_begin) as libc::c_long + *col as libc::c_long >= 998i32 as libc::c_long { mailimf_string_write_driver( do_write, data, col, word_begin, p.wrapping_offset_from(word_begin) as libc::c_long as size_t, ); mailimf_string_write_driver( do_write, data, col, b"\r\n \x00" as *const u8 as *const libc::c_char, (::std::mem::size_of::<[libc::c_char; 4]>() as libc::size_t) .wrapping_sub(1i32 as libc::size_t), ); word_begin = p } p = p.offset(1isize); length = length.wrapping_sub(1) } }, _ => {} } } if state == STATE_WORD as libc::c_int { if p.wrapping_offset_from(word_begin) as libc::c_long + *col as libc::c_long >= 72i32 as libc::c_long { mailimf_string_write_driver( do_write, data, col, b"\r\n \x00" as *const u8 as *const libc::c_char, (::std::mem::size_of::<[libc::c_char; 4]>() as libc::size_t) .wrapping_sub(1i32 as libc::size_t), ); } else if 0 == first { mailimf_string_write_driver( do_write, data, col, b" \x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); } first = 0i32; mailimf_string_write_driver( do_write, data, col, word_begin, p.wrapping_offset_from(word_begin) as libc::c_long as size_t, ); } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_keywords_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut keywords: *mut mailimf_keywords, ) -> libc::c_int { let mut r: libc::c_int = 0; let mut cur: *mut clistiter = 0 as *mut clistiter; let mut first: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Keywords: \x00" as *const u8 as *const libc::c_char, 10i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } first = 1i32; cur = (*(*keywords).kw_list).first; while !cur.is_null() { let mut keyword: *mut libc::c_char = 0 as *mut libc::c_char; let mut len: size_t = 0; keyword = (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut libc::c_char; len = strlen(keyword); if 0 == first { r = mailimf_string_write_driver( do_write, data, col, b", \x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } else { first = 0i32 } r = mailimf_header_string_write_driver(do_write, data, col, keyword, len); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_comments_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut comments: *mut mailimf_comments, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Comments: \x00" as *const u8 as *const libc::c_char, 10i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_header_string_write_driver( do_write, data, col, (*comments).cm_value, strlen((*comments).cm_value), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_subject_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut subject: *mut mailimf_subject, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Subject: \x00" as *const u8 as *const libc::c_char, 9i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_header_string_write_driver( do_write, data, col, (*subject).sbj_value, strlen((*subject).sbj_value), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_references_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut references: *mut mailimf_references, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"References: \x00" as *const u8 as *const libc::c_char, 12i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_msg_id_list_write_driver(do_write, data, col, (*references).mid_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_msg_id_list_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut mid_list: *mut clist, ) -> libc::c_int { let mut cur: *mut clistiter = 0 as *mut clistiter; let mut r: libc::c_int = 0; let mut first: libc::c_int = 0; first = 1i32; cur = (*mid_list).first; while !cur.is_null() { let mut msgid: *mut libc::c_char = 0 as *mut libc::c_char; let mut len: size_t = 0; msgid = (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut libc::c_char; len = strlen(msgid); if 0 == first { if *col > 1i32 { if (*col as libc::size_t).wrapping_add(len) >= 72i32 as libc::size_t { r = mailimf_string_write_driver( do_write, data, col, b"\r\n \x00" as *const u8 as *const libc::c_char, 3i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } first = 1i32 } } } if 0 == first { r = mailimf_string_write_driver( do_write, data, col, b" \x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } else { first = 0i32 } r = mailimf_string_write_driver( do_write, data, col, b"<\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver(do_write, data, col, msgid, len); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b">\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_in_reply_to_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut in_reply_to: *mut mailimf_in_reply_to, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"In-Reply-To: \x00" as *const u8 as *const libc::c_char, 13i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_msg_id_list_write_driver(do_write, data, col, (*in_reply_to).mid_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_message_id_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut message_id: *mut mailimf_message_id, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Message-ID: \x00" as *const u8 as *const libc::c_char, 12i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"<\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, (*message_id).mid_value, strlen((*message_id).mid_value), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b">\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_bcc_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut bcc: *mut mailimf_bcc, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Bcc: \x00" as *const u8 as *const libc::c_char, 5i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } if !(*bcc).bcc_addr_list.is_null() { r = mailimf_address_list_write_driver(do_write, data, col, (*bcc).bcc_addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailimf_address_list_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut addr_list: *mut mailimf_address_list, ) -> libc::c_int { let mut cur: *mut clistiter = 0 as *mut clistiter; let mut r: libc::c_int = 0; let mut first: libc::c_int = 0; first = 1i32; cur = (*(*addr_list).ad_list).first; while !cur.is_null() { let mut addr: *mut mailimf_address = 0 as *mut mailimf_address; addr = (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut mailimf_address; if 0 == first { r = mailimf_string_write_driver( do_write, data, col, b", \x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } else { first = 0i32 } r = mailimf_address_write_driver(do_write, data, col, addr); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_address_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut addr: *mut mailimf_address, ) -> libc::c_int { let mut r: libc::c_int = 0; match (*addr).ad_type { 1 => { r = mailimf_mailbox_write_driver(do_write, data, col, (*addr).ad_data.ad_mailbox); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } 2 => { r = mailimf_group_write_driver(do_write, data, col, (*addr).ad_data.ad_group); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } _ => {} } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_group_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut group: *mut mailimf_group, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_header_string_write_driver( do_write, data, col, (*group).grp_display_name, strlen((*group).grp_display_name), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b": \x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } if !(*group).grp_mb_list.is_null() { r = mailimf_mailbox_list_write_driver(do_write, data, col, (*group).grp_mb_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } r = mailimf_string_write_driver( do_write, data, col, b";\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailimf_mailbox_list_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut mb_list: *mut mailimf_mailbox_list, ) -> libc::c_int { let mut cur: *mut clistiter = 0 as *mut clistiter; let mut r: libc::c_int = 0; let mut first: libc::c_int = 0; first = 1i32; cur = (*(*mb_list).mb_list).first; while !cur.is_null() { let mut mb: *mut mailimf_mailbox = 0 as *mut mailimf_mailbox; mb = (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut mailimf_mailbox; if 0 == first { r = mailimf_string_write_driver( do_write, data, col, b", \x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } else { first = 0i32 } r = mailimf_mailbox_write_driver(do_write, data, col, mb); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_mailbox_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut mb: *mut mailimf_mailbox, ) -> libc::c_int { let mut r: libc::c_int = 0; let mut do_fold: libc::c_int = 0; if !(*mb).mb_display_name.is_null() { if 0 != is_atext((*mb).mb_display_name) { r = mailimf_header_string_write_driver( do_write, data, col, (*mb).mb_display_name, strlen((*mb).mb_display_name), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } else { if !(*mb).mb_display_name.is_null() { if (*col as libc::size_t).wrapping_add(strlen((*mb).mb_display_name)) >= 72i32 as libc::size_t { r = mailimf_string_write_driver( do_write, data, col, b"\r\n \x00" as *const u8 as *const libc::c_char, 3i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } } if strlen((*mb).mb_display_name) > (998i32 / 2i32) as libc::size_t { return MAILIMF_ERROR_INVAL as libc::c_int; } r = mailimf_quoted_string_write_driver( do_write, data, col, (*mb).mb_display_name, strlen((*mb).mb_display_name), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } do_fold = 0i32; if *col > 1i32 { if (*col as libc::size_t) .wrapping_add(strlen((*mb).mb_addr_spec)) .wrapping_add(3i32 as libc::size_t) >= 72i32 as libc::size_t { r = mailimf_string_write_driver( do_write, data, col, b"\r\n \x00" as *const u8 as *const libc::c_char, 3i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } do_fold = 1i32 } } if 0 != do_fold { r = mailimf_string_write_driver( do_write, data, col, b"<\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ) } else { r = mailimf_string_write_driver( do_write, data, col, b" <\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ) } if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, (*mb).mb_addr_spec, strlen((*mb).mb_addr_spec), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b">\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } else { if (*col as libc::size_t).wrapping_add(strlen((*mb).mb_addr_spec)) >= 72i32 as libc::size_t { r = mailimf_string_write_driver( do_write, data, col, b"\r\n \x00" as *const u8 as *const libc::c_char, 3i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } r = mailimf_string_write_driver( do_write, data, col, (*mb).mb_addr_spec, strlen((*mb).mb_addr_spec), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } return MAILIMF_NO_ERROR as libc::c_int; } /* mailimf_quoted_string_write writes a string that is quoted to a given stream @param f is the stream @param col (* col) is the column number where we will start to write the text, the ending column will be stored in (* col) @param string is the string to quote and write */ pub unsafe fn mailimf_quoted_string_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut string: *const libc::c_char, mut len: size_t, ) -> libc::c_int { let mut r: libc::c_int = 0; let mut i: size_t = 0; r = do_write.expect("non-null function pointer")( data, b"\"\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } i = 0i32 as size_t; while i < len { match *string.offset(i as isize) as libc::c_int { 92 | 34 => { r = do_write.expect("non-null function pointer")( data, b"\\\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } r = do_write.expect("non-null function pointer")( data, &*string.offset(i as isize), 1i32 as size_t, ); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } *col += 2i32 } _ => { r = do_write.expect("non-null function pointer")( data, &*string.offset(i as isize), 1i32 as size_t, ); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } *col += 1 } } i = i.wrapping_add(1) } r = do_write.expect("non-null function pointer")( data, b"\"\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r == 0i32 { return MAILIMF_ERROR_FILE as libc::c_int; } return MAILIMF_NO_ERROR as libc::c_int; } /* static int atext = ALPHA / DIGIT / ; Any character except controls, "!" / "#" / ; SP, and specials. "$" / "%" / ; Used for atoms "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" */ unsafe fn is_atext(mut s: *const libc::c_char) -> libc::c_int { let mut p: *const libc::c_char = 0 as *const libc::c_char; p = s; while *p as libc::c_int != 0i32 { if !(0 != isalpha(*p as libc::c_uchar as libc::c_int)) { if !(0 != isdigit(*p as libc::c_uchar as libc::c_int)) { match *p as libc::c_int { 32 | 9 | 33 | 35 | 36 | 37 | 38 | 39 | 42 | 43 | 45 | 47 | 61 | 63 | 94 | 95 | 96 | 123 | 124 | 125 | 126 => {} _ => return 0i32, } } } p = p.offset(1isize) } return 1i32; } unsafe fn mailimf_cc_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut cc: *mut mailimf_cc, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Cc: \x00" as *const u8 as *const libc::c_char, 4i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_address_list_write_driver(do_write, data, col, (*cc).cc_addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_to_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut to: *mut mailimf_to, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"To: \x00" as *const u8 as *const libc::c_char, 4i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_address_list_write_driver(do_write, data, col, (*to).to_addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_reply_to_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut reply_to: *mut mailimf_reply_to, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Reply-To: \x00" as *const u8 as *const libc::c_char, 10i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_address_list_write_driver(do_write, data, col, (*reply_to).rt_addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_sender_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut sender: *mut mailimf_sender, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Sender: \x00" as *const u8 as *const libc::c_char, 8i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_mailbox_write_driver(do_write, data, col, (*sender).snd_mb); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_from_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut from: *mut mailimf_from, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"From: \x00" as *const u8 as *const libc::c_char, 6i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_mailbox_list_write_driver(do_write, data, col, (*from).frm_mb_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } /* * libEtPan! -- a mail stuff library * * Copyright (C) 2001, 2005 - DINH Viet Hoa * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the libEtPan! project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id: mailimf_write_generic.c,v 1.3 2006/05/22 13:39:42 hoa Exp $ */ unsafe fn mailimf_orig_date_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut date: *mut mailimf_orig_date, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Date: \x00" as *const u8 as *const libc::c_char, 6i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_date_time_write_driver(do_write, data, col, (*date).dt_date_time); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_date_time_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut date_time: *mut mailimf_date_time, ) -> libc::c_int { let mut r: libc::c_int = 0; let mut date_str: [libc::c_char; 256] = [0; 256]; let mut wday: libc::c_int = 0; wday = dayofweek( (*date_time).dt_year, (*date_time).dt_month, (*date_time).dt_day, ); snprintf( date_str.as_mut_ptr(), 256i32 as libc::size_t, b"%s, %i %s %i %02i:%02i:%02i %+05i\x00" as *const u8 as *const libc::c_char, week_of_day_str[wday as usize], (*date_time).dt_day, month_str[((*date_time).dt_month - 1i32) as usize], (*date_time).dt_year, (*date_time).dt_hour, (*date_time).dt_min, (*date_time).dt_sec, (*date_time).dt_zone, ); r = mailimf_string_write_driver( do_write, data, col, date_str.as_mut_ptr(), strlen(date_str.as_mut_ptr()), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } static mut month_str: [*const libc::c_char; 12] = [ b"Jan\x00" as *const u8 as *const libc::c_char, b"Feb\x00" as *const u8 as *const libc::c_char, b"Mar\x00" as *const u8 as *const libc::c_char, b"Apr\x00" as *const u8 as *const libc::c_char, b"May\x00" as *const u8 as *const libc::c_char, b"Jun\x00" as *const u8 as *const libc::c_char, b"Jul\x00" as *const u8 as *const libc::c_char, b"Aug\x00" as *const u8 as *const libc::c_char, b"Sep\x00" as *const u8 as *const libc::c_char, b"Oct\x00" as *const u8 as *const libc::c_char, b"Nov\x00" as *const u8 as *const libc::c_char, b"Dec\x00" as *const u8 as *const libc::c_char, ]; static mut week_of_day_str: [*const libc::c_char; 7] = [ b"Sun\x00" as *const u8 as *const libc::c_char, b"Mon\x00" as *const u8 as *const libc::c_char, b"Tue\x00" as *const u8 as *const libc::c_char, b"Wed\x00" as *const u8 as *const libc::c_char, b"Thu\x00" as *const u8 as *const libc::c_char, b"Fri\x00" as *const u8 as *const libc::c_char, b"Sat\x00" as *const u8 as *const libc::c_char, ]; /* 0 = Sunday */ /* y > 1752 */ unsafe fn dayofweek( mut year: libc::c_int, mut month: libc::c_int, mut day: libc::c_int, ) -> libc::c_int { static mut offset: [libc::c_int; 12] = [ 0i32, 3i32, 2i32, 5i32, 0i32, 3i32, 5i32, 1i32, 4i32, 6i32, 2i32, 4i32, ]; year -= (month < 3i32) as libc::c_int; return (year + year / 4i32 - year / 100i32 + year / 400i32 + offset[(month - 1i32) as usize] + day) % 7i32; } unsafe fn mailimf_resent_msg_id_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut message_id: *mut mailimf_message_id, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Resent-Message-ID: \x00" as *const u8 as *const libc::c_char, 19i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"<\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, (*message_id).mid_value, strlen((*message_id).mid_value), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b">\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_resent_bcc_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut bcc: *mut mailimf_bcc, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Resent-Bcc: \x00" as *const u8 as *const libc::c_char, 12i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } if !(*bcc).bcc_addr_list.is_null() { r = mailimf_address_list_write_driver(do_write, data, col, (*bcc).bcc_addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_resent_cc_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut cc: *mut mailimf_cc, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Resent-Cc: \x00" as *const u8 as *const libc::c_char, 11i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_address_list_write_driver(do_write, data, col, (*cc).cc_addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_resent_to_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut to: *mut mailimf_to, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Resent-To: \x00" as *const u8 as *const libc::c_char, 11i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_address_list_write_driver(do_write, data, col, (*to).to_addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_resent_sender_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut sender: *mut mailimf_sender, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Resent-Sender: \x00" as *const u8 as *const libc::c_char, 15i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_mailbox_write_driver(do_write, data, col, (*sender).snd_mb); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_resent_from_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut from: *mut mailimf_from, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Resent-From: \x00" as *const u8 as *const libc::c_char, 13i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_mailbox_list_write_driver(do_write, data, col, (*from).frm_mb_list); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_resent_date_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut date: *mut mailimf_orig_date, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Resent-Date: \x00" as *const u8 as *const libc::c_char, 13i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_date_time_write_driver(do_write, data, col, (*date).dt_date_time); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_return_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut return_path: *mut mailimf_return, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"Return-Path: \x00" as *const u8 as *const libc::c_char, 13i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_path_write_driver(do_write, data, col, (*return_path).ret_path); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_string_write_driver( do_write, data, col, b"\r\n\x00" as *const u8 as *const libc::c_char, 2i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_path_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut path: *mut mailimf_path, ) -> libc::c_int { let mut r: libc::c_int = 0; r = mailimf_string_write_driver( do_write, data, col, b"<\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } if !(*path).pt_addr_spec.is_null() { r = mailimf_string_write_driver( do_write, data, col, (*path).pt_addr_spec, strlen((*path).pt_addr_spec), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } r = mailimf_string_write_driver( do_write, data, col, b">\x00" as *const u8 as *const libc::c_char, 1i32 as size_t, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } return MAILIMF_NO_ERROR as libc::c_int; } /* mailimf_envelope_fields_write writes only some fields to a given stream @param f is the stream @param col (* col) is the column number where we will start to write the text, the ending column will be stored in (* col) @param fields is the fields to write */ pub unsafe fn mailimf_envelope_fields_write_driver( mut do_write: Option< unsafe fn(_: *mut libc::c_void, _: *const libc::c_char, _: size_t) -> libc::c_int, >, mut data: *mut libc::c_void, mut col: *mut libc::c_int, mut fields: *mut mailimf_fields, ) -> libc::c_int { let mut cur: *mut clistiter = 0 as *mut clistiter; cur = (*(*fields).fld_list).first; while !cur.is_null() { let mut r: libc::c_int = 0; let mut field: *mut mailimf_field = 0 as *mut mailimf_field; field = (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut mailimf_field; if (*field).fld_type != MAILIMF_FIELD_OPTIONAL_FIELD as libc::c_int { r = mailimf_field_write_driver(do_write, data, col, field); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } return MAILIMF_NO_ERROR as libc::c_int; }
use std::fs::File; use xmltree::Element; fn main() -> Result<(), anyhow::Error> { let data: &'static str = r##" <?xml version="1.0" encoding="utf-8" standalone="yes"?> <names> <name first="bob" last="jones" /> <name first="elizabeth" last="smith" /> </names> "##; let mut names_element = Element::parse(data.as_bytes()).unwrap(); println!("{:#?}", names_element); { // get first `name` element let name = names_element .get_mut_child("name") .expect("Can't find name element"); name.attributes.insert("suffix".to_owned(), "mr".to_owned()); } names_element.write(std::io::stdout())?; Ok(()) }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qstatusbar.h // dst-file: /src/widgets/qstatusbar.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::qwidget::*; // 773 use std::ops::Deref; use super::super::core::qstring::*; // 771 use super::super::core::qobjectdefs::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QStatusBar_Class_Size() -> c_int; // proto: void QStatusBar::~QStatusBar(); fn C_ZN10QStatusBarD2Ev(qthis: u64 /* *mut c_void*/); // proto: int QStatusBar::insertPermanentWidget(int index, QWidget * widget, int stretch); fn C_ZN10QStatusBar21insertPermanentWidgetEiP7QWidgeti(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void, arg2: c_int) -> c_int; // proto: void QStatusBar::removeWidget(QWidget * widget); fn C_ZN10QStatusBar12removeWidgetEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QStatusBar::setSizeGripEnabled(bool ); fn C_ZN10QStatusBar18setSizeGripEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QStatusBar::addPermanentWidget(QWidget * widget, int stretch); fn C_ZN10QStatusBar18addPermanentWidgetEP7QWidgeti(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int); // proto: bool QStatusBar::isSizeGripEnabled(); fn C_ZNK10QStatusBar17isSizeGripEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QStatusBar::clearMessage(); fn C_ZN10QStatusBar12clearMessageEv(qthis: u64 /* *mut c_void*/); // proto: QString QStatusBar::currentMessage(); fn C_ZNK10QStatusBar14currentMessageEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: const QMetaObject * QStatusBar::metaObject(); fn C_ZNK10QStatusBar10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QStatusBar::showMessage(const QString & text, int timeout); fn C_ZN10QStatusBar11showMessageERK7QStringi(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int); // proto: int QStatusBar::insertWidget(int index, QWidget * widget, int stretch); fn C_ZN10QStatusBar12insertWidgetEiP7QWidgeti(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void, arg2: c_int) -> c_int; // proto: void QStatusBar::addWidget(QWidget * widget, int stretch); fn C_ZN10QStatusBar9addWidgetEP7QWidgeti(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int); // proto: void QStatusBar::QStatusBar(QWidget * parent); fn C_ZN10QStatusBarC2EP7QWidget(arg0: *mut c_void) -> u64; fn QStatusBar_SlotProxy_connect__ZN10QStatusBar14messageChangedERK7QString(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QStatusBar)=1 #[derive(Default)] pub struct QStatusBar { qbase: QWidget, pub qclsinst: u64 /* *mut c_void*/, pub _messageChanged: QStatusBar_messageChanged_signal, } impl /*struct*/ QStatusBar { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QStatusBar { return QStatusBar{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QStatusBar { type Target = QWidget; fn deref(&self) -> &QWidget { return & self.qbase; } } impl AsRef<QWidget> for QStatusBar { fn as_ref(& self) -> & QWidget { return & self.qbase; } } // proto: void QStatusBar::~QStatusBar(); impl /*struct*/ QStatusBar { pub fn free<RetType, T: QStatusBar_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QStatusBar_free<RetType> { fn free(self , rsthis: & QStatusBar) -> RetType; } // proto: void QStatusBar::~QStatusBar(); impl<'a> /*trait*/ QStatusBar_free<()> for () { fn free(self , rsthis: & QStatusBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBarD2Ev()}; unsafe {C_ZN10QStatusBarD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: int QStatusBar::insertPermanentWidget(int index, QWidget * widget, int stretch); impl /*struct*/ QStatusBar { pub fn insertPermanentWidget<RetType, T: QStatusBar_insertPermanentWidget<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertPermanentWidget(self); // return 1; } } pub trait QStatusBar_insertPermanentWidget<RetType> { fn insertPermanentWidget(self , rsthis: & QStatusBar) -> RetType; } // proto: int QStatusBar::insertPermanentWidget(int index, QWidget * widget, int stretch); impl<'a> /*trait*/ QStatusBar_insertPermanentWidget<i32> for (i32, &'a QWidget, Option<i32>) { fn insertPermanentWidget(self , rsthis: & QStatusBar) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBar21insertPermanentWidgetEiP7QWidgeti()}; let arg0 = self.0 as c_int; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = (if self.2.is_none() {0} else {self.2.unwrap()}) as c_int; let mut ret = unsafe {C_ZN10QStatusBar21insertPermanentWidgetEiP7QWidgeti(rsthis.qclsinst, arg0, arg1, arg2)}; return ret as i32; // 1 // return 1; } } // proto: void QStatusBar::removeWidget(QWidget * widget); impl /*struct*/ QStatusBar { pub fn removeWidget<RetType, T: QStatusBar_removeWidget<RetType>>(& self, overload_args: T) -> RetType { return overload_args.removeWidget(self); // return 1; } } pub trait QStatusBar_removeWidget<RetType> { fn removeWidget(self , rsthis: & QStatusBar) -> RetType; } // proto: void QStatusBar::removeWidget(QWidget * widget); impl<'a> /*trait*/ QStatusBar_removeWidget<()> for (&'a QWidget) { fn removeWidget(self , rsthis: & QStatusBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBar12removeWidgetEP7QWidget()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QStatusBar12removeWidgetEP7QWidget(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QStatusBar::setSizeGripEnabled(bool ); impl /*struct*/ QStatusBar { pub fn setSizeGripEnabled<RetType, T: QStatusBar_setSizeGripEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setSizeGripEnabled(self); // return 1; } } pub trait QStatusBar_setSizeGripEnabled<RetType> { fn setSizeGripEnabled(self , rsthis: & QStatusBar) -> RetType; } // proto: void QStatusBar::setSizeGripEnabled(bool ); impl<'a> /*trait*/ QStatusBar_setSizeGripEnabled<()> for (i8) { fn setSizeGripEnabled(self , rsthis: & QStatusBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBar18setSizeGripEnabledEb()}; let arg0 = self as c_char; unsafe {C_ZN10QStatusBar18setSizeGripEnabledEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QStatusBar::addPermanentWidget(QWidget * widget, int stretch); impl /*struct*/ QStatusBar { pub fn addPermanentWidget<RetType, T: QStatusBar_addPermanentWidget<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addPermanentWidget(self); // return 1; } } pub trait QStatusBar_addPermanentWidget<RetType> { fn addPermanentWidget(self , rsthis: & QStatusBar) -> RetType; } // proto: void QStatusBar::addPermanentWidget(QWidget * widget, int stretch); impl<'a> /*trait*/ QStatusBar_addPermanentWidget<()> for (&'a QWidget, Option<i32>) { fn addPermanentWidget(self , rsthis: & QStatusBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBar18addPermanentWidgetEP7QWidgeti()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {0} else {self.1.unwrap()}) as c_int; unsafe {C_ZN10QStatusBar18addPermanentWidgetEP7QWidgeti(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: bool QStatusBar::isSizeGripEnabled(); impl /*struct*/ QStatusBar { pub fn isSizeGripEnabled<RetType, T: QStatusBar_isSizeGripEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isSizeGripEnabled(self); // return 1; } } pub trait QStatusBar_isSizeGripEnabled<RetType> { fn isSizeGripEnabled(self , rsthis: & QStatusBar) -> RetType; } // proto: bool QStatusBar::isSizeGripEnabled(); impl<'a> /*trait*/ QStatusBar_isSizeGripEnabled<i8> for () { fn isSizeGripEnabled(self , rsthis: & QStatusBar) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QStatusBar17isSizeGripEnabledEv()}; let mut ret = unsafe {C_ZNK10QStatusBar17isSizeGripEnabledEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QStatusBar::clearMessage(); impl /*struct*/ QStatusBar { pub fn clearMessage<RetType, T: QStatusBar_clearMessage<RetType>>(& self, overload_args: T) -> RetType { return overload_args.clearMessage(self); // return 1; } } pub trait QStatusBar_clearMessage<RetType> { fn clearMessage(self , rsthis: & QStatusBar) -> RetType; } // proto: void QStatusBar::clearMessage(); impl<'a> /*trait*/ QStatusBar_clearMessage<()> for () { fn clearMessage(self , rsthis: & QStatusBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBar12clearMessageEv()}; unsafe {C_ZN10QStatusBar12clearMessageEv(rsthis.qclsinst)}; // return 1; } } // proto: QString QStatusBar::currentMessage(); impl /*struct*/ QStatusBar { pub fn currentMessage<RetType, T: QStatusBar_currentMessage<RetType>>(& self, overload_args: T) -> RetType { return overload_args.currentMessage(self); // return 1; } } pub trait QStatusBar_currentMessage<RetType> { fn currentMessage(self , rsthis: & QStatusBar) -> RetType; } // proto: QString QStatusBar::currentMessage(); impl<'a> /*trait*/ QStatusBar_currentMessage<QString> for () { fn currentMessage(self , rsthis: & QStatusBar) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QStatusBar14currentMessageEv()}; let mut ret = unsafe {C_ZNK10QStatusBar14currentMessageEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QStatusBar::metaObject(); impl /*struct*/ QStatusBar { pub fn metaObject<RetType, T: QStatusBar_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QStatusBar_metaObject<RetType> { fn metaObject(self , rsthis: & QStatusBar) -> RetType; } // proto: const QMetaObject * QStatusBar::metaObject(); impl<'a> /*trait*/ QStatusBar_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QStatusBar) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QStatusBar10metaObjectEv()}; let mut ret = unsafe {C_ZNK10QStatusBar10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QStatusBar::showMessage(const QString & text, int timeout); impl /*struct*/ QStatusBar { pub fn showMessage<RetType, T: QStatusBar_showMessage<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showMessage(self); // return 1; } } pub trait QStatusBar_showMessage<RetType> { fn showMessage(self , rsthis: & QStatusBar) -> RetType; } // proto: void QStatusBar::showMessage(const QString & text, int timeout); impl<'a> /*trait*/ QStatusBar_showMessage<()> for (&'a QString, Option<i32>) { fn showMessage(self , rsthis: & QStatusBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBar11showMessageERK7QStringi()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {0} else {self.1.unwrap()}) as c_int; unsafe {C_ZN10QStatusBar11showMessageERK7QStringi(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: int QStatusBar::insertWidget(int index, QWidget * widget, int stretch); impl /*struct*/ QStatusBar { pub fn insertWidget<RetType, T: QStatusBar_insertWidget<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertWidget(self); // return 1; } } pub trait QStatusBar_insertWidget<RetType> { fn insertWidget(self , rsthis: & QStatusBar) -> RetType; } // proto: int QStatusBar::insertWidget(int index, QWidget * widget, int stretch); impl<'a> /*trait*/ QStatusBar_insertWidget<i32> for (i32, &'a QWidget, Option<i32>) { fn insertWidget(self , rsthis: & QStatusBar) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBar12insertWidgetEiP7QWidgeti()}; let arg0 = self.0 as c_int; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = (if self.2.is_none() {0} else {self.2.unwrap()}) as c_int; let mut ret = unsafe {C_ZN10QStatusBar12insertWidgetEiP7QWidgeti(rsthis.qclsinst, arg0, arg1, arg2)}; return ret as i32; // 1 // return 1; } } // proto: void QStatusBar::addWidget(QWidget * widget, int stretch); impl /*struct*/ QStatusBar { pub fn addWidget<RetType, T: QStatusBar_addWidget<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addWidget(self); // return 1; } } pub trait QStatusBar_addWidget<RetType> { fn addWidget(self , rsthis: & QStatusBar) -> RetType; } // proto: void QStatusBar::addWidget(QWidget * widget, int stretch); impl<'a> /*trait*/ QStatusBar_addWidget<()> for (&'a QWidget, Option<i32>) { fn addWidget(self , rsthis: & QStatusBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBar9addWidgetEP7QWidgeti()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {0} else {self.1.unwrap()}) as c_int; unsafe {C_ZN10QStatusBar9addWidgetEP7QWidgeti(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QStatusBar::QStatusBar(QWidget * parent); impl /*struct*/ QStatusBar { pub fn new<T: QStatusBar_new>(value: T) -> QStatusBar { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QStatusBar_new { fn new(self) -> QStatusBar; } // proto: void QStatusBar::QStatusBar(QWidget * parent); impl<'a> /*trait*/ QStatusBar_new for (Option<&'a QWidget>) { fn new(self) -> QStatusBar { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QStatusBarC2EP7QWidget()}; let ctysz: c_int = unsafe{QStatusBar_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN10QStatusBarC2EP7QWidget(arg0)}; let rsthis = QStatusBar{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } #[derive(Default)] // for QStatusBar_messageChanged pub struct QStatusBar_messageChanged_signal{poi:u64} impl /* struct */ QStatusBar { pub fn messageChanged(&self) -> QStatusBar_messageChanged_signal { return QStatusBar_messageChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QStatusBar_messageChanged_signal { pub fn connect<T: QStatusBar_messageChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QStatusBar_messageChanged_signal_connect { fn connect(self, sigthis: QStatusBar_messageChanged_signal); } // messageChanged(const class QString &) extern fn QStatusBar_messageChanged_signal_connect_cb_0(rsfptr:fn(QString), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QString::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QStatusBar_messageChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QString)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QString::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QStatusBar_messageChanged_signal_connect for fn(QString) { fn connect(self, sigthis: QStatusBar_messageChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QStatusBar_messageChanged_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QStatusBar_SlotProxy_connect__ZN10QStatusBar14messageChangedERK7QString(arg0, arg1, arg2)}; } } impl /* trait */ QStatusBar_messageChanged_signal_connect for Box<Fn(QString)> { fn connect(self, sigthis: QStatusBar_messageChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QStatusBar_messageChanged_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QStatusBar_SlotProxy_connect__ZN10QStatusBar14messageChangedERK7QString(arg0, arg1, arg2)}; } } // <= body block end
use serde::{Serialize, Deserialize, Deserializer}; use serde::de::Visitor; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct NBT(nbt::Blob); #[derive(Debug, Clone, Deserialize, Serialize)] pub struct GZIPNBT(nbt::Blob);
use near_sdk::{json_types::U128, AccountId}; use near_sdk::{serde_json::json, PendingContractTx}; use near_sdk_sim::*; use oysterpack_near_stake_token::domain::{Gas, YoctoNear}; use oysterpack_near_stake_token::interface::StakeAccount; use oysterpack_near_stake_token::near::NO_DEPOSIT; pub fn owner_id(contract_account_id: &str, user: &UserAccount) -> AccountId { let result = user.view(PendingContractTx::new( contract_account_id, "owner_id", json!({}), true, )); result.unwrap_json() }
use std::ops; use channel::ChannelFormatCast; pub trait ColorChannel { type Format: Clone + PartialEq + PartialOrd + Default + ops::Add<Self::Format, Output = Self::Format> + ops::Sub<Self::Format, Output = Self::Format>; type Scalar; type Tag; fn min_bound() -> Self::Format; fn max_bound() -> Self::Format; fn clamp(&self, min: Self::Format, max: Self::Format) -> Self; fn value(&self) -> Self::Format; fn scalar(&self) -> Self::Scalar; fn from_scalar(value: Self::Scalar) -> Self; fn new(value: Self::Format) -> Self; } pub trait ChannelCast: ColorChannel { fn channel_cast<To>(self) -> To where Self::Format: ChannelFormatCast<To::Format>, To: ColorChannel<Tag = Self::Tag>; fn scalar_cast<To>(self) -> To where Self::Format: ChannelFormatCast<To>; }
extern crate image; extern crate num; extern crate graphics; use image::ImageDecoder; use std::fmt; use std::env; use std::error; use std::fs::File; fn main() { println!("editing an image"); match run_app() { Ok(()) => println!("ran successfully"), Err(err) => println!("error: {} (reason: {})", err, err.description()), } println!("done editing"); } fn run_app() -> Result<(), Box<error::Error>> { let args: Vec<String> = env::args().collect(); if args.len() <= 1 { return Err(Box::new(Error::ArgError {})); } let filename = args[1].as_str(); let f = try!(File::open(filename)); let mut decoder = image::png::PNGDecoder::new(f); let (width, height) = try!(decoder.dimensions()); let im = try!(decoder.read_image()); let u8image = try!(match im { image::DecodingResult::U8(u8im) => Ok(u8im), image::DecodingResult::U16(_) => Err(Error::U8OnlyError {}), }); let tex_def = graphics::TextureSetupDefinition { width: width, height: height, data: u8image, }; let mut screen_width = 600; let mut screen_height = 600; let mut app = try!(graphics::App::new(screen_width, screen_height, "Picture Viewer", graphics::RenderingSource::TextureRenderingSource { tex_def: tex_def, })); loop { match app.handle_events() { Some(graphics::Action::Closed) => break, Some(graphics::Action::Resized(w, h)) => { screen_width = w; screen_height = h; } None => (), } let (lower_x, upper_x, lower_y, upper_y) = calc_position(width, height, screen_width, screen_height); let rects: Vec<Box<graphics::VertexSpecable>> = vec![Box::new(graphics::TexRect::new(lower_x, upper_x, lower_y, upper_y))]; app.draw(&rects); } app.close(); return Ok(()); } fn calc_position(image_w: u32, image_h: u32, screen_w: u32, screen_h: u32) -> (f32, f32, f32, f32) { let f_image_h = f32::from(image_h as u16); let f_image_w = f32::from(image_w as u16); let f_screen_h = f32::from(screen_h as u16); let f_screen_w = f32::from(screen_w as u16); let image_ratio = f_image_w / f_image_h; let screen_ratio = f_screen_w / f_screen_h; if image_ratio > screen_ratio { let half = (f_screen_h - ((f_screen_w / f_image_w) * f_image_h)) / (f_screen_h); return (-1.0, 1.0, -1.0 + half, 1.0 - half); } else { let half = (f_screen_w - ((f_screen_h / f_image_h) * f_image_w)) / (f_screen_w); return (-1.0 + half, 1.0 - half, -1.0, 1.0); } } #[derive(Debug)] enum Error { U8OnlyError, ArgError, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::U8OnlyError => write!(f, "can only accept u8 for the image"), Error::ArgError => write!(f, "must supply png to load"), } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::U8OnlyError => "can only accept u8 for the image", Error::ArgError => "must supply png to load", } } }
///! "Interface" tests for pin store, maybe more later use crate::repo::DataStore; use std::path::PathBuf; use std::sync::Arc; use tempfile::TempDir; pub struct DSTestContext<T> { #[allow(dead_code)] tempdir: TempDir, datastore: Arc<T>, } impl<T: DataStore> DSTestContext<T> { /// Create the test context which holds the DataStore inside an Arc and deletes the temporary /// directory on drop. pub async fn with<F>(factory: F) -> Self where F: FnOnce(PathBuf) -> T, { let tempdir = TempDir::new().expect("tempdir creation failed"); let p = tempdir.path().to_owned(); let ds = factory(p); ds.init().await.unwrap(); ds.open().await.unwrap(); DSTestContext { tempdir, datastore: Arc::new(ds), } } } impl<T: DataStore> std::ops::Deref for DSTestContext<T> { type Target = T; fn deref(&self) -> &Self::Target { &*self.datastore } } /// Generates the "common interface" tests for PinStore implementations as a given module using a /// types factory method. When adding tests, it might be easier to write them against the one /// implementation and only then move them here; the compiler errors seem to point at the /// `#[tokio::test]` attribute and the error needs to be guessed. #[macro_export] macro_rules! pinstore_interface_tests { ($module_name:ident, $factory:expr) => { #[cfg(test)] mod $module_name { use crate::repo::common_tests::DSTestContext; use crate::repo::{DataStore, PinKind, PinMode, PinStore}; use cid::Cid; use futures::{StreamExt, TryStreamExt}; use hash_hasher::HashedMap; use std::convert::TryFrom; #[tokio::test] async fn pin_direct_twice_is_good() { let repo = DSTestContext::with($factory).await; let empty = Cid::try_from("QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH").unwrap(); assert_eq!( repo.is_pinned(&empty).await.unwrap(), false, "initially unpinned" ); repo.insert_direct_pin(&empty).await.unwrap(); assert_eq!( repo.is_pinned(&empty).await.unwrap(), true, "must be pinned following direct pin" ); repo.insert_direct_pin(&empty) .await .expect("rewriting existing direct pin as direct should be noop"); assert_eq!( repo.is_pinned(&empty).await.unwrap(), true, "must be pinned following two direct pins" ); } #[tokio::test] async fn cannot_recursively_unpin_unpinned() { let repo = DSTestContext::with($factory).await; // root/nested/deeper: QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp let empty = Cid::try_from("QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH").unwrap(); // the only pin we can try removing without first querying is direct, as shown in // `cannot_unpin_indirect`. let e = repo .remove_recursive_pin(&empty, futures::stream::empty().boxed()) .await .unwrap_err(); // FIXME: go-ipfs errors on the actual path assert_eq!(e.to_string(), "not pinned or pinned indirectly"); } #[tokio::test] async fn cannot_unpin_indirect() { let repo = DSTestContext::with($factory).await; // root/nested/deeper: QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp let root = Cid::try_from("QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp").unwrap(); let empty = Cid::try_from("QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH").unwrap(); // first refs repo.insert_recursive_pin( &root, futures::stream::iter(vec![Ok(empty.clone())]).boxed(), ) .await .unwrap(); // should panic because the caller must not attempt this because: let (_, kind) = repo .query(vec![empty.clone()], None) .await .unwrap() .into_iter() .next() .unwrap(); // mem based uses "canonicalized" cids and fs uses them raw match kind { PinKind::IndirectFrom(v0_or_v1) if v0_or_v1.hash() == root.hash() && v0_or_v1.codec() == root.codec() => {} x => unreachable!("{:?}", x), } // this makes the "remove direct" invalid, as the direct pin must not be removed while // recursively pinned let e = repo.remove_direct_pin(&empty).await.unwrap_err(); // FIXME: go-ipfs errors on the actual path assert_eq!(e.to_string(), "not pinned or pinned indirectly"); } #[tokio::test] async fn can_pin_direct_as_recursive() { // the other way around doesn't work let repo = DSTestContext::with($factory).await; // // root/nested/deeper: QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp let root = Cid::try_from("QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp").unwrap(); let empty = Cid::try_from("QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH").unwrap(); repo.insert_direct_pin(&root).await.unwrap(); let pins = repo.list(None).await.try_collect::<Vec<_>>().await.unwrap(); assert_eq!( pins, vec![(root.clone(), PinMode::Direct)], "must find direct pin for root" ); // first refs repo.insert_recursive_pin( &root, futures::stream::iter(vec![Ok(empty.clone())]).boxed(), ) .await .unwrap(); let mut both = repo .list(None) .await .try_collect::<HashedMap<Cid, PinMode>>() .await .unwrap(); assert_eq!(both.remove(&root), Some(PinMode::Recursive)); assert_eq!(both.remove(&empty), Some(PinMode::Indirect)); assert!(both.is_empty(), "{:?}", both); } #[tokio::test] async fn pin_recursive_pins_all_blocks() { let repo = DSTestContext::with($factory).await; // root/nested/deeper: QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp let root = Cid::try_from("QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp").unwrap(); let empty = Cid::try_from("QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH").unwrap(); // assumed use: repo.insert_recursive_pin( &root, futures::stream::iter(vec![Ok(empty.clone())]).boxed(), ) .await .unwrap(); assert!(repo.is_pinned(&root).await.unwrap()); assert!(repo.is_pinned(&empty).await.unwrap()); let mut both = repo .list(None) .await .try_collect::<HashedMap<Cid, PinMode>>() .await .unwrap(); assert_eq!(both.remove(&root), Some(PinMode::Recursive)); assert_eq!(both.remove(&empty), Some(PinMode::Indirect)); assert!(both.is_empty(), "{:?}", both); } #[tokio::test] async fn indirect_can_be_pinned_directly() { let repo = DSTestContext::with($factory).await; // root/nested/deeper: QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp let root = Cid::try_from("QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp").unwrap(); let empty = Cid::try_from("QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH").unwrap(); repo.insert_direct_pin(&empty).await.unwrap(); repo.insert_recursive_pin( &root, futures::stream::iter(vec![Ok(empty.clone())]).boxed(), ) .await .unwrap(); let mut both = repo .list(None) .await .try_collect::<HashedMap<Cid, PinMode>>() .await .unwrap(); assert_eq!(both.remove(&root), Some(PinMode::Recursive)); // when working on the first round of mem based recursive pinning I had understood // this to be a rule. go-ipfs preferes the priority order of Recursive, Direct, // Indirect and so does our fs datastore. let mode = both.remove(&empty).unwrap(); assert!( mode == PinMode::Indirect || mode == PinMode::Direct, "{:?}", mode ); assert!(both.is_empty(), "{:?}", both); } #[tokio::test] async fn direct_and_indirect_when_parent_unpinned() { let repo = DSTestContext::with($factory).await; // root/nested/deeper: QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp let root = Cid::try_from("QmX5S2xLu32K6WxWnyLeChQFbDHy79ULV9feJYH2Hy9bgp").unwrap(); let empty = Cid::try_from("QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH").unwrap(); repo.insert_direct_pin(&empty).await.unwrap(); assert_eq!( repo.query(vec![empty.clone()], None) .await .unwrap() .into_iter() .collect::<Vec<_>>(), vec![(empty.clone(), PinKind::Direct)], ); // first refs repo.insert_recursive_pin( &root, futures::stream::iter(vec![Ok(empty.clone())]).boxed(), ) .await .unwrap(); // second refs repo.remove_recursive_pin( &root, futures::stream::iter(vec![Ok(empty.clone())]).boxed(), ) .await .unwrap(); let mut one = repo .list(None) .await .try_collect::<HashedMap<Cid, PinMode>>() .await .unwrap(); assert_eq!(one.remove(&empty), Some(PinMode::Direct)); assert!(one.is_empty(), "{:?}", one); } #[tokio::test] async fn cannot_pin_recursively_pinned_directly() { // this is a bit of odd as other ops are additive let repo = DSTestContext::with($factory).await; let empty = Cid::try_from("QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH").unwrap(); repo.insert_recursive_pin(&empty, futures::stream::iter(vec![]).boxed()) .await .unwrap(); let e = repo.insert_direct_pin(&empty).await.unwrap_err(); // go-ipfs puts the cid in front here, not sure if we want to at this level? though in // go-ipfs it's different than path resolving assert_eq!(e.to_string(), "already pinned recursively"); } } }; }
use crate::utils::StatefulList; use crate::todo::{ Todo, TodoData }; pub struct TodoList { pub items: StatefulList<Todo> } impl<'a> TodoList { pub fn new(data: TodoData) -> TodoList { TodoList { items: StatefulList::with_items(data.todos) } } }
#[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::RCGCTIMER { #[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 SYSCTL_RCGCTIMER_R0R { bits: bool, } impl SYSCTL_RCGCTIMER_R0R { #[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 _SYSCTL_RCGCTIMER_R0W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_RCGCTIMER_R0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_RCGCTIMER_R1R { bits: bool, } impl SYSCTL_RCGCTIMER_R1R { #[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 _SYSCTL_RCGCTIMER_R1W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_RCGCTIMER_R1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_RCGCTIMER_R2R { bits: bool, } impl SYSCTL_RCGCTIMER_R2R { #[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 _SYSCTL_RCGCTIMER_R2W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_RCGCTIMER_R2W<'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 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_RCGCTIMER_R3R { bits: bool, } impl SYSCTL_RCGCTIMER_R3R { #[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 _SYSCTL_RCGCTIMER_R3W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_RCGCTIMER_R3W<'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 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_RCGCTIMER_R4R { bits: bool, } impl SYSCTL_RCGCTIMER_R4R { #[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 _SYSCTL_RCGCTIMER_R4W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_RCGCTIMER_R4W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct SYSCTL_RCGCTIMER_R5R { bits: bool, } impl SYSCTL_RCGCTIMER_R5R { #[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 _SYSCTL_RCGCTIMER_R5W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_RCGCTIMER_R5W<'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 SYSCTL_RCGCTIMER_R6R { bits: bool, } impl SYSCTL_RCGCTIMER_R6R { #[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 _SYSCTL_RCGCTIMER_R6W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_RCGCTIMER_R6W<'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 SYSCTL_RCGCTIMER_R7R { bits: bool, } impl SYSCTL_RCGCTIMER_R7R { #[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 _SYSCTL_RCGCTIMER_R7W<'a> { w: &'a mut W, } impl<'a> _SYSCTL_RCGCTIMER_R7W<'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 0 - 16/32-Bit General-Purpose Timer 0 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r0(&self) -> SYSCTL_RCGCTIMER_R0R { let bits = ((self.bits >> 0) & 1) != 0; SYSCTL_RCGCTIMER_R0R { bits } } #[doc = "Bit 1 - 16/32-Bit General-Purpose Timer 1 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r1(&self) -> SYSCTL_RCGCTIMER_R1R { let bits = ((self.bits >> 1) & 1) != 0; SYSCTL_RCGCTIMER_R1R { bits } } #[doc = "Bit 2 - 16/32-Bit General-Purpose Timer 2 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r2(&self) -> SYSCTL_RCGCTIMER_R2R { let bits = ((self.bits >> 2) & 1) != 0; SYSCTL_RCGCTIMER_R2R { bits } } #[doc = "Bit 3 - 16/32-Bit General-Purpose Timer 3 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r3(&self) -> SYSCTL_RCGCTIMER_R3R { let bits = ((self.bits >> 3) & 1) != 0; SYSCTL_RCGCTIMER_R3R { bits } } #[doc = "Bit 4 - 16/32-Bit General-Purpose Timer 4 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r4(&self) -> SYSCTL_RCGCTIMER_R4R { let bits = ((self.bits >> 4) & 1) != 0; SYSCTL_RCGCTIMER_R4R { bits } } #[doc = "Bit 5 - 16/32-Bit General-Purpose Timer 5 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r5(&self) -> SYSCTL_RCGCTIMER_R5R { let bits = ((self.bits >> 5) & 1) != 0; SYSCTL_RCGCTIMER_R5R { bits } } #[doc = "Bit 6 - 16/32-Bit General-Purpose Timer 6 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r6(&self) -> SYSCTL_RCGCTIMER_R6R { let bits = ((self.bits >> 6) & 1) != 0; SYSCTL_RCGCTIMER_R6R { bits } } #[doc = "Bit 7 - 16/32-Bit General-Purpose Timer 7 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r7(&self) -> SYSCTL_RCGCTIMER_R7R { let bits = ((self.bits >> 7) & 1) != 0; SYSCTL_RCGCTIMER_R7R { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - 16/32-Bit General-Purpose Timer 0 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r0(&mut self) -> _SYSCTL_RCGCTIMER_R0W { _SYSCTL_RCGCTIMER_R0W { w: self } } #[doc = "Bit 1 - 16/32-Bit General-Purpose Timer 1 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r1(&mut self) -> _SYSCTL_RCGCTIMER_R1W { _SYSCTL_RCGCTIMER_R1W { w: self } } #[doc = "Bit 2 - 16/32-Bit General-Purpose Timer 2 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r2(&mut self) -> _SYSCTL_RCGCTIMER_R2W { _SYSCTL_RCGCTIMER_R2W { w: self } } #[doc = "Bit 3 - 16/32-Bit General-Purpose Timer 3 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r3(&mut self) -> _SYSCTL_RCGCTIMER_R3W { _SYSCTL_RCGCTIMER_R3W { w: self } } #[doc = "Bit 4 - 16/32-Bit General-Purpose Timer 4 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r4(&mut self) -> _SYSCTL_RCGCTIMER_R4W { _SYSCTL_RCGCTIMER_R4W { w: self } } #[doc = "Bit 5 - 16/32-Bit General-Purpose Timer 5 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r5(&mut self) -> _SYSCTL_RCGCTIMER_R5W { _SYSCTL_RCGCTIMER_R5W { w: self } } #[doc = "Bit 6 - 16/32-Bit General-Purpose Timer 6 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r6(&mut self) -> _SYSCTL_RCGCTIMER_R6W { _SYSCTL_RCGCTIMER_R6W { w: self } } #[doc = "Bit 7 - 16/32-Bit General-Purpose Timer 7 Run Mode Clock Gating Control"] #[inline(always)] pub fn sysctl_rcgctimer_r7(&mut self) -> _SYSCTL_RCGCTIMER_R7W { _SYSCTL_RCGCTIMER_R7W { w: self } } }
pub mod file; pub mod array; pub mod class;
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Flash Memory Address"] pub fma: FMA, #[doc = "0x04 - Flash Memory Data"] pub fmd: FMD, #[doc = "0x08 - Flash Memory Control"] pub fmc: FMC, #[doc = "0x0c - Flash Controller Raw Interrupt Status"] pub fcris: FCRIS, #[doc = "0x10 - Flash Controller Interrupt Mask"] pub fcim: FCIM, #[doc = "0x14 - Flash Controller Masked Interrupt Status and Clear"] pub fcmisc: FCMISC, _reserved6: [u8; 8usize], #[doc = "0x20 - Flash Memory Control 2"] pub fmc2: FMC2, _reserved7: [u8; 12usize], #[doc = "0x30 - Flash Write Buffer Valid"] pub fwbval: FWBVAL, _reserved8: [u8; 204usize], #[doc = "0x100 - Flash Write Buffer"] pub fwbn: [FWBN; 32], _reserved9: [u8; 3648usize], #[doc = "0xfc0 - Flash Size"] pub fsize: FSIZE, #[doc = "0xfc4 - SRAM Size"] pub ssize: SSIZE, _reserved11: [u8; 4usize], #[doc = "0xfcc - ROM Software Map"] pub romswmap: ROMSWMAP, _reserved12: [u8; 288usize], #[doc = "0x10f0 - ROM Control"] pub rmctl: RMCTL, _reserved13: [u8; 220usize], #[doc = "0x11d0 - Boot Configuration"] pub bootcfg: BOOTCFG, _reserved14: [u8; 12usize], #[doc = "0x11e0 - User Register 0"] pub userreg0: USERREG0, #[doc = "0x11e4 - User Register 1"] pub userreg1: USERREG1, #[doc = "0x11e8 - User Register 2"] pub userreg2: USERREG2, #[doc = "0x11ec - User Register 3"] pub userreg3: USERREG3, _reserved18: [u8; 16usize], #[doc = "0x1200 - Flash Memory Protection Read Enable 0"] pub fmpre0: FMPRE0, #[doc = "0x1204 - Flash Memory Protection Read Enable 1"] pub fmpre1: FMPRE1, #[doc = "0x1208 - Flash Memory Protection Read Enable 2"] pub fmpre2: FMPRE2, #[doc = "0x120c - Flash Memory Protection Read Enable 3"] pub fmpre3: FMPRE3, _reserved22: [u8; 496usize], #[doc = "0x1400 - Flash Memory Protection Program Enable 0"] pub fmppe0: FMPPE0, #[doc = "0x1404 - Flash Memory Protection Program Enable 1"] pub fmppe1: FMPPE1, #[doc = "0x1408 - Flash Memory Protection Program Enable 2"] pub fmppe2: FMPPE2, #[doc = "0x140c - Flash Memory Protection Program Enable 3"] pub fmppe3: FMPPE3, } #[doc = "Flash Memory Address\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fma](fma) module"] pub type FMA = crate::Reg<u32, _FMA>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMA; #[doc = "`read()` method returns [fma::R](fma::R) reader structure"] impl crate::Readable for FMA {} #[doc = "`write(|w| ..)` method takes [fma::W](fma::W) writer structure"] impl crate::Writable for FMA {} #[doc = "Flash Memory Address"] pub mod fma; #[doc = "Flash Memory Data\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmd](fmd) module"] pub type FMD = crate::Reg<u32, _FMD>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMD; #[doc = "`read()` method returns [fmd::R](fmd::R) reader structure"] impl crate::Readable for FMD {} #[doc = "`write(|w| ..)` method takes [fmd::W](fmd::W) writer structure"] impl crate::Writable for FMD {} #[doc = "Flash Memory Data"] pub mod fmd; #[doc = "Flash Memory Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmc](fmc) module"] pub type FMC = crate::Reg<u32, _FMC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMC; #[doc = "`read()` method returns [fmc::R](fmc::R) reader structure"] impl crate::Readable for FMC {} #[doc = "`write(|w| ..)` method takes [fmc::W](fmc::W) writer structure"] impl crate::Writable for FMC {} #[doc = "Flash Memory Control"] pub mod fmc; #[doc = "Flash Controller Raw Interrupt Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fcris](fcris) module"] pub type FCRIS = crate::Reg<u32, _FCRIS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FCRIS; #[doc = "`read()` method returns [fcris::R](fcris::R) reader structure"] impl crate::Readable for FCRIS {} #[doc = "Flash Controller Raw Interrupt Status"] pub mod fcris; #[doc = "Flash Controller Interrupt Mask\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fcim](fcim) module"] pub type FCIM = crate::Reg<u32, _FCIM>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FCIM; #[doc = "`read()` method returns [fcim::R](fcim::R) reader structure"] impl crate::Readable for FCIM {} #[doc = "`write(|w| ..)` method takes [fcim::W](fcim::W) writer structure"] impl crate::Writable for FCIM {} #[doc = "Flash Controller Interrupt Mask"] pub mod fcim; #[doc = "Flash Controller Masked Interrupt Status and Clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fcmisc](fcmisc) module"] pub type FCMISC = crate::Reg<u32, _FCMISC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FCMISC; #[doc = "`read()` method returns [fcmisc::R](fcmisc::R) reader structure"] impl crate::Readable for FCMISC {} #[doc = "`write(|w| ..)` method takes [fcmisc::W](fcmisc::W) writer structure"] impl crate::Writable for FCMISC {} #[doc = "Flash Controller Masked Interrupt Status and Clear"] pub mod fcmisc; #[doc = "Flash Memory Control 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmc2](fmc2) module"] pub type FMC2 = crate::Reg<u32, _FMC2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMC2; #[doc = "`read()` method returns [fmc2::R](fmc2::R) reader structure"] impl crate::Readable for FMC2 {} #[doc = "`write(|w| ..)` method takes [fmc2::W](fmc2::W) writer structure"] impl crate::Writable for FMC2 {} #[doc = "Flash Memory Control 2"] pub mod fmc2; #[doc = "Flash Write Buffer Valid\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fwbval](fwbval) module"] pub type FWBVAL = crate::Reg<u32, _FWBVAL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FWBVAL; #[doc = "`read()` method returns [fwbval::R](fwbval::R) reader structure"] impl crate::Readable for FWBVAL {} #[doc = "`write(|w| ..)` method takes [fwbval::W](fwbval::W) writer structure"] impl crate::Writable for FWBVAL {} #[doc = "Flash Write Buffer Valid"] pub mod fwbval; #[doc = "Flash Write Buffer\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fwbn](fwbn) module"] pub type FWBN = crate::Reg<u32, _FWBN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FWBN; #[doc = "`read()` method returns [fwbn::R](fwbn::R) reader structure"] impl crate::Readable for FWBN {} #[doc = "`write(|w| ..)` method takes [fwbn::W](fwbn::W) writer structure"] impl crate::Writable for FWBN {} #[doc = "Flash Write Buffer"] pub mod fwbn; #[doc = "Flash Size\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fsize](fsize) module"] pub type FSIZE = crate::Reg<u32, _FSIZE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FSIZE; #[doc = "`read()` method returns [fsize::R](fsize::R) reader structure"] impl crate::Readable for FSIZE {} #[doc = "Flash Size"] pub mod fsize; #[doc = "SRAM Size\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ssize](ssize) module"] pub type SSIZE = crate::Reg<u32, _SSIZE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SSIZE; #[doc = "`read()` method returns [ssize::R](ssize::R) reader structure"] impl crate::Readable for SSIZE {} #[doc = "SRAM Size"] pub mod ssize; #[doc = "ROM Software Map\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [romswmap](romswmap) module"] pub type ROMSWMAP = crate::Reg<u32, _ROMSWMAP>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ROMSWMAP; #[doc = "`read()` method returns [romswmap::R](romswmap::R) reader structure"] impl crate::Readable for ROMSWMAP {} #[doc = "ROM Software Map"] pub mod romswmap; #[doc = "ROM Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rmctl](rmctl) module"] pub type RMCTL = crate::Reg<u32, _RMCTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RMCTL; #[doc = "`read()` method returns [rmctl::R](rmctl::R) reader structure"] impl crate::Readable for RMCTL {} #[doc = "`write(|w| ..)` method takes [rmctl::W](rmctl::W) writer structure"] impl crate::Writable for RMCTL {} #[doc = "ROM Control"] pub mod rmctl; #[doc = "Boot Configuration\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bootcfg](bootcfg) module"] pub type BOOTCFG = crate::Reg<u32, _BOOTCFG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _BOOTCFG; #[doc = "`read()` method returns [bootcfg::R](bootcfg::R) reader structure"] impl crate::Readable for BOOTCFG {} #[doc = "Boot Configuration"] pub mod bootcfg; #[doc = "User Register 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [userreg0](userreg0) module"] pub type USERREG0 = crate::Reg<u32, _USERREG0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _USERREG0; #[doc = "`read()` method returns [userreg0::R](userreg0::R) reader structure"] impl crate::Readable for USERREG0 {} #[doc = "`write(|w| ..)` method takes [userreg0::W](userreg0::W) writer structure"] impl crate::Writable for USERREG0 {} #[doc = "User Register 0"] pub mod userreg0; #[doc = "User Register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [userreg1](userreg1) module"] pub type USERREG1 = crate::Reg<u32, _USERREG1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _USERREG1; #[doc = "`read()` method returns [userreg1::R](userreg1::R) reader structure"] impl crate::Readable for USERREG1 {} #[doc = "`write(|w| ..)` method takes [userreg1::W](userreg1::W) writer structure"] impl crate::Writable for USERREG1 {} #[doc = "User Register 1"] pub mod userreg1; #[doc = "User Register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [userreg2](userreg2) module"] pub type USERREG2 = crate::Reg<u32, _USERREG2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _USERREG2; #[doc = "`read()` method returns [userreg2::R](userreg2::R) reader structure"] impl crate::Readable for USERREG2 {} #[doc = "`write(|w| ..)` method takes [userreg2::W](userreg2::W) writer structure"] impl crate::Writable for USERREG2 {} #[doc = "User Register 2"] pub mod userreg2; #[doc = "User Register 3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [userreg3](userreg3) module"] pub type USERREG3 = crate::Reg<u32, _USERREG3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _USERREG3; #[doc = "`read()` method returns [userreg3::R](userreg3::R) reader structure"] impl crate::Readable for USERREG3 {} #[doc = "`write(|w| ..)` method takes [userreg3::W](userreg3::W) writer structure"] impl crate::Writable for USERREG3 {} #[doc = "User Register 3"] pub mod userreg3; #[doc = "Flash Memory Protection Read Enable 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmpre0](fmpre0) module"] pub type FMPRE0 = crate::Reg<u32, _FMPRE0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMPRE0; #[doc = "`read()` method returns [fmpre0::R](fmpre0::R) reader structure"] impl crate::Readable for FMPRE0 {} #[doc = "`write(|w| ..)` method takes [fmpre0::W](fmpre0::W) writer structure"] impl crate::Writable for FMPRE0 {} #[doc = "Flash Memory Protection Read Enable 0"] pub mod fmpre0; #[doc = "Flash Memory Protection Read Enable 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmpre1](fmpre1) module"] pub type FMPRE1 = crate::Reg<u32, _FMPRE1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMPRE1; #[doc = "`read()` method returns [fmpre1::R](fmpre1::R) reader structure"] impl crate::Readable for FMPRE1 {} #[doc = "`write(|w| ..)` method takes [fmpre1::W](fmpre1::W) writer structure"] impl crate::Writable for FMPRE1 {} #[doc = "Flash Memory Protection Read Enable 1"] pub mod fmpre1; #[doc = "Flash Memory Protection Read Enable 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmpre2](fmpre2) module"] pub type FMPRE2 = crate::Reg<u32, _FMPRE2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMPRE2; #[doc = "`read()` method returns [fmpre2::R](fmpre2::R) reader structure"] impl crate::Readable for FMPRE2 {} #[doc = "`write(|w| ..)` method takes [fmpre2::W](fmpre2::W) writer structure"] impl crate::Writable for FMPRE2 {} #[doc = "Flash Memory Protection Read Enable 2"] pub mod fmpre2; #[doc = "Flash Memory Protection Read Enable 3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmpre3](fmpre3) module"] pub type FMPRE3 = crate::Reg<u32, _FMPRE3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMPRE3; #[doc = "`read()` method returns [fmpre3::R](fmpre3::R) reader structure"] impl crate::Readable for FMPRE3 {} #[doc = "`write(|w| ..)` method takes [fmpre3::W](fmpre3::W) writer structure"] impl crate::Writable for FMPRE3 {} #[doc = "Flash Memory Protection Read Enable 3"] pub mod fmpre3; #[doc = "Flash Memory Protection Program Enable 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmppe0](fmppe0) module"] pub type FMPPE0 = crate::Reg<u32, _FMPPE0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMPPE0; #[doc = "`read()` method returns [fmppe0::R](fmppe0::R) reader structure"] impl crate::Readable for FMPPE0 {} #[doc = "`write(|w| ..)` method takes [fmppe0::W](fmppe0::W) writer structure"] impl crate::Writable for FMPPE0 {} #[doc = "Flash Memory Protection Program Enable 0"] pub mod fmppe0; #[doc = "Flash Memory Protection Program Enable 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmppe1](fmppe1) module"] pub type FMPPE1 = crate::Reg<u32, _FMPPE1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMPPE1; #[doc = "`read()` method returns [fmppe1::R](fmppe1::R) reader structure"] impl crate::Readable for FMPPE1 {} #[doc = "`write(|w| ..)` method takes [fmppe1::W](fmppe1::W) writer structure"] impl crate::Writable for FMPPE1 {} #[doc = "Flash Memory Protection Program Enable 1"] pub mod fmppe1; #[doc = "Flash Memory Protection Program Enable 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmppe2](fmppe2) module"] pub type FMPPE2 = crate::Reg<u32, _FMPPE2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMPPE2; #[doc = "`read()` method returns [fmppe2::R](fmppe2::R) reader structure"] impl crate::Readable for FMPPE2 {} #[doc = "`write(|w| ..)` method takes [fmppe2::W](fmppe2::W) writer structure"] impl crate::Writable for FMPPE2 {} #[doc = "Flash Memory Protection Program Enable 2"] pub mod fmppe2; #[doc = "Flash Memory Protection Program Enable 3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fmppe3](fmppe3) module"] pub type FMPPE3 = crate::Reg<u32, _FMPPE3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FMPPE3; #[doc = "`read()` method returns [fmppe3::R](fmppe3::R) reader structure"] impl crate::Readable for FMPPE3 {} #[doc = "`write(|w| ..)` method takes [fmppe3::W](fmppe3::W) writer structure"] impl crate::Writable for FMPPE3 {} #[doc = "Flash Memory Protection Program Enable 3"] pub mod fmppe3;
// 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. #[derive(Debug)] struct TlsGenericStream<'yielder, SD: SocketData, S: SessionExt> { generic_stream: GenericStream<'yielder, SD>, tls_session: S, } impl<'yielder, SD: SocketData> TlsGenericStream<'yielder, SD, ServerSession> { #[inline(always)] fn server_name_indication_handshake_information(&self) -> Option<&str> { self.tls_session.get_sni_hostname() } } impl<'yielder, SD: SocketData, S: SessionExt> TlsGenericStream<'yielder, SD, S> { #[inline(always)] fn configure_and_handshake(mut generic_stream: GenericStream<'yielder, SD>, mut tls_session: S, session_buffer_limit: usize) -> Result<Self, CompleteError> { tls_session.set_buffer_limit(session_buffer_limit); generic_stream.tls_handshake(&mut tls_session)?; Ok ( Self { generic_stream, tls_session, } ) } /// This is a lie (ie the lifetime is ***NOT*** `'static`); the actual lifetime is ***LESS THAN*** `'yielder` and is the same as the lifetime of the underlying TLS `S: SessionExt`. #[inline(always)] fn common_tls_post_handshake_information(&self) -> CommonTlsPostHandshakeInformation<'static> { let value = CommonTlsPostHandshakeInformation::from_tls_session(&self.tls_session); // Grotesque hack which extends lifetime from 'yielder to 'static. unsafe { transmute(value) } } #[inline(always)] fn read_data(&mut self, read_into_buffer: &mut [u8]) -> Result<usize, CompleteError> { self.generic_stream.tls_read(&mut self.tls_session, read_into_buffer) } #[inline(always)] fn write_data(&mut self, write_from_buffer: &[u8]) -> Result<usize, CompleteError> { self.generic_stream.tls_write(&mut self.tls_session, write_from_buffer) } #[inline(always)] fn flush_written_data(&mut self) -> Result<(), CompleteError> { self.generic_stream.tls_flush_written_data(&mut self.tls_session) } #[inline(always)] fn finish(mut self) -> Result<(), CompleteError> { self.generic_stream.tls_finish(&mut self.tls_session) } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 pub mod helper; pub mod storage; pub mod transactions;
fn inplace_swap(x: &mut i32, y: &mut i32) { *y = *x ^ *y; // 第一步 *x = *x ^ *y; // 第二步 *y = *x ^ *y; // 第三步 }
extern crate monkey; use std::vec; use monkey::evaluator::*; use monkey::lexer::*; use monkey::object::*; use monkey::parser::*; #[test] fn test_eval_integer_expression() { let tests = vec![ ("5", 5), ("10", 10), ("-5", -5), ("-10", -10), ("5 + 5 + 5 + 5 - 10", 10), ("2 * 2 * 2 * 2 * 2", 32), ("-50 + 100 + -50", 0), ("5 * 2 + 10", 20), ("5 + 2 * 10", 25), ("20 + 2 * -10", 0), ("50 / 2 * 2 + 10", 60), ("2 * (5 + 10)", 30), ("3 * 3 * 3 + 10", 37), ("3 * (3 * 3) + 10", 37), ("(5 + 10 * 2 + 15 / 3) * 2 + -10", 50), ]; for (input, expected) in tests.iter() { let evaluated = test_eval(input); test_integer_object(&evaluated, *expected); } } #[test] fn test_eval_string_expression() { let input = r#""Hello World!""#; let l = Lexer::new(input.chars().collect()); let mut p = Parser::new(l); let program = p.parse_program(); let mut env = Environment::new(); let evaluation = eval(program, &mut env); match evaluation { Ok(obj) => match obj { Object::String { value } => assert_eq!(value, "Hello World!"), _ => assert!(false, "object is not String, got {}", obj), }, Err(msg) => { assert!(false, "{}", msg); } } } fn test_eval(input: &str) -> Object { let l = Lexer::new(input.chars().collect()); let mut p = Parser::new(l); let program = p.parse_program(); let mut env = Environment::new(); let evaluation = eval(program, &mut env); match evaluation { Ok(obj) => obj, _ => Object::Null, } } fn test_integer_object(obj: &Object, expected: i64) { match obj { Object::Integer { value } => { assert_eq!(*value, expected); } _ => assert!(false, "object is not Integer. got {}", obj.get_type()), } } fn test_boolean_object(obj: &Object, expected: bool) { match obj { Object::Boolean { value } => { assert_eq!(*value, expected); } _ => assert!(false, "object is not Boolean. got {}", obj.get_type()), } } #[test] fn test_eval_bool_expression() { let tests = vec![ ("true", true), ("false", false), ("1 < 2", true), ("1 > 2", false), ("1 < 1", false), ("1 > 1", false), ("1 == 1", true), ("1 != 1", false), ("1 == 2", false), ("1 != 2", true), ("true == true", true), ("false == false", true), ("true == false", false), ("true != false", true), ("false != true", true), ("(1 < 2) == true", true), ("(1 < 2) == false", false), ("(1 > 2) == true", false), ("(1 > 2) == false", true), ]; for (input, expected) in tests.iter() { let evaluated = test_eval(input); test_boolean_object(&evaluated, *expected); } } #[test] fn test_bang_operator() { let tests = vec![ ("!true", false), ("!false", true), ("!5", false), ("!!true", true), ("!!false", false), ("!!5", true), ("!!0", false), ]; for (input, expected) in tests.iter() { let evaluated = test_eval(input); test_boolean_object(&evaluated, *expected); } } #[test] fn test_if_else_expression() { let tests = vec![ ("if (true) { 10 }", "10"), ("if (false) { 10 }", "null"), ("if (1) { 10 }", "10"), ("if (1 < 2) { 10 }", "10"), ("if (1 > 2) { 10 }", "null"), ("if (1 > 2) { 10 } else { 20 }", "20"), ("if (1 < 2) { 10 } else { 20 }", "10"), ]; for (input, expected) in tests { let evaluated = test_eval(input); match i64::from_str_radix(expected, 10) { Ok(n) => test_integer_object(&evaluated, n), _ => test_null_object(&evaluated), } } } fn test_null_object(obj: &Object) { match obj { Object::Null => (), _ => assert!(false, "object is not NULL, got {}", obj), } } #[test] fn test_return_statement() { let tests = vec![ ("return 10;", "10"), ("return 10; 9;", "10"), ("return 2 * 5; 9;", "10"), ("9; return 2 * 5; 9;", "10"), ( "if (10 > 1) { if (10 > 1) { return 10; } return 1; }", "10", ), ]; for (input, expected) in tests { let evaluated = test_eval(input); match i64::from_str_radix(expected, 10) { Ok(n) => test_integer_object(&evaluated, n), _ => assert!(false, "type not expected. got {}", expected), } } } #[test] fn test_error_handling() { let tests = vec![ ("5 + true;", "type mismatch: INTEGER + BOOLEAN"), ("5 + true; 5;", "type mismatch: INTEGER + BOOLEAN"), ("-true", "unknown operator: -BOOLEAN"), ("true + false;", "unknown operator: BOOLEAN + BOOLEAN"), ( "true + false + true + false;", "unknown operator: BOOLEAN + BOOLEAN", ), ("5; true + false; 5", "unknown operator: BOOLEAN + BOOLEAN"), ( "if (10 > 1) { true + false; }", "unknown operator: BOOLEAN + BOOLEAN", ), ( " if (10 > 1) { if (10 > 1) { return true + false; } return 1; } ", "unknown operator: BOOLEAN + BOOLEAN", ), ("foobar", "identifier not found: foobar"), (r#""Hello" - "World""#, "unknown operator: STRING - STRING"), ]; for (input, expected) in tests { let l = Lexer::new(input.chars().collect()); let mut p = Parser::new(l); let program = p.parse_program(); let mut env = Environment::new(); let evaluation = eval(program, &mut env); match evaluation { Ok(_obj) => assert!(false, "expected error not found!"), Err(msg) => { assert_eq!(expected, &msg); } } } } #[test] fn test_let_statements() { let tests = vec![ ("let a = 5; a;", 5), ("let a = 5 * 5; a;", 25), ("let a = 5; let b = a; b;", 5), ("let a = 5; let b = a; let c = a + b + 5; c;", 15), ]; for (input, expected) in tests { let evaluated = test_eval(input); test_integer_object(&evaluated, expected); } } #[test] fn test_function_object() { let input = "fn(x) { x + 2; }"; let evaluated = test_eval(input); match evaluated { Object::Function { parameters, body, env: _, } => { assert_eq!(parameters.len(), 1); assert_eq!(parameters[0].to_string(), "x".to_string()); let expected_body = "(x + 2)".to_string(); assert_eq!(body.to_string(), expected_body); } _ => assert!(false, "object is not a Function, got {:?}", evaluated), } } #[test] fn test_function_application() { let tests = vec![ ("let identity = fn(x) { x; }; identity(5);", 5), ("let identity = fn(x) { return x; }; identity(5);", 5), ("let double = fn(x) { x * 2; }; double(5);", 10), ("let add = fn(x, y) { x + y; }; add(5, 5);", 10), ("let add = fn(x, y) { x + y; }; add(5 + 5, add(5, 5));", 20), ("fn(x) { x; }(5)", 5), ]; for (input, expected) in tests { test_integer_object(&test_eval(input), expected); } } #[test] fn test_closures() { let tests = vec![( " let newAdder = fn(x) { fn(y) { x + y }; }; let addTwo = newAdder(2); addTwo(2);", 4, )]; for (input, expected) in tests { test_integer_object(&test_eval(input), expected); } } #[test] fn test_string_concatenation() { let input = r#""Hello" + " " + "World!" "#; let evaluated = test_eval(input); match evaluated { Object::String { value } => assert_eq!(value, "Hello World!"), _ => assert!(false, "object not String. got {}", evaluated), } } #[test] fn test_string_comparison() { let tests = vec![ (r#""Hello" == "World!" "#, false), (r#""Hello" == "Hello" "#, true), ]; for (input, expected) in tests { let evaluated = test_eval(input); test_boolean_object(&evaluated, expected); } }
use crate::core::U256; use crate::{ domain::{BlockTimeHeight, YoctoNear, YoctoStake}, interface, }; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; /// STAKE token value at a point in time, i.e., at a block height. /// /// STAKE token value = [total_staked_near_balance](StakeTokenValue::total_staked_near_balance) / [total_stake_supply](StakeTokenValue::total_stake_supply) /// /// NOTE: The STAKE token value is gathered while the contract is locked. #[derive(BorshSerialize, BorshDeserialize, Copy, Clone, Default, Debug)] pub struct StakeTokenValue { block_time_height: BlockTimeHeight, total_staked_near_balance: YoctoNear, total_stake_supply: YoctoStake, } impl StakeTokenValue { pub fn new( block_time_height: BlockTimeHeight, total_staked_near_balance: YoctoNear, total_stake_supply: YoctoStake, ) -> Self { assert!( total_staked_near_balance.value() >= total_stake_supply.value(), "total staked NEAR balance ({}) should always >= total STAKE supply ({}) : {}", total_staked_near_balance.value(), total_stake_supply.value(), total_stake_supply.value() - total_staked_near_balance.value() ); Self { block_time_height, total_staked_near_balance, total_stake_supply, } } pub fn block_time_height(&self) -> BlockTimeHeight { self.block_time_height } pub fn total_staked_near_balance(&self) -> YoctoNear { self.total_staked_near_balance } pub fn total_stake_supply(&self) -> YoctoStake { self.total_stake_supply } /// converts NEAR to STAKE rounded down /// - STAKE appreciates in value over time - if we were to round up, then NEAR would leak out pub fn near_to_stake(&self, near: YoctoNear) -> YoctoStake { if self.total_staked_near_balance.value() == 0 { return near.value().into(); } let near = U256::from(near); let total_stake_supply = U256::from(self.total_stake_supply); let total_staked_near_balance = U256::from(self.total_staked_near_balance); (near * total_stake_supply / total_staked_near_balance) .as_u128() .into() } /// converts STAKE to NEAR rounded up /// - we round up because we never want to short change the payout /// - this also helps to compensate for rounding down when we convert NEAR -> STAKE pub fn stake_to_near(&self, stake: YoctoStake) -> YoctoNear { if self.total_staked_near_balance.value() == 0 // when deposit and staked with staking pool, there is a small amount remaining as unstaked // however, STAKE token value should never be less than 1:1 in terms of NEAR || self.total_staked_near_balance.value() < self.total_stake_supply.value() { return stake.value().into(); } let stake = U256::from(stake); let total_stake_supply = U256::from(self.total_stake_supply); let total_staked_near_balance = U256::from(self.total_staked_near_balance); let near_value = stake * total_staked_near_balance / total_stake_supply; if (stake * total_staked_near_balance) % total_stake_supply == U256::from(0) { near_value.as_u128().into() } else { // round up (near_value.as_u128() + 1).into() } } } impl From<interface::StakeTokenValue> for StakeTokenValue { fn from(value: interface::StakeTokenValue) -> Self { Self { block_time_height: value.block_time_height.into(), total_staked_near_balance: value.total_staked_near_balance.into(), total_stake_supply: value.total_stake_supply.into(), } } } #[cfg(test)] mod test { use super::*; use crate::near::YOCTO; use crate::test_utils::*; use near_sdk::{testing_env, MockedBlockchain}; #[test] fn when_total_stake_supply_is_zero() { let account_id = "bob.near"; let context = new_context(account_id); testing_env!(context); let stake_token_value = StakeTokenValue::default(); assert_eq!( stake_token_value.stake_to_near(YOCTO.into()), YoctoNear(YOCTO) ); assert_eq!( stake_token_value.near_to_stake(YOCTO.into()), YoctoStake(YOCTO) ); assert_eq!( stake_token_value.stake_to_near((10 * YOCTO).into()), YoctoNear(10 * YOCTO) ); assert_eq!( stake_token_value.near_to_stake((10 * YOCTO).into()), YoctoStake(10 * YOCTO) ); } #[test] fn conversion_should_be_symmetric() { let account_id = "bob.near"; let context = new_context(account_id); testing_env!(context); let mut stake_token_value = StakeTokenValue::default(); stake_token_value.total_staked_near_balance = 17206799984076953573143542.into(); stake_token_value.total_stake_supply = 16742879620291694593306687.into(); let near_value = stake_token_value.stake_to_near(YOCTO.into()); let stake_value = stake_token_value.near_to_stake(near_value); assert_eq!(stake_value, YoctoStake(YOCTO)); let stake_value = stake_token_value.near_to_stake(YOCTO.into()); let near_value = stake_token_value.stake_to_near(stake_value); assert_eq!(near_value, YoctoNear(YOCTO)); } }
mod codegen; mod utils; use eyre::Result; fn main() -> Result<()> { codegen::run()?; Ok(()) }
use super::{utils::FiberIdExtension, PausedState}; use crate::{ database::Database, debug_adapter::{ session::StartAt1Config, tracer::{DebugTracer, StackFrame}, utils::FiberIdThreadIdConversion, }, utils::{module_to_url, LspPositionConversion}, }; use candy_frontend::{ast_to_hir::AstToHir, hir::Id, utils::AdjustCasingOfFirstLetter}; use candy_vm::{ fiber::FiberId, heap::{Data, DisplayWithSymbolTable, InlineObject}, lir::Lir, vm::Vm, }; use dap::{ self, requests::StackTraceArguments, responses::StackTraceResponse, types::{PresentationHint, Source, StackFramePresentationhint}, }; use std::{borrow::Borrow, hash::Hash}; impl PausedState { pub fn stack_trace( &mut self, db: &Database, start_at_1_config: StartAt1Config, args: StackTraceArguments, ) -> Result<StackTraceResponse, &'static str> { let fiber_id = FiberId::from_thread_id(args.thread_id); let fiber = self .vm_state .vm .fiber(fiber_id) .ok_or("fiber-not-found")? .fiber_ref(); let fiber_state = &fiber.tracer; let start_frame = args.start_frame.unwrap_or_default(); let levels = args .levels .and_then(|it| if it == 0 { None } else { Some(it) }) .unwrap_or(usize::MAX); let call_stack = &fiber_state.call_stack[..fiber_state.call_stack.len() - start_frame]; let total_frames = fiber_state.call_stack.len() + 1; let mut stack_frames = Vec::with_capacity((1 + call_stack.len()).min(levels)); stack_frames.extend(call_stack.iter().enumerate().rev().skip(start_frame).map( |(index, frame)| { let id = self .stack_frame_ids .key_to_id(StackFrameKey { fiber_id, index: index + 1, }) .get(); Self::stack_frame(db, start_at_1_config, id, frame, self.vm_state.vm.lir()) }, )); if stack_frames.len() < levels { stack_frames.push(dap::types::StackFrame { id: self .stack_frame_ids .key_to_id(StackFrameKey { fiber_id, index: 0 }) .get(), name: "Spawn".to_string(), source: None, line: 1, column: 1, end_line: None, end_column: None, can_restart: Some(false), instruction_pointer_reference: None, module_id: None, presentation_hint: Some(StackFramePresentationhint::Normal), }); } Ok(StackTraceResponse { stack_frames, total_frames: Some(total_frames), }) } fn stack_frame( db: &Database, start_at_1_config: StartAt1Config, id: usize, frame: &StackFrame, lir: &Lir, ) -> dap::types::StackFrame { let (name, source, range) = match Data::from(frame.call.callee) { Data::Function(function) => { let functions = lir.functions_behind(function.body()); assert_eq!(functions.len(), 1); let function = functions.iter().next().unwrap(); let source = Source { name: Some(ToString::to_string(&function.module)), path: Some(ToString::to_string( &module_to_url(&function.module, &db.packages_path).unwrap(), )), source_reference: None, presentation_hint: if lir.module.package == function.module.package { PresentationHint::Emphasize } else { PresentationHint::Normal }, origin: None, sources: None, adapter_data: None, checksums: None, }; let range = db.hir_id_to_span(function.to_owned()).unwrap(); let range = db.range_to_lsp_range(function.module.to_owned(), range); let range = start_at_1_config.range_to_dap(range); (function.function_name(), Some(source), Some(range)) } Data::Builtin(builtin) => { let name = format!( "✨.{}", format!("{:?}", builtin.get()).lowercase_first_letter(), ); (name, None, None) } it => panic!( "Unexpected callee: {}", DisplayWithSymbolTable::to_string(&it, &lir.symbol_table), ), }; dap::types::StackFrame { id, name, source, line: range.map(|it| it.start.line as usize).unwrap_or(1), column: range.map(|it| it.start.character as usize).unwrap_or(1), end_line: range.map(|it| it.end.line as usize), end_column: range.map(|it| it.end.character as usize), can_restart: Some(false), instruction_pointer_reference: None, module_id: None, presentation_hint: Some(StackFramePresentationhint::Normal), } } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct StackFrameKey { pub fiber_id: FiberId, /// `0` represents the fiber spawn for which we don't have a stack frame. index: usize, } impl StackFrameKey { pub fn get<'a, L: Borrow<Lir>>(&self, vm: &'a Vm<L, DebugTracer>) -> Option<&'a StackFrame> { if self.index == 0 { return None; } Some(&self.fiber_id.get(vm).tracer.call_stack[self.index - 1]) } pub fn get_locals<'a, L: Borrow<Lir>>( &self, vm: &'a Vm<L, DebugTracer>, ) -> &'a Vec<(Id, InlineObject)> { let fiber_state = &self.fiber_id.get(vm).tracer; if self.index == 0 { &fiber_state.root_locals } else { &fiber_state.call_stack[self.index - 1].locals } } }
use rustc_semver::RustcVersion; macro_rules! msrv_aliases { ($($major:literal,$minor:literal,$patch:literal { $($name:ident),* $(,)? })*) => { $($( pub const $name: RustcVersion = RustcVersion::new($major, $minor, $patch); )*)* }; } // names may refer to stabilized feature flags or library items msrv_aliases! { 1,53,0 { OR_PATTERNS } 1,52,0 { STR_SPLIT_ONCE } 1,50,0 { BOOL_THEN } 1,47,0 { TAU } 1,46,0 { CONST_IF_MATCH } 1,45,0 { STR_STRIP_PREFIX } 1,43,0 { LOG2_10, LOG10_2 } 1,42,0 { MATCHES_MACRO, SLICE_PATTERNS } 1,41,0 { RE_REBALANCING_COHERENCE, RESULT_MAP_OR_ELSE } 1,40,0 { MEM_TAKE, NON_EXHAUSTIVE, OPTION_AS_DEREF } 1,38,0 { POINTER_CAST } 1,37,0 { TYPE_ALIAS_ENUM_VARIANTS } 1,36,0 { ITERATOR_COPIED } 1,35,0 { OPTION_COPIED, RANGE_CONTAINS } 1,34,0 { TRY_FROM } 1,30,0 { ITERATOR_FIND_MAP, TOOL_ATTRIBUTES } 1,28,0 { FROM_BOOL } 1,17,0 { FIELD_INIT_SHORTHAND, STATIC_IN_CONST } 1,16,0 { STR_REPEAT } }
mod climsg; mod filetarget; mod kmp; mod maketarget; mod target; mod tmaster; use crate::climsg::CliMsg; fn print_todo() { let msg = CliMsg::new( "TO-DO", vec![ ">consider creating a menu that allows you", "to pick in what order makefiles get compiled", ">maybe make it so that all makefile outputs get", "run and deleted and not just the first one you find", "Rust is a language for niggers and trannies", ], "*", 36, 0, 0, ); println!("{}", msg); } fn main_loop() { println!("COmpile-Run-DElete-Loop(CORDEL) v.0.0.1"); println!("type cordel -h and hit ENTER for help"); let mut a = tmaster::TMaster::new(); a.start(); println!("bye"); } fn main() { main_loop(); }
#[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; mod account; mod agent; mod asset; #[macro_use] mod macros; mod mission_control; mod rate;
use super::base::Base; use super::traits::get::Get; use super::traits::delete::Delete; use super::traits::edit::Edit; pub struct Done { pub super_struct: Base } impl Done { pub fn new(input_title: String) -> Done { let input_status: String = String::from("done"); let base: Base = Base::new(input_title, input_status); return Done{super_struct: base} } } impl Get for Done {} impl Delete for Done {} impl Edit for Done {}
// Standard library use std::sync::{Arc, Mutex}; use crate::collections::BaseRegistry; use crate::config::Config; use crate::exts::LockIt; use crate::signals::poll::PollQuery; use crate::signals::{Signal, SignalEvent, SignalEventShared, SignalOrderCurrent, UserSignal}; use anyhow::Result; use delegate::delegate; use lazy_static::lazy_static; use log::{error, warn}; use tokio::task::LocalSet; use unic_langid::LanguageIdentifier; lazy_static! { pub static ref POLL_SIGNAL: Mutex<Option<Arc<Mutex<PollQuery>>>> = Mutex::new(None); } #[derive(Debug, Clone)] pub struct SignalRegistry { event: SignalEventShared, order: Option<Arc<Mutex<SignalOrderCurrent>>>, poll: Option<Arc<Mutex<PollQuery>>>, base: BaseRegistry<dyn UserSignal + Send>, } impl SignalRegistry { pub fn new() -> Self { Self { event: Arc::new(Mutex::new(SignalEvent::new())), order: None, poll: None, base: BaseRegistry::new(), } } pub fn end_load(&mut self, curr_langs: &[LanguageIdentifier]) -> Result<()> { let mut to_remove = Vec::new(); for (sig_name, signal) in self.base.iter_mut() { if let Err(e) = signal.lock_it().end_load(curr_langs) { warn!( "Signal \"{}\" had trouble in \"end_load\", will be disabled, error: {}", &sig_name, e ); to_remove.push(sig_name.to_owned()); } } // Delete any signals which had problems during end_load for sig_name in &to_remove { self.base.remove_mangled(sig_name); } Ok(()) } pub async fn call_loops( &mut self, config: &Config, curr_lang: &Vec<LanguageIdentifier>, ) -> Result<()> { let local = LocalSet::new(); let spawn_on_local = |n: String, s: Arc<Mutex<dyn Signal + Send>>| { let event = self.event.clone(); let config = config.clone(); let curr_lang = curr_lang.clone(); local.spawn_local(async move { let res = s.lock_it().event_loop(event, &config, &curr_lang).await; if let Err(e) = res { error!("Signal '{}' had an error: {}", n, e.to_string()); } }); }; let spawn_on_local_u = |n: String, s: Arc<Mutex<dyn UserSignal + Send>>| { let event = self.event.clone(); let config = config.clone(); let curr_lang = curr_lang.clone(); local.spawn_local(async move { let res = s.lock_it().event_loop(event, &config, &curr_lang).await; if let Err(e) = res { error!("Signal '{}' had an error: {}", n, e.to_string()); } }); }; spawn_on_local( "order".into(), self.order .as_ref() .expect("Order signal had problems during init") .clone(), ); spawn_on_local( "poll".into(), self.poll .as_ref() .expect("Poll signal had problems during init") .clone(), ); for (sig_name, sig) in self.base.clone() { spawn_on_local_u(sig_name, sig); } local.await; Ok(()) } pub fn set_order(&mut self, sig_order: Arc<Mutex<SignalOrderCurrent>>) -> Result<()> { self.order = Some(sig_order); Ok(()) } pub fn set_poll(&mut self, sig_poll: Arc<Mutex<PollQuery>>) -> Result<()> { *POLL_SIGNAL.lock_it() = Some(sig_poll.clone()); self.poll = Some(sig_poll); Ok(()) } pub fn get_sig_order(&self) -> Option<&Arc<Mutex<SignalOrderCurrent>>> { self.order.as_ref() } delegate! {to self.base{ pub fn insert(&mut self, skill_name: &str, sig_name: &str, signal: Arc<Mutex<dyn UserSignal + Send>>) -> Result<()>; }} }
fn main() { println!("{}", lpf(600851475143)); } fn lpf(mut x: u64) -> u64 { let mut largest_prime = 2; while x > largest_prime { if x % largest_prime == 0 { x = x / largest_prime; largest_prime = 2; } else { largest_prime += 1; } } largest_prime }
use error::{Error, ErrorKind, Result}; use serde::ser::{self, Serialize}; struct PrimitiveSerializer { result: String, } pub fn serialize_primitive<T: Serialize>(v: T) -> Result<String> { let mut serializer = PrimitiveSerializer::new(); v.serialize(&mut serializer)?; Ok(serializer.result) } impl PrimitiveSerializer { fn new() -> PrimitiveSerializer { PrimitiveSerializer { result: String::new(), } } } // This serializer only allows for the serialization of primitives. Anything else results // in an error. impl<'a> ser::Serializer for &'a mut PrimitiveSerializer { type Ok = (); type Error = Error; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Self; type SerializeMap = Self; type SerializeStruct = Self; type SerializeStructVariant = Self; fn serialize_bool(self, _v: bool) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_i8(self, v: i8) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_i16(self, v: i16) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_i32(self, v: i32) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_i64(self, v: i64) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_u8(self, v: u8) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_u16(self, v: u16) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_u32(self, v: u32) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_u64(self, v: u64) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_f32(self, v: f32) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_f64(self, v: f64) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_char(self, v: char) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_str(self, v: &str) -> Result<Self::Ok> { self.result = v.to_string(); Ok(()) } fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_none(self) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_unit(self) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, ) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_newtype_variant<T>( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, ) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeTupleStruct> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeTupleVariant> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant> { Err(ErrorKind::NonPrimitiveKey.into()) } } impl<'a> ser::SerializeSeq for &'a mut PrimitiveSerializer { type Ok = (); type Error = Error; fn serialize_element<T>(&mut self, _value: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } // Close the sequence. fn end(self) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } } // Same thing but for tuples. impl<'a> ser::SerializeTuple for &'a mut PrimitiveSerializer { type Ok = (); type Error = Error; fn serialize_element<T>(&mut self, _value: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn end(self) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } } impl<'a> ser::SerializeTupleStruct for &'a mut PrimitiveSerializer { type Ok = (); type Error = Error; fn serialize_field<T>(&mut self, _value: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn end(self) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } } impl<'a> ser::SerializeTupleVariant for &'a mut PrimitiveSerializer { type Ok = (); type Error = Error; fn serialize_field<T>(&mut self, _value: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn end(self) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } } impl<'a> ser::SerializeMap for &'a mut PrimitiveSerializer { type Ok = (); type Error = Error; fn serialize_key<T>(&mut self, _key: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn serialize_value<T>(&mut self, _value: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn end(self) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } } impl<'a> ser::SerializeStruct for &'a mut PrimitiveSerializer { type Ok = (); type Error = Error; fn serialize_field<T>(&mut self, _key: &'static str, _value: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn end(self) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } } impl<'a> ser::SerializeStructVariant for &'a mut PrimitiveSerializer { type Ok = (); type Error = Error; fn serialize_field<T>(&mut self, _key: &'static str, _value: &T) -> Result<Self::Ok> where T: ?Sized + Serialize, { Err(ErrorKind::NonPrimitiveKey.into()) } fn end(self) -> Result<Self::Ok> { Err(ErrorKind::NonPrimitiveKey.into()) } }
use futures_03::prelude::*; use log::{error, info}; use nix::unistd::close; use std::io::Error; use std::net::SocketAddr; use std::os::unix::io::FromRawFd; use std::os::unix::io::RawFd; use std::result::Result; use stream_cancel::{Trigger, Tripwire}; use tokio::sync::mpsc::UnboundedSender; // use nix::sys::socket::{shutdown, Shutdown}; use bytes::Bytes; use tokio::net::UdpSocket; type TxType = UnboundedSender<(bytes::Bytes, std::net::SocketAddr)>; pub struct UStub { rawfd: RawFd, tx: Option<TxType>, tigger: Option<Trigger>, src_addr: SocketAddr, } impl UStub { pub fn new(src_addr: &SocketAddr, ll: super::LongLiveX) -> Result<Self, Error> { let mut stub = UStub { rawfd: 0, tx: None, tigger: None, src_addr: *src_addr, }; stub.start_udp_socket(src_addr, ll)?; Ok(stub) } pub fn on_udp_proxy_south(&self, msg: Bytes, dst_addr: SocketAddr) { if self.tx.is_none() { error!("[UStub] on_udp_proxy_south failed, no tx"); return; } info!( "[UStub] on_udp_proxy_south udp from:{} to:{}, len:{}", self.src_addr, dst_addr, msg.len() ); match self.tx.as_ref().unwrap().send((msg, dst_addr)) { Err(e) => { error!("[UStub]on_udp_proxy_south, send tx msg failed:{}", e); } _ => {} } } pub fn cleanup(&mut self) { // TODO: close socket and send fut info!("[UStub] cleanup, src_addr:{}", self.src_addr); self.close_rawfd(); self.tx = None; self.tigger = None; } fn close_rawfd(&self) { info!("[UStub]close_rawfd"); // let r = shutdown(self.rawfd, Shutdown::Both); let r = close(self.rawfd); match r { Err(e) => { info!("[UStub]close_rawfd failed:{}", e); } _ => {} } } fn set_tx(&mut self, tx2: TxType, trigger: Trigger) { self.tx = Some(tx2); self.tigger = Some(trigger); } fn start_udp_socket( &mut self, src_addr: &SocketAddr, ll: super::LongLiveX, ) -> std::result::Result<(), Error> { // let sockudp = std::net::UdpSocket::new(); let rawfd = super::sas_socket(src_addr)?; let socket_udp = unsafe { std::net::UdpSocket::from_raw_fd(rawfd) }; let a = UdpSocket::from_std(socket_udp)?; let udp_framed = tokio_util::udp::UdpFramed::new(a, tokio_util::codec::BytesCodec::new()); let (a_sink, a_stream) = udp_framed.split(); let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); let (trigger, tripwire) = Tripwire::new(); self.set_tx(tx, trigger); self.rawfd = rawfd; let ll2 = ll.clone(); let target_addr = *src_addr; // send future let send_fut = rx.map(move |x| Ok(x)).forward(a_sink); let receive_fut = async move { let mut a_stream = a_stream.take_until(tripwire); while let Some(rr) = a_stream.next().await { match rr { Ok((message, addr)) => { let rf = ll.borrow(); // post to manager info!( "[UStub] start_udp_socket udp from:{} to:{}, len:{}", addr, target_addr, message.len() ); rf.on_udp_msg_forward(message, addr, target_addr); } Err(e) => { error!("[UStub] a_stream.next failed:{}", e); break; } } } }; // Wait for one future to complete. let select_fut = async move { future::select(receive_fut.boxed_local(), send_fut).await; info!("[UStub] udp both future completed"); let mut rf = ll2.borrow_mut(); rf.on_ustub_closed(&target_addr); }; tokio::task::spawn_local(select_fut); Ok(()) } }
pub use crate::error::Error; pub mod clickhouse; pub mod error; pub mod export; pub mod geom; pub trait Named { fn name(&self) -> &'static str; }
// Copyright 2015 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 #![feature(specialization)] // Make sure we *can* project non-defaulted associated types // cf compile-fail/specialization-default-projection.rs // First, do so without any use of specialization trait Foo { type Assoc; } impl<T> Foo for T { type Assoc = (); } fn generic_foo<T>() -> <T as Foo>::Assoc { () } // Next, allow for one layer of specialization trait Bar { type Assoc; } impl<T> Bar for T { default type Assoc = (); } impl<T: Clone> Bar for T { type Assoc = u8; } fn generic_bar_clone<T: Clone>() -> <T as Bar>::Assoc { 0u8 } fn main() { }
use itertools::*; use utils::Vector2; // #[test] pub fn run() { let input = read_input1(include_str!("input/day13.txt")); println!("{}", exercise_1(&input)); println!("{}", exercise_2(&input.1)); } pub fn read_input1(input: &str) -> (usize, Vec<Option<usize>>) { let mut lines = input.lines(); let minutes = lines.next().and_then(|x| x.parse().ok()).unwrap(); let busses = lines .next() .unwrap() .split(',') .map(|x| { if x == "x" { None } else { Some(x.parse().unwrap()) } }) .collect(); (minutes, busses) } fn exercise_1((arrival, busses): &(usize, Vec<Option<usize>>)) -> usize { let bus = busses .iter() .filter_map(|x| x.as_ref()) .map(|&bus| (bus, bus - (arrival % bus))) .min_by_key(|(_, wait)| *wait) .unwrap(); bus.0 * bus.1 } fn exercise_2(input: &Vec<Option<usize>>) -> usize { let c = input[0].unwrap(); // offset, bus let mut busses = input .iter() .enumerate() .skip(1) .filter_map(|x| x.1.map(|a| (x.0, a))) .collect::<Vec<_>>(); busses.sort_by_key(|x| -(x.1 as isize)); println!("{:?}", busses); // let mut step = 100000000000002 ; // let mut step = 7380589664952; let mut start = 0usize; let mut increment = c; for &(offset, bus) in &busses { let x = (start..) .step_by(increment) .find(|&x| ((x + offset) % bus == 0)) .unwrap(); start = x; // increment = increment / gcd(bus, increment) * bus ; increment *= bus; println!("bus: {}, cycle: {}, step: {}", bus, increment, start); } start } fn gcd2(mut a: isize, mut b: isize) -> (usize, isize, isize) { let mut x = 0isize; let mut y = 1isize; let mut lastx = 1isize; let mut lasty = 0isize; let mut temp; while b != 0 { let q = a / b; let r = a.rem_euclid(b); a = b; b = r; temp = x; x = lastx - q * x; lastx = temp; temp = y; y = lasty - q * y; lasty = temp; println!("{}, {}", lastx, lasty); } println!(">>{}, {}", lastx, lasty); (a as usize, lastx, lasty) } fn gcd(mut a: usize, mut b: usize) -> usize { if a == 0 || b == 0 { return std::cmp::max(a, b); } while a != b { if a > b { a -= b; } else { b -= a; } } a } #[cfg(test)] mod tests { use super::*; use crate::test::Bencher; // #[test] // fn gcd2_test() { // assert_eq!((6, 132, -535), gcd2(12378, 3054)); // let (r, a ,b) = gcd2(-7, 13); // assert_eq!(6, a); // assert_eq!(11, b); // } #[test] fn d13p1_test() { // let input = read_input(include_str!("input/day13.txt")); assert_eq!( 295, exercise_1(&( 939, vec![ Some(7), Some(13), None, None, Some(59), None, Some(31), Some(19) ] )) ); } #[test] fn d13p2_test() { assert_eq!( 1068781, exercise_2(&vec![ Some(7), Some(13), None, None, Some(59), None, Some(31), Some(19) ]) ); assert_eq!(3417, exercise_2(&vec![Some(17), None, Some(13), Some(19)])); // assert_eq!(754018, exercise_2(&vec![67, 7, 59, 61])); } // #[bench] // fn d13_bench_parse(b: &mut Bencher) { // b.iter(|| read_input(include_str!("input/day13.txt"))); // } // #[bench] // fn d13_bench_ex1(b: &mut Bencher) { // let input = read_input(include_str!("input/day13.txt")); // b.iter(|| exercise_1(&input)); // } // #[bench] // fn d13_bench_ex2(b: &mut Bencher) { // let input = read_input(include_str!("input/day13.txt")); // b.iter(|| exercise_2(&input)); // } }
//! This is documentation for the `ftp` module. //! `ftp` module includes all necessary functionnalities to manage ftp connections. extern crate regex; use super::utils::Configuration; use std::net::{SocketAddr,TcpStream, Shutdown}; use std::io::{Read,Write}; use std::str; use self::regex::Regex; /// Struct representing a FTP server reply. #[derive(Clone, Debug, PartialEq)] pub struct FtpStatus { /// FTP Server reply code code: FtpStatusType, /// FTP Server reply message without code message: String, /// FTP Server reply full message full_message: String } impl FtpStatus { /// Instanciate an `FtpStatus` struct from parameters /// /// # Examples /// /// ``` /// FtpStatus::build(FtpStatusType::INITIATING, "Connection init.\n".to_owned(), "100 Connection init.\n".to_owned()); /// /// ... /// ``` pub fn build(code: FtpStatusType, message: String, full_message: String) -> FtpStatus { FtpStatus { code, message, full_message } } } /// Enum representing FTP server replies codes. #[derive(Clone, Debug, PartialEq)] #[allow(non_camel_case_types)] pub enum FtpStatusType { // Bifrost Internal Errors REPLY_ERROR = 0, INITIATING = 100, RESTART_MARKER = 110, READY_MINUTE = 120, ALREADY_OPEN = 125, ABOUT_TO_SEND = 150, // 2xx: Positive Completion Reply COMMAND_OK = 200, COMMAND_NOT_IMPLEMENTED = 202, SYSTEM = 211, DIRECTORY = 212, FILE = 213, HELP = 214, NAME = 215, READY = 220, CLOSING = 221, DATA_CONNECTION_OPEN = 225, CLOSING_DATA_CONNECTION = 226, PASSIVE_MODE = 227, LONG_PASSIVE_MODE = 228, EXTENDED_PASSIVE_MODE = 229, LOGGED_ON = 230, LOGGED_OUT = 231, LOGOUT_ACK = 232, AUTH_OK = 234, REQUESTED_FILE_ACTION_OK = 250, PATH_CREATED = 257, // 3xx: Positive intermediate Reply NEED_PASSWORD = 331, LOGIN_NEED_ACCOUNT = 332, REQUEST_FILE_PENDING = 350, // 4xx: Transient Negative Completion Reply NOT_AVAILABLE = 421, CANNOT_OPEN_DATA_CONNECTION = 425, TRANSER_ABORTED = 426, INVALID_CREDENTIALS = 430, HOST_UNAVAILABLE = 434, REQUEST_FILE_ACTION_IGNORED = 450, ACTION_ABORTED = 451, REQUESTED_ACTION_NOT_TAKEN = 452, // 5xx: Permanent Negative Completion Reply BAD_COMMAND = 500, BAD_ARGUMENTS = 501, NOT_IMPLEMENTED = 502, BAD_SEQUENCE = 503, NOT_IMPLEMENTED_PARAMETER = 504, NOT_LOGGED_IN = 530, STORING_NEED_ACCOUNT = 532, FILE_UNAVAILABLE = 550, PAGE_TYPE_UNKNOWN = 551, EXCEEDED_STORAGE = 552, BAD_FILENAME = 553, } impl FtpStatusType { #[allow(unreachable_patterns)] pub fn from_value(code: u16) -> FtpStatusType { match code { // Bifrost Internal Errors 0 => FtpStatusType::REPLY_ERROR, 100 => FtpStatusType::INITIATING, 110 => FtpStatusType::RESTART_MARKER, 120 => FtpStatusType::READY_MINUTE, 125 => FtpStatusType::ALREADY_OPEN, 150 => FtpStatusType::ABOUT_TO_SEND, // 2xx: Positive Completion Reply 200 => FtpStatusType::COMMAND_OK, 202 => FtpStatusType::COMMAND_NOT_IMPLEMENTED, 211 => FtpStatusType::SYSTEM, 212 => FtpStatusType::DIRECTORY, 213 => FtpStatusType::FILE, 214 => FtpStatusType::HELP, 215 => FtpStatusType::NAME, 220 => FtpStatusType::READY, 221 => FtpStatusType::CLOSING, 225 => FtpStatusType::DATA_CONNECTION_OPEN, 226 => FtpStatusType::CLOSING_DATA_CONNECTION, 227 => FtpStatusType::PASSIVE_MODE, 228 => FtpStatusType::LONG_PASSIVE_MODE, 229 => FtpStatusType::EXTENDED_PASSIVE_MODE, 230 => FtpStatusType::LOGGED_ON, 231 => FtpStatusType::LOGGED_OUT, 232 => FtpStatusType::LOGOUT_ACK, 234 => FtpStatusType::AUTH_OK, 250 => FtpStatusType::REQUESTED_FILE_ACTION_OK, 257 => FtpStatusType::PATH_CREATED, // 3xx: Positive intermediate Reply 331 => FtpStatusType::NEED_PASSWORD, 332 => FtpStatusType::LOGIN_NEED_ACCOUNT, 350 => FtpStatusType::REQUEST_FILE_PENDING, // 4xx: Transient Negative Completion Reply 421 => FtpStatusType::NOT_AVAILABLE, 425 => FtpStatusType::CANNOT_OPEN_DATA_CONNECTION, 436 => FtpStatusType::TRANSER_ABORTED, 430 => FtpStatusType::INVALID_CREDENTIALS, 434 => FtpStatusType::HOST_UNAVAILABLE, 450 => FtpStatusType::REQUEST_FILE_ACTION_IGNORED, 451 => FtpStatusType::ACTION_ABORTED, 452 => FtpStatusType::REQUESTED_ACTION_NOT_TAKEN, // 5xx: Permanent Negative Completion Reply 500 => FtpStatusType::BAD_COMMAND, 501 => FtpStatusType::BAD_ARGUMENTS, 502 => FtpStatusType::NOT_IMPLEMENTED, 503 => FtpStatusType::BAD_SEQUENCE, 504 => FtpStatusType::NOT_IMPLEMENTED_PARAMETER, 530 => FtpStatusType::NOT_LOGGED_IN, 532 => FtpStatusType::STORING_NEED_ACCOUNT, 550 => FtpStatusType::FILE_UNAVAILABLE, 551 => FtpStatusType::PAGE_TYPE_UNKNOWN, 552 => FtpStatusType::EXCEEDED_STORAGE, 553 => FtpStatusType::BAD_FILENAME, _ => FtpStatusType::REPLY_ERROR } } } /// Enum representing FTP commands. #[allow(dead_code)] pub enum FtpCommandType { ABOR, ACCT, LIST, MLSD, PASS, PASV, PWD, QUIT, SYST, USER, } impl FtpCommandType { pub fn value(&self) -> String { match *self { FtpCommandType::ABOR => "ABOR".to_owned(), FtpCommandType::ACCT => "ACCT".to_owned(), FtpCommandType::LIST => "LIST".to_owned(), FtpCommandType::MLSD => "MLSD".to_owned(), FtpCommandType::PASS => "PASS".to_owned(), FtpCommandType::PASV => "PASV".to_owned(), FtpCommandType::PWD => "PWD".to_owned(), FtpCommandType::QUIT => "QUIT".to_owned(), FtpCommandType::SYST => "SYST".to_owned(), FtpCommandType::USER => "USER".to_owned(), } } } /// Struct representing a ftp connection /// /// # Examples /// /// ``` /// let mut conf: Configuration = Configuration { /// username: "anonymous".to_string(), /// password: "anonymous".to_string(), /// host: IpAddr::V4(Ipv4Addr::new(127,0,0,1)), /// port: 21 /// }; /// let mut ftp: FtpStream = FtpStream::build(conf).unwrap(); /// /// ... /// ``` #[derive(Debug)] pub struct FtpStream { configuration: Configuration, command_stream: Option<TcpStream>, data_stream: Option<TcpStream>, is_authenticated: bool, is_connected: bool, is_pasv: bool } impl Drop for FtpStream { fn drop(&mut self) { self.close(); } } #[allow(dead_code)] impl FtpStream { /// Open stream to server and auth. /// /// # Examples /// /// ``` /// let mut conf: Configuration = Configuration { /// username: "anonymous".to_string(), /// password: "anonymous".to_string(), /// host: IpAddr::V4(Ipv4Addr::new(127,0,0,1)), /// port: 21 /// }; /// let mut ftp: FtpStream = FtpStream::build(conf).unwrap(); /// /// ftp.start(); /// /// ... /// ``` pub fn start(&mut self) -> bool { if self.open() && self.is_connected { self.auth() } else { self.is_connected.clone() } } /// Open stream to server. /// /// # Examples /// /// ``` /// let mut conf: Configuration = Configuration { /// username: "anonymous".to_string(), /// password: "anonymous".to_string(), /// host: IpAddr::V4(Ipv4Addr::new(127,0,0,1)), /// port: 21 /// }; /// let mut ftp: FtpStream = FtpStream::build(conf).unwrap(); /// /// ftp.conn(); /// /// ... /// ``` pub fn open(&mut self) -> bool { match self.command_stream { None => { let conn = TcpStream::connect(SocketAddr::new(self.configuration.host,self.configuration.port)); match conn { Ok(mut c) => { let res = self.read_reply(Some(&mut c)); if res.code == FtpStatusType::READY { self.is_connected = true; self.command_stream = Some(c); } }, Err(_e) => { } } }, _ => { } }; self.is_connected } /// Close stream to server. /// /// # Examples /// /// ``` /// let mut conf: Configuration = Configuration { /// username: "anonymous".to_string(), /// password: "anonymous".to_string(), /// host: IpAddr::V4(Ipv4Addr::new(127,0,0,1)), /// port: 21 /// }; /// let mut ftp: FtpStream = FtpStream::build(conf).unwrap(); /// /// ... /// /// ftp.close(); /// ``` pub fn close(&mut self) -> bool { self.command_stream = match self.command_stream.take() { Some(mut c) => { let res = self.raw_cmd(Some(&mut c), FtpCommandType::QUIT, None); match res { Ok(status) => { if status.code == FtpStatusType::CLOSING { c.shutdown(Shutdown::Both); None } else { Some(c) } }, Err(_e) => { Some(c) } } }, None => { None } }; if self.command_stream.is_none() { self.data_stream = match self.data_stream.take() { Some(c) => { c.shutdown(Shutdown::Both); None }, None => { None } }; self.is_authenticated = false; self.is_connected = false; } self.command_stream.is_none() && self.data_stream.is_none() && self.is_connected == false && self.is_authenticated == false } /// Auth user to server. /// /// # Examples /// /// ``` /// let mut conf: Configuration = Configuration { /// username: "anonymous".to_string(), /// password: "anonymous".to_string(), /// host: IpAddr::V4(Ipv4Addr::new(127,0,0,1)), /// port: 21 /// }; /// let mut ftp: FtpStream = FtpStream::build(conf).unwrap(); /// /// ... /// /// ftp.auth(); /// ``` pub fn auth(&mut self) -> bool { self.command_stream = match self.command_stream.take() { Some(mut c) => { let username: String = self.configuration.username.clone(); let password: String = self.configuration.password.clone(); let mut res: Result<FtpStatus, FtpStatus>; res = self.raw_cmd(Some(&mut c), FtpCommandType::USER, Some(username)); match res { Ok(status) => { if status.code == FtpStatusType::NEED_PASSWORD { res = self.raw_cmd(Some(&mut c), FtpCommandType::PASS, Some(password)); match res { Ok(status) => { if status.code == FtpStatusType::LOGGED_ON { self.is_authenticated = true; } }, Err(_e) => { self.is_authenticated = false; } } } }, Err(_e) => { self.is_authenticated = false; } } Some(c) }, None => { None } }; self.is_authenticated.clone() } pub fn list(&mut self) { self.command_stream = match self.command_stream.take() { Some(mut c) => { self.raw_cmd(Some(&mut c), FtpCommandType::LIST, None); Some(c) }, None => { None } }; } pub fn pasv(&mut self, pasv: bool) { self.command_stream = match self.command_stream.take() { Some(mut c) => { self.raw_cmd(Some(&mut c), FtpCommandType::PASV, Some(if pasv { "true".to_owned() } else { "false".to_owned() })); self.is_pasv = pasv; Some(c) }, None => { None } }; } pub fn pwd(&mut self) { self.command_stream = match self.command_stream.take() { Some(mut c) => { self.raw_cmd(Some(&mut c), FtpCommandType::PWD, None); Some(c) }, None => { None } }; } pub fn syst(&mut self) { self.command_stream = match self.command_stream.take() { Some(mut c) => { self.raw_cmd(Some(&mut c), FtpCommandType::SYST, None); Some(c) }, None => { None } }; } fn raw_cmd(&mut self, stream: Option<&mut TcpStream>, command: FtpCommandType, parameters: Option<String>) -> Result<FtpStatus, FtpStatus> { let err: FtpStatus = FtpStatus::build(FtpStatusType::REPLY_ERROR, "Error while reading server reply".to_owned(), "Error while reading server reply".to_owned()); match stream { Some(mut c) => { let mut full_command: String = String::new(); full_command.push_str(&command.value()); match parameters { Some(mut p) => { let re = Regex::new(r"(\r|\r\n|\n)").unwrap(); p = re.replace_all(&p, "").into_owned(); full_command.push_str(" "); full_command.push_str(&p); }, None => {} }; full_command.push_str("\n"); let ret = c.write(full_command.as_bytes()); match ret { Ok(_content) => { //if content > 0 { println!("{:?}", self.read_reply(Some(&mut c))); } Ok(self.read_reply(Some(&mut c))) }, _ => { Err(err) } } }, _ => { Err(err) } } } fn read_reply(&mut self, stream: Option<&mut TcpStream>) -> FtpStatus { let err: FtpStatus = FtpStatus::build(FtpStatusType::REPLY_ERROR, "Error while reading server reply".to_owned(), "Error while reading server reply".to_owned()); let res: FtpStatus; match stream { Some(c) => { let mut response: [u8; 16] = [0;16]; let mut full_message: String = "".to_owned(); let re_msg = Regex::new(r"\d{3}\x20.*(\r|\r\n|\n)").unwrap(); let re_eol = Regex::new(r".?(\r|\r\n|\n)").unwrap(); while { match c.read(&mut response) { Ok(bytes) => { match str::from_utf8(&response) { Ok(val) => { full_message.push_str(&val[..bytes]); } Err(_e) => { } } }, Err(_e) => { } }; full_message.len() > 0 && re_eol.find(&full_message[(full_message.len() - 2)..]) == None && re_msg.find(&full_message) == None } { response = [0;16]; } let mut message: String = "".to_owned(); match re_msg.find(&full_message){ Some(m) => { message = m.as_str().to_owned(); }, None => {} }; if full_message.len() != 0 && message.len() != 0 { res = FtpStatus::build(FtpStatusType::from_value(message[0..3].parse::<u16>().unwrap()), message[4..].to_owned(), full_message); } else { res = err; } }, _ => { res = err; } } res } /// Instanciate an `FtpStream` struct from parameters /// /// # Examples /// /// ``` /// let mut c: Configuration = Configuration { /// username: "anonymous".to_string(), /// password: "anonymous\n".to_string(), /// host: IpAddr::V4(Ipv4Addr::new(127,0,0,1)), /// port: 21 /// }; /// /// let mut ftp: FtpStream = FtpStream::build(c).unwrap(); /// /// ... /// ``` pub fn build (conf: Configuration) -> Result<FtpStream, FtpStream> { Ok(FtpStream { configuration: conf, command_stream: None, data_stream: None, is_connected: false, is_authenticated: false, is_pasv: false }) } }
// Defines the action requested from the database server. // Is documented as Message Type. // Irrelevant RequestTypes (abap related, "reserved" stuff) are omitted. #[derive(Copy, Clone, Debug)] pub enum RequestType { ExecuteDirect = 2, // Directly execute SQL statement Prepare = 3, // Prepare an SQL statement Execute = 13, // Execute a previously prepared SQL statement ReadLob = 16, // Reads large object data WriteLob = 17, // Writes large object data Authenticate = 65, // Sends authentication data Connect = 66, // Connects to the database CloseResultSet = 69, // Closes resultset DropStatementId = 70, // Drops prepared statement identifier FetchNext = 71, // Fetches next data from resultset Disconnect = 77, // Disconnects session DbConnectInfo = 82, // Request/receive database connect information #[cfg(feature = "dist_tx")] XAStart = 83, #[cfg(feature = "dist_tx")] XAEnd = 84, #[cfg(feature = "dist_tx")] XAPrepare = 85, #[cfg(feature = "dist_tx")] XACommit = 86, #[cfg(feature = "dist_tx")] XARollback = 87, #[cfg(feature = "dist_tx")] XARecover = 88, #[cfg(feature = "dist_tx")] XAForget = 89, // OldXaStart = 5, // Start a distributed transaction // OldXaJoin = 6, // Join a distributed transaction // FindLob = 18, // Finds data in a large object // Commit = 67, // Commits current transaction // Rollback = 68, // Rolls back current transaction // FetchAbsolute = 72, // Moves the cursor to the given row number and fetches the data // FetchRelative = 73, // Like above, but moves the cursor relative to the current position // FetchFirst = 74, // Moves the cursor to the first row and fetches the data // FetchLast = 75, // Moves the cursor to the last row and fetches the data }
use std::collections::VecDeque; use input_i_scanner::InputIScanner; use join::Join; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),+); $n: expr) => { std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>() }; ($t: ty; $n: expr) => { std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>() }; } let (n, q) = scan!((usize, usize)); let mut g = vec![vec![]; n]; for _ in 0..(n - 1) { let (a, b) = scan!((usize, usize)); g[a - 1].push(b - 1); g[b - 1].push(a - 1); } let mut score = vec![0; n]; for _ in 0..q { let (p, x) = scan!((usize, u64)); score[p - 1] += x; } let mut que = VecDeque::new(); que.push_back((0, 0)); while let Some((cur, prev)) = que.pop_front() { for &nxt in &g[cur] { if nxt == prev { continue; } score[nxt] += score[cur]; que.push_back((nxt, cur)); } } println!("{}", score.iter().join(" ")); }
use crate::{AST, FALSE, TRUE}; fn numeric_op(lhs: AST, rhs: AST, f: fn(i64, i64) -> i64) -> Result<AST, String> { match (lhs, rhs) { (AST::Const(l), AST::Const(r)) => Ok(AST::Const(f(l, r))), (_, _) => Err("type error".to_string()), } } fn unpack2(mut args: Vec<AST>) -> Result<(AST, AST), String> { if args.len() == 2 { let arg1 = args.pop().ok_or("err".to_string())?; let arg0 = args.pop().ok_or("err".to_string())?; Ok((arg0, arg1)) } else { Err(format!("wrong arity: expected {}, got {}", 2, args.len())) } } fn unpack1(mut args: Vec<AST>) -> Result<AST, String> { if args.len() == 1 { let arg0 = args.pop().ok_or("err".to_string())?; Ok(arg0) } else { Err(format!("wrong arity: expected {}, got {}", 1, args.len())) } } pub fn print(args: Vec<AST>) -> Result<AST, String> { let value = unpack1(args)?; println!("{}", crate::repr(value)); Ok(AST::Nil) } pub fn add(args: Vec<AST>) -> Result<AST, String> { let (lhs, rhs) = unpack2(args)?; numeric_op(lhs, rhs, |x, y| x + y) } pub fn sub(args: Vec<AST>) -> Result<AST, String> { let (lhs, rhs) = unpack2(args)?; numeric_op(lhs, rhs, |x, y| x - y) } pub fn mul(args: Vec<AST>) -> Result<AST, String> { let (lhs, rhs) = unpack2(args)?; numeric_op(lhs, rhs, |x, y| x * y) } pub fn eq(args: Vec<AST>) -> Result<AST, String> { let (lhs, rhs) = unpack2(args)?; if lhs == rhs { Ok(TRUE()) } else { Ok(FALSE()) } } pub fn gt(args: Vec<AST>) -> Result<AST, String> { let (lhs, rhs) = unpack2(args)?; match (lhs, rhs) { (AST::Const(l), AST::Const(r)) => { if l > r { Ok(TRUE()) } else { Ok(FALSE()) } } (AST::Lit(l), AST::Lit(r)) => { if l > r { Ok(TRUE()) } else { Ok(FALSE()) } } (_, _) => Err("type error".to_string()), } } pub fn lt(args: Vec<AST>) -> Result<AST, String> { let (lhs, rhs) = unpack2(args)?; match (lhs, rhs) { (AST::Const(l), AST::Const(r)) => { if l < r { Ok(TRUE()) } else { Ok(FALSE()) } } (AST::Lit(l), AST::Lit(r)) => { if l < r { Ok(TRUE()) } else { Ok(FALSE()) } } (_, _) => Err("type error".to_string()), } }
pub mod utilities; use crate::utilities::Verify; use proffer::*; #[test] fn basic_gen() { let tr8t = Trait::new("Foo").set_is_pub(true).to_owned(); let expected = r#" pub trait Foo { } "#; let src_code = tr8t.generate_and_verify(); println!("{}", &src_code); assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code)); } #[test] fn gen_with_method_signatures() { let tr8t = Trait::new("Foo") .set_is_pub(true) .add_signature(FunctionSignature::new("foo")) .add_signature(FunctionSignature::new("bar")) .to_owned(); let expected = r#" pub trait Foo { fn foo() -> (); fn bar() -> (); } "#; let src_code = tr8t.generate_and_verify(); println!("{}", &src_code); assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code)); } #[test] fn gen_with_generics() { let tr8t = Trait::new("Foo") .set_is_pub(true) .add_signature( FunctionSignature::new("foo") .add_parameter(Parameter::new("name", "T")) .to_owned(), ) .add_signature(FunctionSignature::new("bar")) .add_generic( Generic::new("T") .add_trait_bounds(vec!["ToString"]) .to_owned(), ) .to_owned(); let expected = r#" pub trait Foo<T> where T: ToString, { fn foo(name: T) -> (); fn bar() -> (); } "#; let src_code = tr8t.generate_and_verify(); println!("{}", &src_code); assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code)); } #[test] fn gen_with_associated_types() { let tr8t = Trait::new("Foo") .set_is_pub(true) .add_associated_type(AssociatedTypeDeclaration::new("FOO")) .add_associated_type( AssociatedTypeDeclaration::new("BAR") .add_trait_bounds(vec!["Debug"]) .to_owned(), ) .add_associated_type( AssociatedTypeDeclaration::new("BAZ") .add_trait_bounds(vec!["Debug", "Default"]) .to_owned(), ) .to_owned(); let expected = r#" pub trait Foo { type FOO; type BAR: Debug; type BAZ: Debug + Default; } "#; let src_code = tr8t.generate_and_verify(); println!("{}", &src_code); assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code)); } #[test] fn gen_with_associated_type_attributes() { let tr8t = Trait::new("Foo") .set_is_pub(true) .add_associated_type( AssociatedTypeDeclaration::new("BAR") .add_attribute("#[bar]") .to_owned(), ) .add_associated_type( AssociatedTypeDeclaration::new("BAZ") .add_attribute("#[bar]") .add_attribute("#[baz]") .to_owned(), ) .to_owned(); let expected = r#" pub trait Foo { #[bar] type BAR; #[bar] #[baz] type BAZ; } "#; let src_code = tr8t.generate_and_verify(); println!("{}", &src_code); assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code)); }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type IWebAccountProviderBaseReportOperation = *mut ::core::ffi::c_void; pub type IWebAccountProviderOperation = *mut ::core::ffi::c_void; pub type IWebAccountProviderSilentReportOperation = *mut ::core::ffi::c_void; pub type IWebAccountProviderTokenObjects = *mut ::core::ffi::c_void; pub type IWebAccountProviderTokenObjects2 = *mut ::core::ffi::c_void; pub type IWebAccountProviderTokenOperation = *mut ::core::ffi::c_void; pub type IWebAccountProviderUIReportOperation = *mut ::core::ffi::c_void; pub type WebAccountClientView = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct WebAccountClientViewType(pub i32); impl WebAccountClientViewType { pub const IdOnly: Self = Self(0i32); pub const IdAndProperties: Self = Self(1i32); } impl ::core::marker::Copy for WebAccountClientViewType {} impl ::core::clone::Clone for WebAccountClientViewType { fn clone(&self) -> Self { *self } } pub type WebAccountProviderAddAccountOperation = *mut ::core::ffi::c_void; pub type WebAccountProviderDeleteAccountOperation = *mut ::core::ffi::c_void; pub type WebAccountProviderGetTokenSilentOperation = *mut ::core::ffi::c_void; pub type WebAccountProviderManageAccountOperation = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct WebAccountProviderOperationKind(pub i32); impl WebAccountProviderOperationKind { pub const RequestToken: Self = Self(0i32); pub const GetTokenSilently: Self = Self(1i32); pub const AddAccount: Self = Self(2i32); pub const ManageAccount: Self = Self(3i32); pub const DeleteAccount: Self = Self(4i32); pub const RetrieveCookies: Self = Self(5i32); pub const SignOutAccount: Self = Self(6i32); } impl ::core::marker::Copy for WebAccountProviderOperationKind {} impl ::core::clone::Clone for WebAccountProviderOperationKind { fn clone(&self) -> Self { *self } } pub type WebAccountProviderRequestTokenOperation = *mut ::core::ffi::c_void; pub type WebAccountProviderRetrieveCookiesOperation = *mut ::core::ffi::c_void; pub type WebAccountProviderSignOutAccountOperation = *mut ::core::ffi::c_void; pub type WebAccountProviderTriggerDetails = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct WebAccountScope(pub i32); impl WebAccountScope { pub const PerUser: Self = Self(0i32); pub const PerApplication: Self = Self(1i32); } impl ::core::marker::Copy for WebAccountScope {} impl ::core::clone::Clone for WebAccountScope { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct WebAccountSelectionOptions(pub u32); impl WebAccountSelectionOptions { pub const Default: Self = Self(0u32); pub const New: Self = Self(1u32); } impl ::core::marker::Copy for WebAccountSelectionOptions {} impl ::core::clone::Clone for WebAccountSelectionOptions { fn clone(&self) -> Self { *self } } pub type WebProviderTokenRequest = *mut ::core::ffi::c_void; pub type WebProviderTokenResponse = *mut ::core::ffi::c_void;
pub mod squaring { pub mod sub_squaring { pub fn square(input_1:u32) { println!("Square of the {} is: {}",input_1,input_1*input_1 ); } } }
use std::collections::HashMap; use std::hash::{Hasher, Hash}; use std::rc::Rc; use std::fmt; use crate::class_file::unvalidated; use crate::class_file::unvalidated::ConstantIdx; use crate::class_file::unvalidated::{ClassFile as UnvalidatedClassFile}; use crate::virtual_machine::VMError; use crate::virtual_machine::VMState; use crate::virtual_machine::VirtualMachine; mod instruction; pub use instruction::Instruction; mod constant; pub use constant::Constant; mod method; pub use method::MethodBody; pub use method::MethodHandle; pub use method::MethodInstrIter; pub use method::MethodRef; mod field; pub use field::FieldHandle; pub use field::FieldRef; fn validate_inst(handle: &MethodBody, position: u32, raw_inst: &unvalidated::Instruction) -> Option<Instruction> { let res = match raw_inst { unvalidated::Instruction::Nop => Instruction::Nop, unvalidated::Instruction::AConstNull => Instruction::AConstNull, unvalidated::Instruction::IConstM1 => Instruction::IConstM1, unvalidated::Instruction::IConst0 => Instruction::IConst0, unvalidated::Instruction::IConst1 => Instruction::IConst1, unvalidated::Instruction::IConst2 => Instruction::IConst2, unvalidated::Instruction::IConst3 => Instruction::IConst3, unvalidated::Instruction::IConst4 => Instruction::IConst4, unvalidated::Instruction::IConst5 => Instruction::IConst5, unvalidated::Instruction::LConst0 => Instruction::LConst0, unvalidated::Instruction::LConst1 => Instruction::LConst1, unvalidated::Instruction::FConst0 => Instruction::FConst0, unvalidated::Instruction::FConst1 => Instruction::FConst1, unvalidated::Instruction::FConst2 => Instruction::FConst2, unvalidated::Instruction::DConst0 => Instruction::DConst0, unvalidated::Instruction::DConst1 => Instruction::DConst1, unvalidated::Instruction::BIPush(v) => Instruction::BIPush(*v), unvalidated::Instruction::SIPush(v) => Instruction::SIPush(*v), unvalidated::Instruction::Ldc(_) => Instruction::Ldc(Rc::clone(&handle.const_refs[&position])), unvalidated::Instruction::LdcW(_) => Instruction::LdcW(Rc::clone(&handle.const_refs[&position])), unvalidated::Instruction::Ldc2W(_) => Instruction::Ldc2W(Rc::clone(&handle.const_refs[&position])), unvalidated::Instruction::ILoad(v) => Instruction::ILoad(*v), unvalidated::Instruction::LLoad(v) => Instruction::LLoad(*v), unvalidated::Instruction::FLoad(v) => Instruction::FLoad(*v), unvalidated::Instruction::DLoad(v) => Instruction::DLoad(*v), unvalidated::Instruction::ALoad(v) => Instruction::ALoad(*v), unvalidated::Instruction::ILoad0 => Instruction::ILoad0, unvalidated::Instruction::ILoad1 => Instruction::ILoad1, unvalidated::Instruction::ILoad2 => Instruction::ILoad2, unvalidated::Instruction::ILoad3 => Instruction::ILoad3, unvalidated::Instruction::LLoad0 => Instruction::LLoad0, unvalidated::Instruction::LLoad1 => Instruction::LLoad1, unvalidated::Instruction::LLoad2 => Instruction::LLoad2, unvalidated::Instruction::LLoad3 => Instruction::LLoad3, unvalidated::Instruction::FLoad0 => Instruction::FLoad0, unvalidated::Instruction::FLoad1 => Instruction::FLoad1, unvalidated::Instruction::FLoad2 => Instruction::FLoad2, unvalidated::Instruction::FLoad3 => Instruction::FLoad3, unvalidated::Instruction::DLoad0 => Instruction::DLoad0, unvalidated::Instruction::DLoad1 => Instruction::DLoad1, unvalidated::Instruction::DLoad2 => Instruction::DLoad2, unvalidated::Instruction::DLoad3 => Instruction::DLoad3, unvalidated::Instruction::ALoad0 => Instruction::ALoad0, unvalidated::Instruction::ALoad1 => Instruction::ALoad1, unvalidated::Instruction::ALoad2 => Instruction::ALoad2, unvalidated::Instruction::ALoad3 => Instruction::ALoad3, unvalidated::Instruction::IAStore => Instruction::IAStore, unvalidated::Instruction::IALoad => Instruction::IALoad, unvalidated::Instruction::LALoad => Instruction::LALoad, unvalidated::Instruction::FALoad => Instruction::FALoad, unvalidated::Instruction::DALoad => Instruction::DALoad, unvalidated::Instruction::AALoad => Instruction::AALoad, unvalidated::Instruction::BALoad => Instruction::BALoad, unvalidated::Instruction::CALoad => Instruction::CALoad, unvalidated::Instruction::SALoad => Instruction::SALoad, unvalidated::Instruction::IStore(v) => Instruction::IStore(*v), unvalidated::Instruction::LStore(v) => Instruction::LStore(*v), unvalidated::Instruction::FStore(v) => Instruction::FStore(*v), unvalidated::Instruction::DStore(v) => Instruction::DStore(*v), unvalidated::Instruction::AStore(v) => Instruction::AStore(*v), unvalidated::Instruction::IStore0 => Instruction::IStore0, unvalidated::Instruction::IStore1 => Instruction::IStore1, unvalidated::Instruction::IStore2 => Instruction::IStore2, unvalidated::Instruction::IStore3 => Instruction::IStore3, unvalidated::Instruction::LStore0 => Instruction::LStore0, unvalidated::Instruction::LStore1 => Instruction::LStore1, unvalidated::Instruction::LStore2 => Instruction::LStore2, unvalidated::Instruction::LStore3 => Instruction::LStore3, unvalidated::Instruction::FStore0 => Instruction::FStore0, unvalidated::Instruction::FStore1 => Instruction::FStore1, unvalidated::Instruction::FStore2 => Instruction::FStore2, unvalidated::Instruction::FStore3 => Instruction::FStore3, unvalidated::Instruction::DStore0 => Instruction::DStore0, unvalidated::Instruction::DStore1 => Instruction::DStore1, unvalidated::Instruction::DStore2 => Instruction::DStore2, unvalidated::Instruction::DStore3 => Instruction::DStore3, unvalidated::Instruction::AStore0 => Instruction::AStore0, unvalidated::Instruction::AStore1 => Instruction::AStore1, unvalidated::Instruction::AStore2 => Instruction::AStore2, unvalidated::Instruction::AStore3 => Instruction::AStore3, unvalidated::Instruction::LAStore => Instruction::LAStore, unvalidated::Instruction::FAStore => Instruction::FAStore, unvalidated::Instruction::DAStore => Instruction::DAStore, unvalidated::Instruction::AAStore => Instruction::AAStore, unvalidated::Instruction::BAStore => Instruction::BAStore, unvalidated::Instruction::CAStore => Instruction::CAStore, unvalidated::Instruction::SAStore => Instruction::SAStore, unvalidated::Instruction::Pop => Instruction::Pop, unvalidated::Instruction::Pop2 => Instruction::Pop2, unvalidated::Instruction::Dup => Instruction::Dup, unvalidated::Instruction::DupX1 => Instruction::DupX1, unvalidated::Instruction::DupX2 => Instruction::DupX2, unvalidated::Instruction::Dup2 => Instruction::Dup2, unvalidated::Instruction::Dup2X1 => Instruction::Dup2X1, unvalidated::Instruction::Dup2X2 => Instruction::Dup2X2, unvalidated::Instruction::Swap => Instruction::Swap, unvalidated::Instruction::IAdd => Instruction::IAdd, unvalidated::Instruction::LAdd => Instruction::LAdd, unvalidated::Instruction::FAdd => Instruction::FAdd, unvalidated::Instruction::DAdd => Instruction::DAdd, unvalidated::Instruction::ISub => Instruction::ISub, unvalidated::Instruction::LSub => Instruction::LSub, unvalidated::Instruction::FSub => Instruction::FSub, unvalidated::Instruction::DSub => Instruction::DSub, unvalidated::Instruction::IMul => Instruction::IMul, unvalidated::Instruction::LMul => Instruction::LMul, unvalidated::Instruction::FMul => Instruction::FMul, unvalidated::Instruction::DMul => Instruction::DMul, unvalidated::Instruction::IDiv => Instruction::IDiv, unvalidated::Instruction::LDiv => Instruction::LDiv, unvalidated::Instruction::FDiv => Instruction::FDiv, unvalidated::Instruction::DDiv => Instruction::DDiv, unvalidated::Instruction::IRem => Instruction::IRem, unvalidated::Instruction::LRem => Instruction::LRem, unvalidated::Instruction::FRem => Instruction::FRem, unvalidated::Instruction::DRem => Instruction::DRem, unvalidated::Instruction::INeg => Instruction::INeg, unvalidated::Instruction::LNeg => Instruction::LNeg, unvalidated::Instruction::FNeg => Instruction::FNeg, unvalidated::Instruction::DNeg => Instruction::DNeg, unvalidated::Instruction::IShl => Instruction::IShl, unvalidated::Instruction::LShl => Instruction::LShl, unvalidated::Instruction::IShr => Instruction::IShr, unvalidated::Instruction::LShr => Instruction::LShr, unvalidated::Instruction::IUshr => Instruction::IUshr, unvalidated::Instruction::LUshr => Instruction::LUshr, unvalidated::Instruction::IAnd => Instruction::IAnd, unvalidated::Instruction::LAnd => Instruction::LAnd, unvalidated::Instruction::IOr => Instruction::IOr, unvalidated::Instruction::LOr => Instruction::LOr, unvalidated::Instruction::IXor => Instruction::IXor, unvalidated::Instruction::LXor => Instruction::LXor, unvalidated::Instruction::IInc(v1, v2) => Instruction::IInc(*v1, *v2), unvalidated::Instruction::I2L => Instruction::I2L, unvalidated::Instruction::I2F => Instruction::I2F, unvalidated::Instruction::I2D => Instruction::I2D, unvalidated::Instruction::L2I => Instruction::L2I, unvalidated::Instruction::L2F => Instruction::L2F, unvalidated::Instruction::L2D => Instruction::L2D, unvalidated::Instruction::F2I => Instruction::F2I, unvalidated::Instruction::F2L => Instruction::F2L, unvalidated::Instruction::F2D => Instruction::F2D, unvalidated::Instruction::D2I => Instruction::D2I, unvalidated::Instruction::D2L => Instruction::D2L, unvalidated::Instruction::D2F => Instruction::D2F, unvalidated::Instruction::I2B => Instruction::I2B, unvalidated::Instruction::I2C => Instruction::I2C, unvalidated::Instruction::I2S => Instruction::I2S, unvalidated::Instruction::ICmp => Instruction::ICmp, unvalidated::Instruction::FCmpL => Instruction::FCmpL, unvalidated::Instruction::FCmpG => Instruction::FCmpG, unvalidated::Instruction::DCmpL => Instruction::DCmpL, unvalidated::Instruction::DCmpG => Instruction::DCmpG, unvalidated::Instruction::IfEq(v) => Instruction::IfEq(*v), unvalidated::Instruction::IfNe(v) => Instruction::IfNe(*v), unvalidated::Instruction::IfLt(v) => Instruction::IfLt(*v), unvalidated::Instruction::IfGe(v) => Instruction::IfGe(*v), unvalidated::Instruction::IfGt(v) => Instruction::IfGt(*v), unvalidated::Instruction::IfLe(v) => Instruction::IfLe(*v), unvalidated::Instruction::IfIcmpEq(v) => Instruction::IfIcmpEq(*v), unvalidated::Instruction::IfIcmpNe(v) => Instruction::IfIcmpNe(*v), unvalidated::Instruction::IfIcmpLt(v) => Instruction::IfIcmpLt(*v), unvalidated::Instruction::IfIcmpGe(v) => Instruction::IfIcmpGe(*v), unvalidated::Instruction::IfIcmpGt(v) => Instruction::IfIcmpGt(*v), unvalidated::Instruction::IfIcmpLe(v) => Instruction::IfIcmpLe(*v), unvalidated::Instruction::IfAcmpEq(v) => Instruction::IfAcmpEq(*v), unvalidated::Instruction::IfAcmpNe(v) => Instruction::IfAcmpNe(*v), unvalidated::Instruction::Goto(v) => Instruction::Goto(*v), unvalidated::Instruction::Jsr(v) => Instruction::Jsr(*v), unvalidated::Instruction::Ret(v) => Instruction::Ret(*v), unvalidated::Instruction::TableSwitch(v1, v2, v3, v4) => Instruction::TableSwitch(*v1, *v2, *v3, v4.clone()), unvalidated::Instruction::LookupSwitch(v1, v2) => Instruction::LookupSwitch(*v1, v2.clone()), unvalidated::Instruction::IReturn => Instruction::IReturn, unvalidated::Instruction::LReturn => Instruction::LReturn, unvalidated::Instruction::FReturn => Instruction::FReturn, unvalidated::Instruction::DReturn => Instruction::DReturn, unvalidated::Instruction::AReturn => Instruction::AReturn, unvalidated::Instruction::Return => Instruction::Return, unvalidated::Instruction::GetStatic(_) => Instruction::GetStatic(Rc::clone(&handle.field_refs[&position])), unvalidated::Instruction::PutStatic(_) => Instruction::PutStatic(Rc::clone(&handle.field_refs[&position])), unvalidated::Instruction::GetField(_) => Instruction::GetField(Rc::clone(&handle.field_refs[&position])), unvalidated::Instruction::PutField(_) => Instruction::PutField(Rc::clone(&handle.field_refs[&position])), unvalidated::Instruction::InvokeVirtual(_) => Instruction::InvokeVirtual(Rc::clone(&handle.method_refs[&position])), unvalidated::Instruction::InvokeSpecial(_) => Instruction::InvokeSpecial(Rc::clone(&handle.method_refs[&position])), unvalidated::Instruction::InvokeStatic(_) => Instruction::InvokeStatic(Rc::clone(&handle.method_refs[&position])), unvalidated::Instruction::InvokeInterface(v1, v2) => Instruction::InvokeInterface(*v1, *v2), unvalidated::Instruction::InvokeDynamic(v) => Instruction::InvokeDynamic(*v), unvalidated::Instruction::New(_) => Instruction::New(Rc::clone(&handle.class_refs[&position])), unvalidated::Instruction::NewArray(v) => Instruction::NewArray(*v), unvalidated::Instruction::ANewArray => Instruction::ANewArray, unvalidated::Instruction::ArrayLength => Instruction::ArrayLength, unvalidated::Instruction::AThrow => Instruction::AThrow, unvalidated::Instruction::CheckCast(_) => Instruction::CheckCast(Rc::clone(&handle.class_refs[&position])), unvalidated::Instruction::InstanceOf(_) => Instruction::InstanceOf(Rc::clone(&handle.class_refs[&position])), unvalidated::Instruction::MonitorEnter => Instruction::MonitorEnter, unvalidated::Instruction::MonitorExit => Instruction::MonitorExit, unvalidated::Instruction::MultiANewArray(_, v) => Instruction::MultiANewArray(Rc::clone(&handle.class_refs[&position]), *v), unvalidated::Instruction::IfNull(v) => Instruction::IfNull(*v), unvalidated::Instruction::IfNonNull(v) => Instruction::IfNonNull(*v), unvalidated::Instruction::GotoW(v) => Instruction::GotoW(*v), unvalidated::Instruction::JsrW(v) => Instruction::JsrW(*v), }; Some(res) } pub struct ClassFile { pub(crate) this_class: String, super_class: Option<String>, constants: Vec<Rc<Constant>>, interfaces: Vec<String>, pub(crate) fields: Vec<Rc<FieldHandle>>, methods: Vec<Rc<MethodHandle>>, // currently support no attributes on classes attributes: Vec<()>, pub(crate) native_methods: HashMap<String, fn(&mut VMState, &mut VirtualMachine) -> Result<(), VMError>> } impl fmt::Debug for ClassFile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ClassFile {{ this_class: {:?}, super_class: {:?}, constants: {:?}, interfaces: {:?}, fields: {:?}, methods: {:?}, attributes: {:?}, native_methods: {:?} }}", self.this_class, self.super_class, self.constants, self.interfaces, self.fields, self.methods, self.attributes, self.native_methods.keys() ) } } #[derive(Debug)] pub enum ValidationError { BadString, BadIndex(ConstantIdx), BadConst(String, String), Unimplemented, InvalidMethod(&'static str), BadAttribute(&'static str), } impl unvalidated::Constant { fn as_utf8(&self) -> Result<&str, ValidationError> { if let unvalidated::Constant::Utf8(data) = self { if let Some(s) = std::str::from_utf8(data).ok() { Ok(s) } else { Err(ValidationError::BadString) } } else { Err(ValidationError::BadConst(self.type_name().to_string(), "Utf8".to_string())) } } } impl UnvalidatedClassFile { fn checked_const<'cls>(&'cls self, idx: ConstantIdx) -> Result<&'cls unvalidated::Constant, ValidationError> { self.get_const(idx) .ok_or(ValidationError::BadIndex(self.this_class)) } } impl ClassFile { pub fn get_method(&self, name: &str, desc: &str) -> Option<Rc<MethodHandle>> { for method in self.methods.iter() { if method.name == name && method.desc == desc { return Some(Rc::clone(method)); } } None } pub fn get_methods(&self, name: &str) -> Vec<Rc<MethodHandle>> { let mut methods = Vec::new(); for method in self.methods.iter() { if method.name == name { methods.push(Rc::clone(method)); } } methods } pub fn has_static_field(&self, name: &str) -> bool { for field in self.fields.iter() { if field.access_flags.is_static() { if field.name == name { return true; } } } false } pub fn validate(raw_class: &UnvalidatedClassFile) -> Result<ClassFile, ValidationError> { // first, `this_class` must be a constant index to a Utf8, containing a well-formed type // descriptor. // TODO: verify type descriptor let this_class = raw_class.checked_const(raw_class.this_class).and_then(|c| match c { unvalidated::Constant::Class(class) => { raw_class.checked_const(*class) }, _ => { panic!("aaa"); } }).and_then(|c| c.as_utf8())?; let super_class = match raw_class.super_class.map(|sup| { raw_class.checked_const(sup).and_then(|c| match c{ unvalidated::Constant::Class(class) => { raw_class.checked_const(*class) }, _ => { panic!("aaa"); } }).and_then(|c| c.as_utf8()) }) { Some(Ok(sup)) => Some(sup), Some(Err(e)) => { return Err(e); }, None => None }; let mut constants = Vec::new(); for raw_const in raw_class.constant_pool.iter() { match raw_const { unvalidated::Constant::String(_) | unvalidated::Constant::Integer(_) | unvalidated::Constant::Long(_) | unvalidated::Constant::Float(_) | unvalidated::Constant::Double(_) => { constants.push(Rc::new(Constant::validate(raw_class, raw_const)?)); } _ => { // preserve indices for ldc and friends constants.push(Rc::new(Constant::Integer(0))); } } } let interfaces = Vec::new(); let mut fields = Vec::new(); for raw_field in raw_class.fields.iter() { fields.push(Rc::new(FieldHandle::validate(raw_class, raw_field)?)); } let mut methods = Vec::new(); for raw_method in raw_class.methods.iter() { methods.push(Rc::new(MethodHandle::validate(raw_class, raw_method)?)); } let attributes = Vec::new(); Ok(ClassFile { this_class: this_class.to_string(), super_class: super_class.map(|x| x.to_string()), constants, interfaces, fields, methods, attributes, native_methods: raw_class.native_methods.clone(), }) } } pub(crate) struct ClassFileRef(Rc<ClassFile>); impl ClassFileRef { pub fn of(reference: &Rc<ClassFile>) -> Self { ClassFileRef(Rc::clone(reference)) } } impl Hash for ClassFileRef { fn hash<H: Hasher>(&self, state: &mut H) { unsafe { let ptr = Rc::into_raw(Rc::clone(&self.0)); ptr.hash(state); Rc::from_raw(ptr); } } } impl Eq for ClassFileRef {} impl PartialEq for ClassFileRef { fn eq(&self, other: &ClassFileRef) -> bool { Rc::ptr_eq(&self.0, &other.0) } }
#![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; pub use self::meeting::Meeting; #[ink::contract] mod meeting { use template::TemplateTrait; use nfticket::NfticketTrait; use ink_env::call::FromAccountId; use ink_prelude::vec::Vec; use primitives::{Meeting as MeetingStruct, MeetingError, CheckRecord, MeetingStatus}; use core::default::Default; use ink_prelude::string::ToString; use ink_storage::collections::{HashMap as StorageMap}; #[ink(storage)] pub struct Meeting { controller: AccountId, template: AccountId, owner: AccountId, price: Balance, // 收费方式=Uniform 时候生效 sold_tickets: u32, // 已经售出多少门票 max_tickets: u32, // 总共可以出售多少车票 inspector_map: StorageMap<AccountId, bool>, // 检票员 // 用户参与后会产生的数据 ticket_map: StorageMap< u32,(u32,u64)>, // 已经售出门票 check_times: StorageMap<(u128, u128), u32>, // 检票次数(获得最大次数后,通过 check_records 轮询可以查到各个检票记录数据) check_records: StorageMap<(u128, u128, u32), CheckRecord> // 检票记录 } impl Meeting { /// Constructor that initializes the `bool` value to the given `init_value`. #[ink(constructor)] pub fn new(owner: AccountId, template: AccountId, controller: AccountId) -> Self { Self { controller: controller, template: template, owner: owner, price: Default::default(), sold_tickets: Default::default(), max_tickets: Default::default(), inspector_map: Default::default(), ticket_map: Default::default(), check_times: Default::default(), check_records: Default::default(), } } /// 修改门票价格、门票总数 #[ink(message)] pub fn modify_meeting(&mut self,max_tickets: u32, price: Balance) -> Result<(), MeetingError>{ self.ensure_owner(); if max_tickets < self.sold_tickets { return Err(MeetingError::LessThanSoldTickets) } let mut template_instance: TemplateTrait = FromAccountId::from_account_id(self.template); if price < template_instance.get_min_create_ticket_fee() { return Err(MeetingError::LessThanCreateTicketFee) } self.max_tickets = max_tickets; self.price = price; Ok(()) } /// 购买门票 #[ink(message, payable)] pub fn buy_ticket(&mut self, amount: u32) -> Result<(), MeetingError>{ let mut nfticket = self.get_nfticket_instance(); let meeting: MeetingStruct = nfticket.get_meeting( self.env().account_id() ); // 必须 active 才能卖票 assert!( meeting.status == MeetingStatus::Active, "InactiveMeeting"); // 必须在售卖时间范围内 assert!( meeting.start_sale_time < self.env().block_timestamp() && meeting.end_sale_time > self.env().block_timestamp(), "OutOfSale" ); // 检查剩余门票是否足够 assert!( self.max_tickets >= (self.sold_tickets + amount), "NotEnoughTicketsLeft"); // 检查付款是否足够 let total = self.price * amount as u128; let transferred: Balance = self.env().transferred_balance(); assert!( total <= transferred , "InsufficientPayment"); // 计算需要用于创建门票的费用 let mut template = self.get_template_instanc(); let create_fee = template.get_min_create_ticket_fee(); // 调用 nfticket 的 create_ticket 创建NFT门票 let caller = self.env().caller(); use ink_lang::ForwardCallMut; // 循环创建门票NFT for _n in 1..amount { self.sold_tickets = self.sold_tickets.checked_add(1).unwrap(); let (class_id, nft_id) = <&mut NfticketTrait>::call_mut(&mut nfticket) .create_ticket(caller, self.sold_tickets.to_string() ) .transferred_value(create_fee) .fire() .unwrap() .unwrap(); // 保存每一张门票 self.ticket_map.insert(self.sold_tickets, (class_id, nft_id)); } Ok(()) } /// 添加检票员 #[ink(message)] pub fn add_inspector(&mut self, inspector: AccountId){ self.ensure_owner(); self.inspector_map.insert(inspector, true); } /// 移除验票员 #[ink(message)] pub fn remove_inspector(&mut self, inspector: AccountId){ self.ensure_owner(); let _ = self.inspector_map.take(&inspector); } /// 验票员验票 #[ink(message)] pub fn check_ticket(&mut self, ticket:(u128, u128), timestamp: u64, sign: Hash) -> Result<(), MeetingError>{ // 必须是验票员 self.ensure_inspector(); // 验票时间必须是当前区块生产前后5分种内 let check_split: u64; if self.env().block_timestamp() > timestamp{ check_split = self.env().block_timestamp() - timestamp; }else{ check_split = timestamp - self.env().block_timestamp(); } assert!( check_split< 300, "CheckTimeout"); // TODO:检查HASH // 添加到验票记录 let caller = self.env().caller(); let recode = CheckRecord{ inspector: caller, timestamp: timestamp, block: self.env().block_number() }; let times = self.check_times.get( &ticket ).unwrap_or(&0u32) + 1u32; self.check_times.insert(ticket, times); self.check_records.insert((ticket.0, ticket.1, times), recode); Ok(()) } /// 转让所有权 #[ink(message)] pub fn transfer_ownership(&mut self, new_owner:AccountId){ self.ensure_owner(); self.owner = new_owner } /// 返回当前拥有人 #[ink(message)] pub fn get_owner(&self) -> AccountId { self.owner } /// 如果不是管理员,就报错 fn ensure_owner(&self) { assert_eq!(self.owner, self.env().caller(), "not owner"); } // 返回一个主合约 fn get_nfticket_instance(&self) -> NfticketTrait{ let nfticket_instance: NfticketTrait = FromAccountId::from_account_id( self.controller ); nfticket_instance } // 返回一个主合约 fn get_template_instanc(&self) -> TemplateTrait{ let template_instance: TemplateTrait = FromAccountId::from_account_id( self.template ); template_instance } /// 检查是否管理员或者检票员 fn ensure_inspector(&self){ let caller = self.env().caller(); if self.owner == caller{ return () } assert!(self.inspector_map.contains_key(&caller), "NotInspector"); } /// 返回模板合约 #[ink(message)] pub fn get_template(&self) -> AccountId { self.template } /// 返回主合约地址 #[ink(message)] pub fn get_controller(&self) -> AccountId { self.controller } /// 返回最大门票数 #[ink(message)] pub fn get_max_tickets(&self) -> u32 { self.max_tickets } /// 返回售出门票数 #[ink(message)] pub fn get_sold_tickets(&self) -> u32 { self.sold_tickets } } }
use std::process::Command; pub fn run_cmd() { let output = Command::new("bash") .arg("-c") .arg("ls /home/susilo") .output() .expect("gagal menjalankan proses"); println!("{}", String::from_utf8_lossy(&output.stdout)); }
use std::cmp::Ordering; use std::fmt::{Display, Formatter, Result}; pub enum Value { NONE, ANY, TRUE, FALSE, } pub struct Hypothesis { pub len: usize, pub values: Vec<Value>, } pub struct Data { pub len: usize, pub values: Vec<bool>, pub result: bool, } impl Data { pub fn new() -> Self { Data { len: 0, values: Vec::new(), result: false } } } impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match self.cmp(other) { Ordering::Equal => true, _ => false, } } } impl Eq for Value {} impl PartialOrd for Value { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } // More general => Greater impl Ord for Value { fn cmp(&self, other: &Self) -> Ordering { match self { Value::ANY => match other { Value::ANY => Ordering::Equal, _ => Ordering::Greater, }, Value::FALSE | Value::TRUE => match other { Value::ANY => Ordering::Less, Value::FALSE | Value::TRUE => Ordering::Equal, Value::NONE => Ordering::Greater, }, Value::NONE => match other { Value::NONE => Ordering::Equal, _ => Ordering::Less, }, } } } impl Hypothesis { pub fn most_general(len: usize) -> Self { let mut values = Vec::new(); for _ in 0..len { values.push(Value::ANY); } Hypothesis { len, values } } pub fn most_specific(len: usize) -> Self { let mut values = Vec::new(); for _ in 0..len { values.push(Value::NONE); } Hypothesis { len, values } } pub fn is_more_general_or_equal(&self, other: &Self) -> Option<bool> { if self.len != other.len { return None; } for i in 0..self.len { if self.values[i] < other.values[i] { return Some(false); } } return Some(true); } } impl Display for Hypothesis { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let mut output = String::from("["); for i in 0..self.len { let character = match self.values[i] { Value::NONE => '\u{3D5}', Value::TRUE => 'T', Value::FALSE => 'F', Value::ANY => '?' }; output.push(character); if i < self.len - 1 { output.push_str(", "); } else { output.push(']'); } } write!(f, "{}", output) } }
extern crate oxygengine_core as core; pub mod animation; pub mod curve; pub mod phase; pub mod spline; pub mod transition; pub mod prelude { pub use crate::animation::*; pub use crate::curve::*; pub use crate::phase::*; pub use crate::spline::*; pub use crate::transition::*; }