lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/cli/utils.rs
lmapii/run_clang_format
153a3fd24813ce4ea8846bf38f1263dcb4f044db
use std::{fs, path}; use color_eyre::{eyre::eyre, eyre::WrapErr}; pub fn path_or_err<P>(path: P) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_as_buf = path::PathBuf::from(path.as_ref()); if !path_as_buf.exists() { return Err(eyre!("Path not found or permission denied")) .wrap_err(format!("'{}' is not a path", path_as_buf.to_string_lossy())); } Ok(path_as_buf) } pub fn file_or_err<P>(path: P) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_as_buf = path::PathBuf::from(path.as_ref()); if !path_as_buf.is_file() { return Err(eyre!("File not found or permission denied")) .wrap_err(format!("'{}' is not a file", path_as_buf.to_string_lossy())); } Ok(path_as_buf) } pub fn dir_or_err<P>(path: P) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_as_buf = path::PathBuf::from(path.as_ref()); let meta = fs::metadata(path.as_ref()).wrap_err(format!( "'{}' is not a directory", path_as_buf.to_string_lossy() ))?; if !meta.is_dir() { return Err(eyre!("Directory not found")).wrap_err(format!( "'{}' is not a directory", path_as_buf.to_string_lossy() )); } Ok(path_as_buf) } pub fn file_with_name<P>(path: P, name: &str) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let buf = file_or_err(path.as_ref())?; let name_str = buf.to_string_lossy(); let file_name = path .as_ref() .file_name() .and_then(std::ffi::OsStr::to_str) .ok_or(eyre!(format!( "Expected file with name '{}', got '{}'", name, name_str )))?; if file_name.to_lowercase() != name.to_lowercase() { return Err(eyre!(format!( "Expected file with name '{}', got '{}'", name, name_str ))); } Ok(buf) } pub fn file_with_ext<P>(path: P, ext: &str, strict: bool) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let buf = file_or_err(path.as_ref())?; let name = buf.to_string_lossy(); let file_ext = path .as_ref() .extension() .and_then(std::ffi::OsStr::to_str) .ok_or(eyre!(format!( "Expected file with extension '{}', got file '{}'", ext, name )))?; let ext_minus = match ext.chars().next() { Some(c) if c == '.' && !strict => &ext[1..], _ => ext, }; if ext_minus.to_lowercase() != file_ext.to_lowercase() { return Err(eyre!(format!( "Expected file extension '{}', got '{}'", ext_minus, file_ext ))); } Ok(buf) } pub fn file_with_name_or_ext<P>(path: P, name_or_ext: &str) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let buf = file_or_err(path.as_ref())?; let f_for_name = file_with_name(path.as_ref(), name_or_ext); let f_for_ext = file_with_ext(path.as_ref(), name_or_ext, false); match f_for_name { Ok(path) => Ok(path), Err(_) => match f_for_ext { Ok(path) => Ok(path), Err(_) => Err(eyre!(format!( "Expected file with name or extension '{}', got '{}'", name_or_ext, buf.to_string_lossy() ))), }, } } pub fn filename_or_exists<P>(path: P, root: Option<P>) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { if path.as_ref().is_absolute() && !path.as_ref().exists() { return Err(eyre::eyre!(format!( "'{}' does not exist", path.as_ref().to_string_lossy() ))); } let is_file = path .as_ref() .file_name() .and_then(|file_name| (path.as_ref().as_os_str() == file_name).then(|| true)) .is_some(); if is_file { return Ok(path.as_ref().to_path_buf()); } if path.as_ref().is_relative() { let full_path = match root { None => path.as_ref().to_path_buf(), Some(root) => { let mut full_path = root.as_ref().to_path_buf(); full_path.push(path.as_ref()); full_path } }; if !full_path.exists() { return Err(eyre::eyre!(format!( "'{}' does not exist", path.as_ref().to_string_lossy() ))); } return Ok(full_path); } Ok(path.as_ref().to_path_buf()) } pub fn filename_or_exists_with_ext<P>( path: P, root: Option<P>, ext: Option<&str>, ) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_buf = path.as_ref().to_path_buf(); let root_buf = root.map(|p| p.as_ref().to_path_buf()); let mut checks = vec![filename_or_exists(path_buf, root_buf.clone())]; if let Some(ext) = ext { let mut try_ext = path.as_ref().to_path_buf(); try_ext.set_extension(ext); checks.push(filename_or_exists(try_ext, root_buf)); } let has_path = checks.iter().find(|result| result.is_ok()); if let Some(cmd) = has_path { return Ok(cmd.as_ref().unwrap().as_path().to_path_buf()); } Err(checks.remove(0).unwrap_err()) } pub fn executable_or_exists<P>(path: P, root: Option<P>) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let ext = if cfg!(windows) { Some("exe") } else { None }; filename_or_exists_with_ext(path, root, ext) } #[cfg(test)] mod tests { use super::*; #[test] fn test_path() { let path = path::Path::new("some/path/to/.clang-format"); let file_name = path.file_name().and_then(std::ffi::OsStr::to_str).unwrap(); assert_eq!(".clang-format", file_name.to_lowercase()); } }
use std::{fs, path}; use color_eyre::{eyre::eyre, eyre::WrapErr}; pub fn path_or_err<P>(path: P) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_as_buf = path::PathBuf::from(path.as_ref()); if !path_as_buf.exists() { return Err(eyre!("Path not found or permission denied")) .wrap_err(format!("'{}' is not a path", path_as_buf.to_string_lossy())); } Ok(path_as_buf) } pub fn file_or_err<P>(path: P) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_as_buf = path::PathBuf::from(path.as_ref()); if !path_as_buf.is_file() { return Err(eyre!("File not found or permission denied")) .wrap_err(format!("'{}' is not a file", path_as_buf.to_string_lossy())); } Ok(path_as_buf) } pub fn dir_or_err<P>(path: P) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_as_buf = path::PathBuf::from(path.as_ref()); let meta = fs::metadata(path.as_ref()).wrap_err(format!( "'{}' is not a directory", path_as_buf.to_string_lossy() ))?; if !meta.is_dir() { return Err(eyre!("Directory not found")).wrap_err(format!( "'{}' is not a directory", path_as_buf.to_string_lossy() )); } Ok(path_as_buf) } pub fn file_with_name<P>(path: P, name: &str) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let buf = file_or_err(path.as_ref())?; let name_str = buf.to_string_lossy(); let file_name = path .as_ref() .file_name() .and_then(std::ffi::OsStr::to_str) .ok_or(eyre!(format!( "Expected file with name '{}', got '{}'", name, name_str )))?; if file_name.to_lowercase() != name.to_lowercase() { return Err(eyre!(format!( "Expected file with name '{}', got '{}'", name, name_str ))); } Ok(buf) } pub fn file_with_ext<P>(path: P, ext: &str, strict: bool) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let buf = file_or_err(path.as_ref())?; let name = buf.to_string_lossy(); let file_ext = path .as_ref() .extension() .and_then(std::ffi::OsStr::to_str) .ok_or(eyre!(format!( "Expected file with extension '{}', got file '{}'", ext, name )))?; let ext_minus = match ext.chars().next() { Some(c) if c == '.' && !strict => &ext[1..], _ => ext, }; if ext_minus.to_lowercase() != file_ext.to_lowercase() { return Err(eyre!(format!( "Expected file extension '{}', got '{}'", ext_minus, file_ext ))); } Ok(buf) } pub fn file_with_name_or_ext<P>(path: P, name_or_ext: &str) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let buf = file_or_err(path.as_ref())?; let f_for_name = file_with_name(path.as_ref(), name_or_ext); let f_for_ext = file_with_ext(path.as_ref(), name_or_ext, false); match f_for_name { Ok(path) => Ok(path), Err(_) => match f_for_ext { Ok(path) => Ok(path), Err(_) => Err(eyre!(format!( "Expected file with name or extension '{}', got '{}'", name_or_ext, buf.to_string_lossy() ))), }, } } pub fn filename_or_exists<P>(path: P, root: Option<P>) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { if path.as_ref().is_absolute() && !path.as_ref().exists() { return Err(eyre::eyre!(format!( "'{}' does not exist", path.as_ref().to_string_lossy() ))); } let is_file = path .as_ref() .file_name() .and_then(|file_name| (path.as_ref().as_os_str() == file_name).then(|| true)) .is_some(); if is_file { return Ok(path.as_ref().to_path_buf()); } if path.as_ref().is_relative() { let full_path = match root { None => path.as_ref().to_path_buf(), Some(root) => { let mut full_path = root.as_ref().to_path_buf(); full_path.push(path.as_ref()); full_path } }; if !full_path.exists() { return Err(eyre::eyre!(format!( "'{}' does not exist", path.as_ref().to_string_lossy() ))); } return Ok(full_path); } Ok(path.as_ref().to_path_buf()) } pub fn filename_or_exists_with_ext<P>( path: P, root: Option<P>, ext: Option<&str>, ) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let path_buf = path.as_ref().to_path_buf(); let root_buf = root.map(|p| p.as_ref().to_path_buf()); let mut checks = vec![filename_or_exists(path_buf, root_buf.clone())]; if let Some(ext) = ext { let mut try_ext = path.as_ref().to_path_buf(); try_ext.set_extension(ext); checks.push(filename_or_exists(try_ext, root_buf)); } let has_path = checks.iter().find(|result| result.is_ok()); if let Some(cmd) = has_path { return Ok(cmd.as_ref().unwrap().as_path().to_path_buf()); } Err(checks.remove(0).unwrap_err()) } pub fn executable_or_exists<P>(path: P, root: Option<P>) -> eyre::Result<path::PathBuf> where P: AsRef<path::Path>, { let ext = if cfg!(windows) { Some("exe") } else { None }; filename_or_exists_with_ext(path, root, ext) } #[cfg(test)] mod tests { use super::*; #[test]
rcase()); } }
fn test_path() { let path = path::Path::new("some/path/to/.clang-format"); let file_name = path.file_name().and_then(std::ffi::OsStr::to_str).unwrap(); assert_eq!(".clang-format", file_name.to_lowe
function_block-random_span
[ { "content": "fn crate_root_rel(path: &str) -> path::PathBuf {\n\n crate_root().join(path)\n\n}\n\n\n", "file_path": "tests/invoke.rs", "rank": 5, "score": 193585.52881078637 }, { "content": "pub fn match_paths<P>(\n\n candidates: Vec<globmatch::Matcher<P>>,\n\n filter: Option<Vec<g...
Rust
base_layer/core/src/covenants/output_set.rs
AaronFeickert/tari
5e55bf22110ac40ffc0dea88d88ba836982591eb
use std::{ cmp::Ordering, collections::BTreeSet, iter::FromIterator, ops::{Deref, DerefMut}, }; use crate::{covenants::error::CovenantError, transactions::transaction_components::TransactionOutput}; #[derive(Debug, Clone)] pub struct OutputSet<'a>(BTreeSet<Indexed<&'a TransactionOutput>>); impl<'a> OutputSet<'a> { pub fn new(outputs: &'a [TransactionOutput]) -> Self { outputs.iter().enumerate().collect() } pub fn len(&self) -> usize { self.0.len() } pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn set(&mut self, new_set: Self) { *self = new_set; } pub fn retain<F>(&mut self, mut f: F) -> Result<(), CovenantError> where F: FnMut(&'a TransactionOutput) -> Result<bool, CovenantError> { let mut err = None; self.0.retain(|output| match f(**output) { Ok(b) => b, Err(e) => { err = Some(e); false }, }); match err { Some(err) => Err(err), None => Ok(()), } } pub fn union(&self, other: &Self) -> Self { self.0.union(&other.0).copied().collect() } pub fn difference(&self, other: &Self) -> Self { self.0.difference(&other.0).copied().collect() } pub fn symmetric_difference(&self, other: &Self) -> Self { self.0.symmetric_difference(&other.0).copied().collect() } pub fn find_inplace<F>(&mut self, mut pred: F) where F: FnMut(&TransactionOutput) -> bool { match self.0.iter().find(|indexed| pred(&**indexed)) { Some(output) => { let output = *output; self.clear(); self.0.insert(output); }, None => { self.clear(); }, } } pub fn clear(&mut self) { self.0.clear(); } #[cfg(test)] pub(super) fn get(&self, index: usize) -> Option<&TransactionOutput> { self.0 .iter() .find(|output| output.index == index) .map(|output| **output) } #[cfg(test)] pub(super) fn get_selected_indexes(&self) -> Vec<usize> { self.0.iter().map(|idx| idx.index).collect() } } impl<'a> FromIterator<(usize, &'a TransactionOutput)> for OutputSet<'a> { fn from_iter<T: IntoIterator<Item = (usize, &'a TransactionOutput)>>(iter: T) -> Self { iter.into_iter().map(|(i, output)| Indexed::new(i, output)).collect() } } impl<'a> FromIterator<Indexed<&'a TransactionOutput>> for OutputSet<'a> { fn from_iter<T: IntoIterator<Item = Indexed<&'a TransactionOutput>>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } #[derive(Debug, Clone, Copy)] struct Indexed<T> { index: usize, value: T, } impl<T> Indexed<T> { pub fn new(index: usize, value: T) -> Self { Self { index, value } } } impl<T> PartialEq for Indexed<T> { fn eq(&self, other: &Self) -> bool { self.index == other.index } } impl<T> Eq for Indexed<T> {} impl<T> PartialOrd for Indexed<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.index.partial_cmp(&other.index) } } impl<T> Ord for Indexed<T> { fn cmp(&self, other: &Self) -> Ordering { self.index.cmp(&other.index) } } impl<T> Deref for Indexed<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.value } } impl<T> DerefMut for Indexed<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.value } }
use std::{ cmp::Ordering, collections::BTreeSet, iter::FromIterator, ops::{Deref, DerefMut}, }; use crate::{covenants::error::CovenantError, transactions::transaction_components::TransactionOutput}; #[derive(Debug, Clone)] pub struct OutputSet<'a>(BTreeSet<Indexed<&'a TransactionOutput>>); impl<'a> OutputSet<'a> { pub fn new(outputs: &'a [TransactionOutput]) -> Self { outputs.iter().enumerate().collect() } pub fn len(&self) -> usize { self.0.len() } pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn set(&mut self, new_set: Self) { *self = new_set; } pub fn retain<F>(&mut self, mut f: F) -> Result<(), CovenantError> where F: FnMut(&'a TransactionOutput) -> Result<bool, CovenantError> { let mut err = None; self.0.retain(|output| match f(**output) { Ok(b) => b, Err(e) => { err = Some(e); false }, }); match err { Some(err) => Err(err), None => Ok(()), } } pub fn union(&self, other: &Self) -> Self { self.0.union(&other.0).copied().collect() } pub fn difference(&self, other: &Self) -> Self { self.0.difference(&other.0).copied().collect() } pub fn symmetric_difference(&self, other: &Self) -> Self { self.0.symmetric_difference(&other.0).copied().collect() }
pub fn clear(&mut self) { self.0.clear(); } #[cfg(test)] pub(super) fn get(&self, index: usize) -> Option<&TransactionOutput> { self.0 .iter() .find(|output| output.index == index) .map(|output| **output) } #[cfg(test)] pub(super) fn get_selected_indexes(&self) -> Vec<usize> { self.0.iter().map(|idx| idx.index).collect() } } impl<'a> FromIterator<(usize, &'a TransactionOutput)> for OutputSet<'a> { fn from_iter<T: IntoIterator<Item = (usize, &'a TransactionOutput)>>(iter: T) -> Self { iter.into_iter().map(|(i, output)| Indexed::new(i, output)).collect() } } impl<'a> FromIterator<Indexed<&'a TransactionOutput>> for OutputSet<'a> { fn from_iter<T: IntoIterator<Item = Indexed<&'a TransactionOutput>>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } #[derive(Debug, Clone, Copy)] struct Indexed<T> { index: usize, value: T, } impl<T> Indexed<T> { pub fn new(index: usize, value: T) -> Self { Self { index, value } } } impl<T> PartialEq for Indexed<T> { fn eq(&self, other: &Self) -> bool { self.index == other.index } } impl<T> Eq for Indexed<T> {} impl<T> PartialOrd for Indexed<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.index.partial_cmp(&other.index) } } impl<T> Ord for Indexed<T> { fn cmp(&self, other: &Self) -> Ordering { self.index.cmp(&other.index) } } impl<T> Deref for Indexed<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.value } } impl<T> DerefMut for Indexed<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.value } }
pub fn find_inplace<F>(&mut self, mut pred: F) where F: FnMut(&TransactionOutput) -> bool { match self.0.iter().find(|indexed| pred(&**indexed)) { Some(output) => { let output = *output; self.clear(); self.0.insert(output); }, None => { self.clear(); }, } }
function_block-full_function
[ { "content": "/// Is this position a leaf in the MMR?\n\n/// We know the positions of all leaves based on the postorder height of an MMR of any size (somewhat unintuitively\n\n/// but this is how the PMMR is \"append only\").\n\npub fn is_leaf(pos: usize) -> bool {\n\n bintree_height(pos) == 0\n\n}\n\n\n", ...
Rust
polars/polars-lazy/src/physical_plan/expressions/aggregation.rs
qiemem/polars
48ea1ed035a44d188d17f2d01ee07f671df27360
use crate::physical_plan::state::ExecutionState; use crate::physical_plan::PhysicalAggregation; use crate::prelude::*; use polars_arrow::export::arrow::{array::*, compute::concatenate::concatenate}; use polars_arrow::prelude::QuantileInterpolOptions; use polars_core::frame::groupby::{fmt_groupby_column, GroupByMethod, GroupsProxy}; use polars_core::{prelude::*, POOL}; use std::borrow::Cow; use std::sync::Arc; pub(crate) struct AggregationExpr { pub(crate) expr: Arc<dyn PhysicalExpr>, pub(crate) agg_type: GroupByMethod, } impl AggregationExpr { pub fn new(expr: Arc<dyn PhysicalExpr>, agg_type: GroupByMethod) -> Self { Self { expr, agg_type } } } impl PhysicalExpr for AggregationExpr { fn as_expression(&self) -> &Expr { unimplemented!() } fn evaluate(&self, _df: &DataFrame, _state: &ExecutionState) -> Result<Series> { unimplemented!() } #[allow(clippy::ptr_arg)] fn evaluate_on_groups<'a>( &self, df: &DataFrame, groups: &'a GroupsProxy, state: &ExecutionState, ) -> Result<AggregationContext<'a>> { let out = self.aggregate(df, groups, state)?.ok_or_else(|| { PolarsError::ComputeError("Aggregation did not return a Series".into()) })?; Ok(AggregationContext::new(out, Cow::Borrowed(groups), true)) } fn to_field(&self, input_schema: &Schema) -> Result<Field> { let field = self.expr.to_field(input_schema)?; let new_name = fmt_groupby_column(field.name(), self.agg_type); Ok(Field::new(&new_name, field.data_type().clone())) } fn as_agg_expr(&self) -> Result<&dyn PhysicalAggregation> { Ok(self) } } fn rename_option_series(opt: Option<Series>, name: &str) -> Option<Series> { opt.map(|mut s| { s.rename(name); s }) } impl PhysicalAggregation for AggregationExpr { fn aggregate( &self, df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Series>> { let mut ac = self.expr.evaluate_on_groups(df, groups, state)?; let new_name = fmt_groupby_column(ac.series().name(), self.agg_type); match self.agg_type { GroupByMethod::Min => { let agg_s = ac.flat_naive().into_owned().agg_min(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Max => { let agg_s = ac.flat_naive().into_owned().agg_max(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Median => { let agg_s = ac.flat_naive().into_owned().agg_median(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Mean => { let agg_s = ac.flat_naive().into_owned().agg_mean(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Sum => { let agg_s = ac.flat_naive().into_owned().agg_sum(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Count => { let mut ca = ac.groups.group_count(); ca.rename(&new_name); Ok(Some(ca.into_series())) } GroupByMethod::First => { let mut agg_s = ac.flat_naive().into_owned().agg_first(ac.groups()); agg_s.rename(&new_name); Ok(Some(agg_s)) } GroupByMethod::Last => { let mut agg_s = ac.flat_naive().into_owned().agg_last(ac.groups()); agg_s.rename(&new_name); Ok(Some(agg_s)) } GroupByMethod::NUnique => { let opt_agg = ac.flat_naive().into_owned().agg_n_unique(ac.groups()); let opt_agg = opt_agg.map(|mut agg| { agg.rename(&new_name); agg.into_series() }); Ok(opt_agg) } GroupByMethod::List => { let agg = ac.aggregated(); Ok(rename_option_series(Some(agg), &new_name)) } GroupByMethod::Groups => { let mut column: ListChunked = ac.groups().as_list_chunked(); column.rename(&new_name); Ok(Some(column.into_series())) } GroupByMethod::Std => { let agg_s = ac.flat_naive().into_owned().agg_std(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Var => { let agg_s = ac.flat_naive().into_owned().agg_var(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Quantile(_, _) => { unimplemented!() } } } fn evaluate_partitioned( &self, df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Vec<Series>>> { match self.agg_type { GroupByMethod::Mean => { let series = self.expr.evaluate(df, state)?; let mut new_name = fmt_groupby_column(series.name(), self.agg_type); let agg_s = series.agg_sum(groups); if let Some(agg_s) = agg_s { let mut agg_s = agg_s.cast(&DataType::Float64)?; agg_s.rename(&new_name); new_name.push_str("__POLARS_MEAN_COUNT"); let mut count_s = series.agg_valid_count(groups).unwrap(); count_s.rename(&new_name); Ok(Some(vec![agg_s, count_s])) } else { Ok(None) } } GroupByMethod::List => { let series = self.expr.evaluate(df, state)?; let new_name = fmt_groupby_column(series.name(), self.agg_type); let opt_agg = series.agg_list(groups); Ok(opt_agg.map(|mut s| { s.rename(&new_name); vec![s] })) } _ => PhysicalAggregation::aggregate(self, df, groups, state) .map(|opt| opt.map(|s| vec![s])), } } fn evaluate_partitioned_final( &self, final_df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Series>> { match self.agg_type { GroupByMethod::Mean => { let series = self.expr.evaluate(final_df, state)?; let count_name = format!("{}__POLARS_MEAN_COUNT", series.name()); let new_name = fmt_groupby_column(series.name(), self.agg_type); let count = final_df.column(&count_name).unwrap(); let (agg_count, agg_s) = POOL.join(|| count.agg_sum(groups), || series.agg_sum(groups)); let agg_s = agg_s.map(|agg_s| &agg_s / &agg_count.unwrap()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::List => { let series = self.expr.evaluate(final_df, state)?; let ca = series.list().unwrap(); let new_name = fmt_groupby_column(ca.name(), self.agg_type); let mut values = Vec::with_capacity(groups.len()); let mut can_fast_explode = true; let mut offsets = Vec::<i64>::with_capacity(groups.len() + 1); let mut length_so_far = 0i64; offsets.push(length_so_far); for (_, idx) in groups.idx_ref() { let ca = unsafe { ca.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; let s = ca.explode()?; length_so_far += s.len() as i64; offsets.push(length_so_far); values.push(s.chunks()[0].clone()); if s.len() == 0 { can_fast_explode = false; } } let vals = values.iter().map(|arr| &**arr).collect::<Vec<_>>(); let values: ArrayRef = concatenate(&vals).unwrap().into(); let data_type = ListArray::<i64>::default_datatype(values.data_type().clone()); let arr = Arc::new(ListArray::<i64>::from_data( data_type, offsets.into(), values, None, )) as ArrayRef; let mut ca = ListChunked::new_from_chunks(&new_name, vec![arr]); if can_fast_explode { ca.set_fast_explode() } Ok(Some(ca.into_series())) } _ => PhysicalAggregation::aggregate(self, final_df, groups, state), } } } impl PhysicalAggregation for AggQuantileExpr { fn aggregate( &self, df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Series>> { let series = self.expr.evaluate(df, state)?; let new_name = fmt_groupby_column( series.name(), GroupByMethod::Quantile(self.quantile, self.interpol), ); let opt_agg = series.agg_quantile(groups, self.quantile, self.interpol); let opt_agg = opt_agg.map(|mut agg| { agg.rename(&new_name); agg.into_series() }); Ok(opt_agg) } } impl PhysicalAggregation for CastExpr { fn aggregate( &self, df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Series>> { let agg_expr = self.input.as_agg_expr()?; let opt_agg = agg_expr.aggregate(df, groups, state)?; opt_agg.map(|agg| agg.cast(&self.data_type)).transpose() } } pub struct AggQuantileExpr { pub(crate) expr: Arc<dyn PhysicalExpr>, pub(crate) quantile: f64, pub(crate) interpol: QuantileInterpolOptions, } impl AggQuantileExpr { pub fn new( expr: Arc<dyn PhysicalExpr>, quantile: f64, interpol: QuantileInterpolOptions, ) -> Self { Self { expr, quantile, interpol, } } } impl PhysicalExpr for AggQuantileExpr { fn as_expression(&self) -> &Expr { unimplemented!() } fn evaluate(&self, _df: &DataFrame, _state: &ExecutionState) -> Result<Series> { unimplemented!() } #[allow(clippy::ptr_arg)] fn evaluate_on_groups<'a>( &self, _df: &DataFrame, _groups: &'a GroupsProxy, _state: &ExecutionState, ) -> Result<AggregationContext<'a>> { unimplemented!() } fn to_field(&self, input_schema: &Schema) -> Result<Field> { let field = self.expr.to_field(input_schema)?; let new_name = fmt_groupby_column( field.name(), GroupByMethod::Quantile(self.quantile, self.interpol), ); Ok(Field::new(&new_name, field.data_type().clone())) } fn as_agg_expr(&self) -> Result<&dyn PhysicalAggregation> { Ok(self) } }
use crate::physical_plan::state::ExecutionState; use crate::physical_plan::PhysicalAggregation; use crate::prelude::*; use polars_arrow::export::arrow::{array::*, compute::concatenate::concatenate}; use polars_arrow::prelude::QuantileInterpolOptions; use polars_core::frame::groupby::{fmt_groupby_column, GroupByMethod, GroupsProxy}; use polars_core::{prelude::*, POOL}; use std::borrow::Cow; use std::sync::Arc; pub(crate) struct AggregationExpr { pub(crate) expr: Arc<dyn PhysicalExpr>, pub(crate) agg_type: GroupByMethod, } impl AggregationExpr { pub fn new(expr: Arc<dyn PhysicalExpr>, agg_type: GroupByMethod) -> Self { Self { expr, agg_type } } } impl PhysicalExpr for AggregationExpr { fn as_expression(&self) -> &Expr { unimplemented!() } fn evaluate(&self, _df: &DataFrame, _state: &ExecutionState) -> Result<Series> { unimplemented!() } #[allow(clippy::ptr_arg)] fn evaluate_on_groups<'a>( &self, df: &DataFrame, groups: &'a GroupsProxy, state: &ExecutionState, ) -> Result<AggregationContext<'a>> { let out = self.aggregate(df, groups, state)?.ok_or_else(|| { PolarsError::ComputeError("Aggregation did not return a Series".into()) })?; Ok(AggregationContext::new(out, Cow::Borrowed(groups), true)) } fn to_field(&self, input_schema: &Schema) -> Result<Field> { let field = self.expr.to_field(input_schema)?; let new_name = fmt_groupby_column(field.name(), self.agg_type); Ok(Field::new(&new_name, field.data_type().clone())) } fn as_agg_expr(&self) -> Result<&dyn PhysicalAggregation> { Ok(self) } } fn rename_option_series(opt: Option<Series>, name: &str) -> Option<Series> { opt.map(|mut s| { s.rename(name); s }) } impl PhysicalAggregation for AggregationExpr { fn aggregate( &self, df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Series>> { let mut ac = self.expr.evaluate_on_groups(df, groups, state)?; let new_name = fmt_groupby_column(ac.series().name(), self.agg_type); match self.agg_type { GroupByMethod::Min => { let agg_s = ac.flat_naive().into_owned().agg_min(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Max => { let agg_s = ac.flat_naive().into_owned().agg_max(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Median => { let agg_s = ac.flat_naive().into_owned().agg_median(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Mean => { let agg_s = ac.flat_naive().into_owned().agg_mean(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Sum => { let agg_s = ac.flat_naive().into_owned().agg_sum(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Count => { let mut ca = ac.groups.group_count(); ca.rename(&new_name); Ok(Some(ca.into_series())) } GroupByMethod::First => { let mut agg_s = ac.flat_naive().into_owned().agg_first(ac.groups()); agg_s.rename(&new_name); Ok(Some(agg_s)) } GroupByMethod::Last => { let mut agg_s = ac.flat_naive().into_owned().agg_last(ac.groups()); agg_s.rename(&new_name); Ok(Some(agg_s)) } GroupByMethod::NUnique => { let opt_agg = ac.flat_naive().into_owned().agg_n_unique(ac.groups()); let opt_agg = opt_agg.map(|mut agg| { agg.rename(&new_name); agg.
GroupByMethod::Mean => { let series = self.expr.evaluate(final_df, state)?; let count_name = format!("{}__POLARS_MEAN_COUNT", series.name()); let new_name = fmt_groupby_column(series.name(), self.agg_type); let count = final_df.column(&count_name).unwrap(); let (agg_count, agg_s) = POOL.join(|| count.agg_sum(groups), || series.agg_sum(groups)); let agg_s = agg_s.map(|agg_s| &agg_s / &agg_count.unwrap()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::List => { let series = self.expr.evaluate(final_df, state)?; let ca = series.list().unwrap(); let new_name = fmt_groupby_column(ca.name(), self.agg_type); let mut values = Vec::with_capacity(groups.len()); let mut can_fast_explode = true; let mut offsets = Vec::<i64>::with_capacity(groups.len() + 1); let mut length_so_far = 0i64; offsets.push(length_so_far); for (_, idx) in groups.idx_ref() { let ca = unsafe { ca.take_unchecked(idx.iter().map(|i| *i as usize).into()) }; let s = ca.explode()?; length_so_far += s.len() as i64; offsets.push(length_so_far); values.push(s.chunks()[0].clone()); if s.len() == 0 { can_fast_explode = false; } } let vals = values.iter().map(|arr| &**arr).collect::<Vec<_>>(); let values: ArrayRef = concatenate(&vals).unwrap().into(); let data_type = ListArray::<i64>::default_datatype(values.data_type().clone()); let arr = Arc::new(ListArray::<i64>::from_data( data_type, offsets.into(), values, None, )) as ArrayRef; let mut ca = ListChunked::new_from_chunks(&new_name, vec![arr]); if can_fast_explode { ca.set_fast_explode() } Ok(Some(ca.into_series())) } _ => PhysicalAggregation::aggregate(self, final_df, groups, state), } } } impl PhysicalAggregation for AggQuantileExpr { fn aggregate( &self, df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Series>> { let series = self.expr.evaluate(df, state)?; let new_name = fmt_groupby_column( series.name(), GroupByMethod::Quantile(self.quantile, self.interpol), ); let opt_agg = series.agg_quantile(groups, self.quantile, self.interpol); let opt_agg = opt_agg.map(|mut agg| { agg.rename(&new_name); agg.into_series() }); Ok(opt_agg) } } impl PhysicalAggregation for CastExpr { fn aggregate( &self, df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Series>> { let agg_expr = self.input.as_agg_expr()?; let opt_agg = agg_expr.aggregate(df, groups, state)?; opt_agg.map(|agg| agg.cast(&self.data_type)).transpose() } } pub struct AggQuantileExpr { pub(crate) expr: Arc<dyn PhysicalExpr>, pub(crate) quantile: f64, pub(crate) interpol: QuantileInterpolOptions, } impl AggQuantileExpr { pub fn new( expr: Arc<dyn PhysicalExpr>, quantile: f64, interpol: QuantileInterpolOptions, ) -> Self { Self { expr, quantile, interpol, } } } impl PhysicalExpr for AggQuantileExpr { fn as_expression(&self) -> &Expr { unimplemented!() } fn evaluate(&self, _df: &DataFrame, _state: &ExecutionState) -> Result<Series> { unimplemented!() } #[allow(clippy::ptr_arg)] fn evaluate_on_groups<'a>( &self, _df: &DataFrame, _groups: &'a GroupsProxy, _state: &ExecutionState, ) -> Result<AggregationContext<'a>> { unimplemented!() } fn to_field(&self, input_schema: &Schema) -> Result<Field> { let field = self.expr.to_field(input_schema)?; let new_name = fmt_groupby_column( field.name(), GroupByMethod::Quantile(self.quantile, self.interpol), ); Ok(Field::new(&new_name, field.data_type().clone())) } fn as_agg_expr(&self) -> Result<&dyn PhysicalAggregation> { Ok(self) } }
into_series() }); Ok(opt_agg) } GroupByMethod::List => { let agg = ac.aggregated(); Ok(rename_option_series(Some(agg), &new_name)) } GroupByMethod::Groups => { let mut column: ListChunked = ac.groups().as_list_chunked(); column.rename(&new_name); Ok(Some(column.into_series())) } GroupByMethod::Std => { let agg_s = ac.flat_naive().into_owned().agg_std(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Var => { let agg_s = ac.flat_naive().into_owned().agg_var(ac.groups()); Ok(rename_option_series(agg_s, &new_name)) } GroupByMethod::Quantile(_, _) => { unimplemented!() } } } fn evaluate_partitioned( &self, df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Vec<Series>>> { match self.agg_type { GroupByMethod::Mean => { let series = self.expr.evaluate(df, state)?; let mut new_name = fmt_groupby_column(series.name(), self.agg_type); let agg_s = series.agg_sum(groups); if let Some(agg_s) = agg_s { let mut agg_s = agg_s.cast(&DataType::Float64)?; agg_s.rename(&new_name); new_name.push_str("__POLARS_MEAN_COUNT"); let mut count_s = series.agg_valid_count(groups).unwrap(); count_s.rename(&new_name); Ok(Some(vec![agg_s, count_s])) } else { Ok(None) } } GroupByMethod::List => { let series = self.expr.evaluate(df, state)?; let new_name = fmt_groupby_column(series.name(), self.agg_type); let opt_agg = series.agg_list(groups); Ok(opt_agg.map(|mut s| { s.rename(&new_name); vec![s] })) } _ => PhysicalAggregation::aggregate(self, df, groups, state) .map(|opt| opt.map(|s| vec![s])), } } fn evaluate_partitioned_final( &self, final_df: &DataFrame, groups: &GroupsProxy, state: &ExecutionState, ) -> Result<Option<Series>> { match self.agg_type {
random
[ { "content": "/// Create a Column Expression based on a column name.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `name` - A string slice that holds the name of the column\n\n///\n\n/// # Examples\n\n///\n\n/// ```ignore\n\n/// // select a column name\n\n/// col(\"foo\")\n\n/// ```\n\n///\n\n/// ```ignore\n\n/// /...
Rust
daemon/state_helper.rs
slooppe/pueue
ee71ad7c6eb05788af063fd98a649b02c006cbb1
use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; use std::sync::MutexGuard; use std::time::SystemTime; use anyhow::{Context, Result}; use chrono::prelude::*; use log::{debug, info}; use pueue_lib::state::{GroupStatus, State}; use pueue_lib::task::{TaskResult, TaskStatus}; pub type LockedState<'a> = MutexGuard<'a, State>; pub fn is_task_removable(state: &LockedState, task_id: &usize, to_delete: &[usize]) -> bool { let dependants: Vec<usize> = state .tasks .iter() .filter(|(_, task)| { task.dependencies.contains(task_id) && !matches!(task.status, TaskStatus::Done(_)) }) .map(|(_, task)| task.id) .collect(); if dependants.is_empty() { return true; } let should_delete_dependants = dependants.iter().all(|task_id| to_delete.contains(task_id)); if !should_delete_dependants { return false; } dependants .iter() .all(|task_id| is_task_removable(state, task_id, to_delete)) } pub fn pause_on_failure(state: &mut LockedState, group: String) { if state.settings.daemon.pause_group_on_failure { state.groups.insert(group, GroupStatus::Paused); } else if state.settings.daemon.pause_all_on_failure { state.set_status_for_all_groups(GroupStatus::Paused); } } pub fn save_settings(state: &LockedState) -> Result<()> { state .settings .save(&state.config_path) .context("Failed to save settings") } pub fn reset_state(state: &mut LockedState) -> Result<()> { backup_state(state)?; state.tasks = BTreeMap::new(); state.set_status_for_all_groups(GroupStatus::Running); save_state(state) } pub fn save_state(state: &State) -> Result<()> { save_state_to_file(state, false) } pub fn backup_state(state: &LockedState) -> Result<()> { save_state_to_file(state, true)?; rotate_state(state).context("Failed to rotate old log files")?; Ok(()) } fn save_state_to_file(state: &State, log: bool) -> Result<()> { let serialized = serde_json::to_string(&state).context("Failed to serialize state:"); let serialized = serialized.unwrap(); let path = state.settings.shared.pueue_directory(); let (temp, real) = if log { let path = path.join("log"); let now: DateTime<Utc> = Utc::now(); let time = now.format("%Y-%m-%d_%H-%M-%S"); ( path.join(format!("{}_state.json.partial", time)), path.join(format!("{}_state.json", time)), ) } else { (path.join("state.json.partial"), path.join("state.json")) }; fs::write(&temp, serialized).context("Failed to write temp file while saving state.")?; fs::rename(&temp, &real).context("Failed to overwrite old state while saving state")?; if log { debug!("State backup created at: {:?}", real); } else { debug!("State saved at: {:?}", real); } Ok(()) } pub fn restore_state(pueue_directory: &Path) -> Result<Option<State>> { let path = pueue_directory.join("state.json"); if !path.exists() { info!( "Couldn't find state from previous session at location: {:?}", path ); return Ok(None); } info!("Start restoring state"); let data = fs::read_to_string(&path).context("State restore: Failed to read file:\n\n{}")?; let mut state: State = serde_json::from_str(&data).context("Failed to deserialize state.")?; for (group, _) in state.settings.daemon.groups.iter() { if let Some(status) = state.groups.clone().get(group) { state.groups.insert(group.clone(), status.clone()); } } for (_, task) in state.tasks.iter_mut() { if task.status == TaskStatus::Running || task.status == TaskStatus::Paused { info!( "Setting task {} with previous status {:?} to new status {:?}", task.id, task.status, TaskResult::Killed ); task.status = TaskStatus::Done(TaskResult::Killed); } if task.status == TaskStatus::Locked { task.status = TaskStatus::Stashed { enqueue_at: None }; } if !state.settings.daemon.groups.contains_key(&task.group) { task.set_default_group(); } if task.status == TaskStatus::Queued { info!( "Pausing group {} to prevent unwanted execution of previous tasks", &task.group ); state.groups.insert(task.group.clone(), GroupStatus::Paused); } } Ok(Some(state)) } fn rotate_state(state: &LockedState) -> Result<()> { let path = state.settings.shared.pueue_directory().join("log"); let mut entries: BTreeMap<SystemTime, PathBuf> = BTreeMap::new(); let mut directory_list = fs::read_dir(path)?; while let Some(Ok(entry)) = directory_list.next() { let path = entry.path(); let metadata = entry.metadata()?; let time = metadata.modified()?; entries.insert(time, path); } let mut number_entries = entries.len(); let mut iter = entries.iter(); while number_entries > 10 { if let Some((_, path)) = iter.next() { fs::remove_file(path)?; number_entries -= 1; } } Ok(()) }
use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; use std::sync::MutexGuard; use std::time::SystemTime; use anyhow::{Context, Result}; use chrono::prelude::*; use log::{debug, info}; use pueue_lib::state::{GroupStatus, State}; use pueue_lib::task::{TaskResult, TaskStatus}; pub type LockedState<'a> = MutexGuard<'a, State>; pub fn is_task_removable(state: &LockedState, task_id: &usize, to_delete: &[usize]) -> bool { let dependants: Vec<usize> = state .tasks .iter() .filter(|(_, task)| { task.dependencies.contains(task_id) && !matches!(task.status, TaskStatus::Done(_)) }) .map(|(_, task)| task.id) .collect(); if dependants.is_empty() { return true; } let should_delete_dependants = dependants.iter().all(|task_id| to_delete.contains(task_id)); if !should_delete_dependants { return false; } dependants .iter() .all(|task_id| is_task_removable(state, task_id, to_delete)) } pub fn pause_on_failure(state: &mut LockedState, group: String) { if state.settings.daemon.pause_group_on_failure { state.groups.insert(group, GroupStatus::Paused); } else if state.settings.daemon.pause_all_on_failure { state.set_status_for_all_groups(GroupStatus::Paused); } } pub fn save_settings(state: &LockedState) -> Result<()> { state .settings .save(&state.config_path) .context("Failed to save settings") } pub fn reset_state(state: &mut LockedState) -> Result<()> { backup_state(state)?; state.tasks = BTreeMap::new(); state.set_status_for_all_groups(GroupStatus::Running); save_state(state) } pub fn save_state(state: &State) -> Result<()> { save_state_to_file(state, false) } pub fn backup_state(state: &LockedState) -> Result<()> { save_state_to_file(state, true)?; rotate_state(state).context("Failed to rotate old log files")?; Ok(()) }
pub fn restore_state(pueue_directory: &Path) -> Result<Option<State>> { let path = pueue_directory.join("state.json"); if !path.exists() { info!( "Couldn't find state from previous session at location: {:?}", path ); return Ok(None); } info!("Start restoring state"); let data = fs::read_to_string(&path).context("State restore: Failed to read file:\n\n{}")?; let mut state: State = serde_json::from_str(&data).context("Failed to deserialize state.")?; for (group, _) in state.settings.daemon.groups.iter() { if let Some(status) = state.groups.clone().get(group) { state.groups.insert(group.clone(), status.clone()); } } for (_, task) in state.tasks.iter_mut() { if task.status == TaskStatus::Running || task.status == TaskStatus::Paused { info!( "Setting task {} with previous status {:?} to new status {:?}", task.id, task.status, TaskResult::Killed ); task.status = TaskStatus::Done(TaskResult::Killed); } if task.status == TaskStatus::Locked { task.status = TaskStatus::Stashed { enqueue_at: None }; } if !state.settings.daemon.groups.contains_key(&task.group) { task.set_default_group(); } if task.status == TaskStatus::Queued { info!( "Pausing group {} to prevent unwanted execution of previous tasks", &task.group ); state.groups.insert(task.group.clone(), GroupStatus::Paused); } } Ok(Some(state)) } fn rotate_state(state: &LockedState) -> Result<()> { let path = state.settings.shared.pueue_directory().join("log"); let mut entries: BTreeMap<SystemTime, PathBuf> = BTreeMap::new(); let mut directory_list = fs::read_dir(path)?; while let Some(Ok(entry)) = directory_list.next() { let path = entry.path(); let metadata = entry.metadata()?; let time = metadata.modified()?; entries.insert(time, path); } let mut number_entries = entries.len(); let mut iter = entries.iter(); while number_entries > 10 { if let Some((_, path)) = iter.next() { fs::remove_file(path)?; number_entries -= 1; } } Ok(()) }
fn save_state_to_file(state: &State, log: bool) -> Result<()> { let serialized = serde_json::to_string(&state).context("Failed to serialize state:"); let serialized = serialized.unwrap(); let path = state.settings.shared.pueue_directory(); let (temp, real) = if log { let path = path.join("log"); let now: DateTime<Utc> = Utc::now(); let time = now.format("%Y-%m-%d_%H-%M-%S"); ( path.join(format!("{}_state.json.partial", time)), path.join(format!("{}_state.json", time)), ) } else { (path.join("state.json.partial"), path.join("state.json")) }; fs::write(&temp, serialized).context("Failed to write temp file while saving state.")?; fs::rename(&temp, &real).context("Failed to overwrite old state while saving state")?; if log { debug!("State backup created at: {:?}", real); } else { debug!("State saved at: {:?}", real); } Ok(()) }
function_block-full_function
[ { "content": "/// Print a local log file.\n\n/// This is usually either the stdout or the stderr\n\nfn print_local_file(stdout: &mut Stdout, file: &mut File, lines: &Option<usize>, text: String) {\n\n if let Ok(metadata) = file.metadata() {\n\n if metadata.len() != 0 {\n\n // Don't print a ...
Rust
macros/src/parser/mod.rs
ryan-summers/smlang-rs
9f4567b6fb05bd867363bb46385f4c33704fe304
pub mod data; pub mod event; pub mod input_state; pub mod output_state; pub mod state_machine; pub mod transition; use data::DataDefinitions; use event::EventMapping; use state_machine::StateMachine; use input_state::InputState; use proc_macro2::Span; use std::collections::HashMap; use syn::{parse, Ident, Type}; use transition::StateTransition; pub type TransitionMap = HashMap<String, HashMap<String, EventMapping>>; #[derive(Debug)] pub struct ParsedStateMachine { pub temporary_context_type: Option<Type>, pub guard_error: Option<Type>, pub states: HashMap<String, Ident>, pub starting_state: Ident, pub state_data: DataDefinitions, pub events: HashMap<String, Ident>, pub event_data: DataDefinitions, pub states_events_mapping: HashMap<String, HashMap<String, EventMapping>>, } fn add_transition( transition: &StateTransition, transition_map: &mut TransitionMap, state_data: &DataDefinitions, ) -> Result<(), parse::Error> { let p = transition_map .get_mut(&transition.in_state.ident.to_string()) .unwrap(); if !p.contains_key(&transition.event.ident.to_string()) { let mapping = EventMapping { event: transition.event.ident.clone(), guard: transition.guard.clone(), action: transition.action.clone(), out_state: transition.out_state.ident.clone(), }; p.insert(transition.event.ident.to_string(), mapping); } else { return Err(parse::Error::new( transition.in_state.ident.span(), "State and event combination specified multiple times, remove duplicates.", )); } if let Some(_) = state_data .data_types .get(&transition.out_state.ident.to_string()) { if transition.action.is_none() { return Err(parse::Error::new( transition.out_state.ident.span(), "This state has data associated, but not action is define here to provide it.", )); } } Ok(()) } impl ParsedStateMachine { pub fn new(sm: StateMachine) -> parse::Result<Self> { let num_start: usize = sm .transitions .iter() .map(|sm| if sm.in_state.start { 1 } else { 0 }) .sum(); if num_start == 0 { return Err(parse::Error::new( Span::call_site(), "No starting state defined, indicate the starting state with a *.", )); } else if num_start > 1 { return Err(parse::Error::new( Span::call_site(), "More than one starting state defined (indicated with *), remove duplicates.", )); } let starting_state = sm .transitions .iter() .find(|sm| sm.in_state.start) .unwrap() .in_state .ident .clone(); let mut states = HashMap::new(); let mut state_data = DataDefinitions::new(); let mut events = HashMap::new(); let mut event_data = DataDefinitions::new(); let mut states_events_mapping = TransitionMap::new(); for transition in sm.transitions.iter() { let in_state_name = transition.in_state.ident.to_string(); let out_state_name = transition.out_state.ident.to_string(); if !transition.in_state.wildcard { states.insert(in_state_name.clone(), transition.in_state.ident.clone()); state_data.collect(in_state_name.clone(), transition.in_state.data_type.clone())?; } states.insert(out_state_name.clone(), transition.out_state.ident.clone()); state_data.collect( out_state_name.clone(), transition.out_state.data_type.clone(), )?; let event_name = transition.event.ident.to_string(); events.insert(event_name.clone(), transition.event.ident.clone()); event_data.collect(event_name.clone(), transition.event.data_type.clone())?; if !transition.in_state.wildcard { states_events_mapping.insert(transition.in_state.ident.to_string(), HashMap::new()); } states_events_mapping.insert(transition.out_state.ident.to_string(), HashMap::new()); } state_data.all_lifetimes.dedup(); event_data.all_lifetimes.dedup(); for transition in sm.transitions.iter() { if transition.in_state.wildcard { for (name, in_state) in &states { let in_state = InputState { start: false, wildcard: false, ident: in_state.clone(), data_type: state_data.data_types.get(name).cloned(), }; let wildcard_transition = StateTransition { in_state, event: transition.event.clone(), guard: transition.guard.clone(), action: transition.action.clone(), out_state: transition.out_state.clone(), }; add_transition( &wildcard_transition, &mut states_events_mapping, &state_data, )?; } } else { add_transition(transition, &mut states_events_mapping, &state_data)?; } } Ok(ParsedStateMachine { temporary_context_type: sm.temporary_context_type, guard_error: sm.guard_error, states, starting_state, state_data, events, event_data, states_events_mapping, }) } }
pub mod data; pub mod event; pub mod input_state; pub mod output_state; pub mod state_machine; pub mod transition; use data::DataDefinitions; use event::EventMapping; use state_machine::StateMachine; use input_state::InputState; use proc_macro2::Span; use std::collections::HashMap; use syn::{parse, Ident, Type}; use transition::StateTransition; pub type TransitionMap = HashMap<String, HashMap<String, EventMapping>>; #[derive(Debug)] pub struct ParsedStateMachine { pub temporary_context_type: Option<Type>, pub guard_error: Option<Type>, pub states: HashMap<String, Ident>, pub starting_state: Ident, pub state_data: DataDefinitions, pub events: HashMap<String, Ident>, pub event_data: DataDefinitions, pub states_events_mapping: HashMap<String, HashMap<String, EventMapping>>, } fn add_transition( transition: &StateTr
in_state, event: transition.event.clone(), guard: transition.guard.clone(), action: transition.action.clone(), out_state: transition.out_state.clone(), }; add_transition( &wildcard_transition, &mut states_events_mapping, &state_data, )?; } } else { add_transition(transition, &mut states_events_mapping, &state_data)?; } } Ok(ParsedStateMachine { temporary_context_type: sm.temporary_context_type, guard_error: sm.guard_error, states, starting_state, state_data, events, event_data, states_events_mapping, }) } }
ansition, transition_map: &mut TransitionMap, state_data: &DataDefinitions, ) -> Result<(), parse::Error> { let p = transition_map .get_mut(&transition.in_state.ident.to_string()) .unwrap(); if !p.contains_key(&transition.event.ident.to_string()) { let mapping = EventMapping { event: transition.event.ident.clone(), guard: transition.guard.clone(), action: transition.action.clone(), out_state: transition.out_state.ident.clone(), }; p.insert(transition.event.ident.to_string(), mapping); } else { return Err(parse::Error::new( transition.in_state.ident.span(), "State and event combination specified multiple times, remove duplicates.", )); } if let Some(_) = state_data .data_types .get(&transition.out_state.ident.to_string()) { if transition.action.is_none() { return Err(parse::Error::new( transition.out_state.ident.span(), "This state has data associated, but not action is define here to provide it.", )); } } Ok(()) } impl ParsedStateMachine { pub fn new(sm: StateMachine) -> parse::Result<Self> { let num_start: usize = sm .transitions .iter() .map(|sm| if sm.in_state.start { 1 } else { 0 }) .sum(); if num_start == 0 { return Err(parse::Error::new( Span::call_site(), "No starting state defined, indicate the starting state with a *.", )); } else if num_start > 1 { return Err(parse::Error::new( Span::call_site(), "More than one starting state defined (indicated with *), remove duplicates.", )); } let starting_state = sm .transitions .iter() .find(|sm| sm.in_state.start) .unwrap() .in_state .ident .clone(); let mut states = HashMap::new(); let mut state_data = DataDefinitions::new(); let mut events = HashMap::new(); let mut event_data = DataDefinitions::new(); let mut states_events_mapping = TransitionMap::new(); for transition in sm.transitions.iter() { let in_state_name = transition.in_state.ident.to_string(); let out_state_name = transition.out_state.ident.to_string(); if !transition.in_state.wildcard { states.insert(in_state_name.clone(), transition.in_state.ident.clone()); state_data.collect(in_state_name.clone(), transition.in_state.data_type.clone())?; } states.insert(out_state_name.clone(), transition.out_state.ident.clone()); state_data.collect( out_state_name.clone(), transition.out_state.data_type.clone(), )?; let event_name = transition.event.ident.to_string(); events.insert(event_name.clone(), transition.event.ident.clone()); event_data.collect(event_name.clone(), transition.event.data_type.clone())?; if !transition.in_state.wildcard { states_events_mapping.insert(transition.in_state.ident.to_string(), HashMap::new()); } states_events_mapping.insert(transition.out_state.ident.to_string(), HashMap::new()); } state_data.all_lifetimes.dedup(); event_data.all_lifetimes.dedup(); for transition in sm.transitions.iter() { if transition.in_state.wildcard { for (name, in_state) in &states { let in_state = InputState { start: false, wildcard: false, ident: in_state.clone(), data_type: state_data.data_types.get(name).cloned(), }; let wildcard_transition = StateTransition {
random
[ { "content": "// helper function for extracting a vector of lifetimes from a Type\n\nfn get_lifetimes(data_type: &Type) -> Result<Lifetimes, parse::Error> {\n\n let mut lifetimes = Lifetimes::new();\n\n match data_type {\n\n Type::Reference(tr) => {\n\n if let Some(lifetime) = &tr.lifeti...
Rust
futures-util/src/future/try_join.rs
zhanghanyun/futures-rs
f1f28da9bdf4bd5ac1182d6adf9ad71d29bfe728
#![allow(non_snake_case)] use crate::future::{TryMaybeDone, try_maybe_done}; use core::fmt; use core::pin::Pin; use futures_core::future::{Future, TryFuture}; use futures_core::task::{Context, Poll}; use pin_project::pin_project; macro_rules! generate { ($( $(#[$doc:meta])* ($Join:ident, <Fut1, $($Fut:ident),*>), )*) => ($( $(#[$doc])* #[pin_project] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct $Join<Fut1: TryFuture, $($Fut: TryFuture),*> { #[pin] Fut1: TryMaybeDone<Fut1>, $(#[pin] $Fut: TryMaybeDone<$Fut>,)* } impl<Fut1, $($Fut),*> fmt::Debug for $Join<Fut1, $($Fut),*> where Fut1: TryFuture + fmt::Debug, Fut1::Ok: fmt::Debug, Fut1::Error: fmt::Debug, $( $Fut: TryFuture + fmt::Debug, $Fut::Ok: fmt::Debug, $Fut::Error: fmt::Debug, )* { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct(stringify!($Join)) .field("Fut1", &self.Fut1) $(.field(stringify!($Fut), &self.$Fut))* .finish() } } impl<Fut1, $($Fut),*> $Join<Fut1, $($Fut),*> where Fut1: TryFuture, $( $Fut: TryFuture<Error=Fut1::Error> ),* { fn new(Fut1: Fut1, $($Fut: $Fut),*) -> Self { Self { Fut1: try_maybe_done(Fut1), $($Fut: try_maybe_done($Fut)),* } } } impl<Fut1, $($Fut),*> Future for $Join<Fut1, $($Fut),*> where Fut1: TryFuture, $( $Fut: TryFuture<Error=Fut1::Error> ),* { type Output = Result<(Fut1::Ok, $($Fut::Ok),*), Fut1::Error>; fn poll( self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Self::Output> { let mut all_done = true; let mut futures = self.project(); all_done &= futures.Fut1.as_mut().poll(cx)?.is_ready(); $( all_done &= futures.$Fut.as_mut().poll(cx)?.is_ready(); )* if all_done { Poll::Ready(Ok(( futures.Fut1.take_output().unwrap(), $( futures.$Fut.take_output().unwrap() ),* ))) } else { Poll::Pending } } } )*) } generate! { (TryJoin, <Fut1, Fut2>), (TryJoin3, <Fut1, Fut2, Fut3>), (TryJoin4, <Fut1, Fut2, Fut3, Fut4>), (TryJoin5, <Fut1, Fut2, Fut3, Fut4, Fut5>), } pub fn try_join<Fut1, Fut2>(future1: Fut1, future2: Fut2) -> TryJoin<Fut1, Fut2> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error>, { TryJoin::new(future1, future2) } pub fn try_join3<Fut1, Fut2, Fut3>( future1: Fut1, future2: Fut2, future3: Fut3, ) -> TryJoin3<Fut1, Fut2, Fut3> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error>, Fut3: TryFuture<Error = Fut1::Error>, { TryJoin3::new(future1, future2, future3) } pub fn try_join4<Fut1, Fut2, Fut3, Fut4>( future1: Fut1, future2: Fut2, future3: Fut3, future4: Fut4, ) -> TryJoin4<Fut1, Fut2, Fut3, Fut4> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error>, Fut3: TryFuture<Error = Fut1::Error>, Fut4: TryFuture<Error = Fut1::Error>, { TryJoin4::new(future1, future2, future3, future4) } pub fn try_join5<Fut1, Fut2, Fut3, Fut4, Fut5>( future1: Fut1, future2: Fut2, future3: Fut3, future4: Fut4, future5: Fut5, ) -> TryJoin5<Fut1, Fut2, Fut3, Fut4, Fut5> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error>, Fut3: TryFuture<Error = Fut1::Error>, Fut4: TryFuture<Error = Fut1::Error>, Fut5: TryFuture<Error = Fut1::Error>, { TryJoin5::new(future1, future2, future3, future4, future5) }
#![allow(non_snake_case)] use crate::future::{TryMaybeDone, try_maybe_done}; use core::fmt; use core::pin::Pin; use futures_core::future::{Future, TryFuture}; use futures_core::task::{Context, Poll}; use pin_project::pin_project; macro_rules! generate { ($( $(#[$doc:meta])* ($Join:ident, <Fut1, $($Fut:ident),*>), )*) => ($( $(#[$doc])* #[pin_project] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct $Join<Fut1: TryFuture, $($Fut: TryFuture),*> { #[pin] Fut1: TryMaybeDone<Fut1>, $(#[pin] $Fut: TryMaybeDone<$Fut>,)* } impl<Fut1, $($Fut),*> fmt::Debug for $Join<Fut1, $($Fut),*> where Fut1: TryFuture + fmt::Debug, Fut1::Ok: fmt::Debug, Fut1::Error: fmt::Debug, $( $Fut: TryFuture + fmt::Debug, $Fut::Ok: fmt::Debug, $Fut::Error: fmt::Debug, )* { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct(stringify!($Join)) .field("Fut1", &self.Fut1) $(.field(stringify!($Fut), &self.$Fut))* .finish() } } impl<Fut1, $($Fut),*> $Join<Fut1, $($Fut),*> where Fut1: TryFuture, $( $Fut: TryFuture<Error=Fut1::Error> ),* { fn new(Fut1: Fut1, $($Fut: $Fut),*) -> Self { Self { Fut1: try_maybe_done(Fut1), $($Fut: try_maybe_done($Fut)),* } } } impl<Fut1, $($Fut),*> Future for $Join<Fut1, $($Fut),*> where Fut1: TryFuture, $( $Fut: TryFuture<Error=Fut1::Error> ),* { type Output = Result<(Fut1::Ok, $($Fut::Ok),*), Fut1::Error>; fn poll( self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Self::Output> { let mut all_done = true; let mut futures = self.project(); all_done &= futures.Fut1.as_mut().poll(cx)?.is_ready(); $( all_done &= futures.$Fut.as_mut().poll(cx)?.is_ready(); )* if all_done { Poll::Ready(Ok(( futures.Fut1.take_output().unwrap(), $( futures.$Fut.take_output().unwrap() ),* ))) } else { Poll::Pending } } } )*) } generate! { (TryJoin, <Fut1, Fut2>), (TryJoin3, <Fut1, Fut2, Fut3>), (TryJoin4, <Fut1, Fut2, Fut3, Fut4>), (TryJoin5, <Fut1, Fut2, Fut3, Fut4, Fut5>), } pub fn try_join<Fut1, Fut2>(future1: Fut1, future2: Fut2) -> TryJoin<Fut1, Fut2> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error>, { TryJoin::new(future1, future2) } pub fn try_join3<Fut1, Fut2, Fut3>( future1: Fut1, future2: Fut2, future3: Fut3, ) -> TryJoin3<Fut1, Fut2, Fut3> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error
1, Fut2, Fut3, Fut4, Fut5> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error>, Fut3: TryFuture<Error = Fut1::Error>, Fut4: TryFuture<Error = Fut1::Error>, Fut5: TryFuture<Error = Fut1::Error>, { TryJoin5::new(future1, future2, future3, future4, future5) }
>, Fut3: TryFuture<Error = Fut1::Error>, { TryJoin3::new(future1, future2, future3) } pub fn try_join4<Fut1, Fut2, Fut3, Fut4>( future1: Fut1, future2: Fut2, future3: Fut3, future4: Fut4, ) -> TryJoin4<Fut1, Fut2, Fut3, Fut4> where Fut1: TryFuture, Fut2: TryFuture<Error = Fut1::Error>, Fut3: TryFuture<Error = Fut1::Error>, Fut4: TryFuture<Error = Fut1::Error>, { TryJoin4::new(future1, future2, future3, future4) } pub fn try_join5<Fut1, Fut2, Fut3, Fut4, Fut5>( future1: Fut1, future2: Fut2, future3: Fut3, future4: Fut4, future5: Fut5, ) -> TryJoin5<Fut
random
[ { "content": "/// Same as [`join`](join()), but with more futures.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # futures::executor::block_on(async {\n\n/// use futures::future;\n\n///\n\n/// let a = async { 1 };\n\n/// let b = async { 2 };\n\n/// let c = async { 3 };\n\n/// let d = async { 4 };\n\n/// let...
Rust
src/revaultd/config.rs
KRD1/revault-gui
5eb9b2fee0c78d63cc5f4b7bb93d1f99c4bb8fb0
use bitcoin::{util::bip32, Network}; use serde::Deserialize; use std::{ net::SocketAddr, path::{Path, PathBuf}, }; #[derive(Debug, Clone, Deserialize)] pub struct BitcoindConfig { pub network: Network, pub cookie_path: PathBuf, pub addr: SocketAddr, pub poll_interval_secs: Option<u64>, } #[derive(Debug, Clone, Deserialize)] pub struct WatchtowerConfig { pub host: String, pub noise_key: String, } #[derive(Debug, Clone, Deserialize)] pub struct StakeholderConfig { pub xpub: bip32::ExtendedPubKey, pub watchtowers: Vec<WatchtowerConfig>, pub emergency_address: String, } #[derive(Debug, Clone, Deserialize)] pub struct CosignerConfig { pub host: String, pub noise_key: String, } #[derive(Debug, Clone, Deserialize)] pub struct ManagerConfig { pub xpub: bip32::ExtendedPubKey, pub cosigners: Vec<CosignerConfig>, } #[derive(Debug, Clone, Deserialize)] pub struct ScriptsConfig { pub deposit_descriptor: String, pub unvault_descriptor: String, pub cpfp_descriptor: String, } #[derive(Debug, Clone, Deserialize)] pub struct Config { pub bitcoind_config: BitcoindConfig, pub stakeholder_config: Option<StakeholderConfig>, pub manager_config: Option<ManagerConfig>, pub scripts_config: ScriptsConfig, pub coordinator_host: String, pub coordinator_noise_key: String, pub coordinator_poll_seconds: Option<u64>, pub data_dir: Option<PathBuf>, pub daemon: Option<bool>, pub log_level: Option<String>, } impl Config { pub fn from_file(path: &Path) -> Result<Self, ConfigError> { let config = std::fs::read(path) .map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => ConfigError::NotFound, _ => ConfigError::ReadingFile(format!("Reading configuration file: {}", e)), }) .and_then(|file_content| { toml::from_slice::<Config>(&file_content).map_err(|e| { ConfigError::ReadingFile(format!("Parsing configuration file: {}", e)) }) })?; Ok(config) } pub fn socket_path(&self) -> Result<PathBuf, ConfigError> { let mut path = if let Some(ref datadir) = self.data_dir { datadir.clone() } else { default_datadir().map_err(|_| { ConfigError::Unexpected("Could not locate the default datadir.".to_owned()) })? }; path.push(&self.bitcoind_config.network.to_string()); path.push("revaultd_rpc"); Ok(path) } pub fn default_path() -> Result<PathBuf, ConfigError> { let mut datadir = default_datadir().map_err(|_| { ConfigError::Unexpected("Could not locate the default datadir.".to_owned()) })?; datadir.push("revault.toml"); Ok(datadir) } } pub fn default_datadir() -> Result<PathBuf, ()> { #[cfg(target_os = "linux")] let configs_dir = dirs::home_dir(); #[cfg(not(target_os = "linux"))] let configs_dir = dirs::config_dir(); if let Some(mut path) = configs_dir { #[cfg(target_os = "linux")] path.push(".revault"); #[cfg(not(target_os = "linux"))] path.push("Revault"); return Ok(path); } Err(()) } #[derive(PartialEq, Eq, Debug, Clone)] pub enum ConfigError { NotFound, ReadingFile(String), Unexpected(String), } impl std::fmt::Display for ConfigError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Self::NotFound => write!(f, "Revaultd Configuration error: not found"), Self::ReadingFile(e) => { write!(f, "Revaultd Configuration error while reading file: {}", e) } Self::Unexpected(e) => write!(f, "Revaultd Configuration error unexpected: {}", e), } } } impl std::error::Error for ConfigError {}
use bitcoin::{util::bip32, Network}; use serde::Deserialize; use std::{ net::SocketAddr, path::{Path, PathBuf}, }; #[derive(Debug, Clone, Deserialize)] pub struct BitcoindConfig { pub network: Network, pub cookie_path: PathBuf, pub addr: SocketAddr, pub poll_interval_secs: Option<u64>, } #[derive(Debug, Clone, Deserialize)] pub struct WatchtowerConfig { pub host: String, pub noise_key: String, } #[derive(Debug, Clone, Deserialize)] pub struct StakeholderConfig { pub xpub: bip32::ExtendedPubKey, pub watchtowers: Vec<WatchtowerConf
figuration file: {}", e)) }) })?; Ok(config) } pub fn socket_path(&self) -> Result<PathBuf, ConfigError> { let mut path = if let Some(ref datadir) = self.data_dir { datadir.clone() } else { default_datadir().map_err(|_| { ConfigError::Unexpected("Could not locate the default datadir.".to_owned()) })? }; path.push(&self.bitcoind_config.network.to_string()); path.push("revaultd_rpc"); Ok(path) } pub fn default_path() -> Result<PathBuf, ConfigError> { let mut datadir = default_datadir().map_err(|_| { ConfigError::Unexpected("Could not locate the default datadir.".to_owned()) })?; datadir.push("revault.toml"); Ok(datadir) } } pub fn default_datadir() -> Result<PathBuf, ()> { #[cfg(target_os = "linux")] let configs_dir = dirs::home_dir(); #[cfg(not(target_os = "linux"))] let configs_dir = dirs::config_dir(); if let Some(mut path) = configs_dir { #[cfg(target_os = "linux")] path.push(".revault"); #[cfg(not(target_os = "linux"))] path.push("Revault"); return Ok(path); } Err(()) } #[derive(PartialEq, Eq, Debug, Clone)] pub enum ConfigError { NotFound, ReadingFile(String), Unexpected(String), } impl std::fmt::Display for ConfigError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Self::NotFound => write!(f, "Revaultd Configuration error: not found"), Self::ReadingFile(e) => { write!(f, "Revaultd Configuration error while reading file: {}", e) } Self::Unexpected(e) => write!(f, "Revaultd Configuration error unexpected: {}", e), } } } impl std::error::Error for ConfigError {}
ig>, pub emergency_address: String, } #[derive(Debug, Clone, Deserialize)] pub struct CosignerConfig { pub host: String, pub noise_key: String, } #[derive(Debug, Clone, Deserialize)] pub struct ManagerConfig { pub xpub: bip32::ExtendedPubKey, pub cosigners: Vec<CosignerConfig>, } #[derive(Debug, Clone, Deserialize)] pub struct ScriptsConfig { pub deposit_descriptor: String, pub unvault_descriptor: String, pub cpfp_descriptor: String, } #[derive(Debug, Clone, Deserialize)] pub struct Config { pub bitcoind_config: BitcoindConfig, pub stakeholder_config: Option<StakeholderConfig>, pub manager_config: Option<ManagerConfig>, pub scripts_config: ScriptsConfig, pub coordinator_host: String, pub coordinator_noise_key: String, pub coordinator_poll_seconds: Option<u64>, pub data_dir: Option<PathBuf>, pub daemon: Option<bool>, pub log_level: Option<String>, } impl Config { pub fn from_file(path: &Path) -> Result<Self, ConfigError> { let config = std::fs::read(path) .map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => ConfigError::NotFound, _ => ConfigError::ReadingFile(format!("Reading configuration file: {}", e)), }) .and_then(|file_content| { toml::from_slice::<Config>(&file_content).map_err(|e| { ConfigError::ReadingFile(format!("Parsing con
random
[ { "content": "pub fn clipboard<'a, T: 'a + Clone>(\n\n state: &'a mut button::State,\n\n message: T,\n\n) -> button::Button<'a, T> {\n\n button::Button::new(state, clipboard_icon().size(15))\n\n .on_press(message)\n\n .style(ClipboardButtonStyle {})\n\n}\n\n\n", "file_path": "src/ui/c...
Rust
src/components/boid.rs
Luke-Draper/Boids
5ddfe3ecc3e34721ed3c6df7dc92cff41fd1e015
use super::player_control::PlayerControl; use super::velocity::Velocity; use amethyst::{ assets::AssetLoaderSystemData, core::{math::Vector3, transform::Transform}, ecs::{prelude::EntityBuilder, Component, VecStorage, World}, prelude::*, renderer::{ rendy::mesh::{Normal, Position, Tangent, TexCoord}, shape::Shape, Material, MaterialDefaults, Mesh, }, }; use serde::{Deserialize, Serialize}; pub enum WingFlapStage { Up, Middle, Down, Ground, } #[derive(Debug, Deserialize, Serialize)] pub enum BoidSpecies { Test, Sparrow, Robin, Cardinal, Bluejay, Eagle, Duck, Goose, Falcon, } pub struct Boid { pub flap_stage: WingFlapStage, pub flap_time: f64, pub step_time: f64, pub hunger: f32, pub flock_id: u8, } impl Component for Boid { type Storage = VecStorage<Self>; } pub fn initialize_boid_default(world: &mut World) { initialize_boid( world, Vector3::new(0.0, 0.0, 0.0), Velocity { velocity: 0.0, direction: Vector3::new(0.0, 0.0, 0.0), }, 0.0, 0.0, ) } pub fn initialize_boid( world: &mut World, position: Vector3<f32>, velocity: Velocity, direction: f32, pitch: f32, ) { setup_boid(world, position, velocity, direction, pitch).build(); } pub fn initialize_player_boid_default(world: &mut World) { initialize_player_boid( world, Vector3::new(0.0, 0.0, 0.0), Velocity { velocity: 0.0, direction: Vector3::new(0.0, 0.0, 0.0), }, 0.0, 0.0, ) } pub fn initialize_player_boid( world: &mut World, position: Vector3<f32>, velocity: Velocity, direction: f32, pitch: f32, ) { setup_boid(world, position, velocity, direction, pitch) .with(PlayerControl {}) .build(); } fn setup_boid( world: &mut World, position: Vector3<f32>, velocity: Velocity, direction: f32, pitch: f32, ) -> EntityBuilder<'_> { let mut trans = Transform::default(); trans .set_translation_xyz(position[0], position[1], position[2]) .set_rotation_euler(direction, pitch, 0.0); let mesh = world.exec(|loader: AssetLoaderSystemData<'_, Mesh>| { loader.load_from_data( Shape::Cone(100) .generate::<(Vec<Position>, Vec<Normal>, Vec<Tangent>, Vec<TexCoord>)>(None) .into(), (), ) }); let material_defaults = world.read_resource::<MaterialDefaults>().0.clone(); let material = world.exec(|loader: AssetLoaderSystemData<'_, Material>| { loader.load_from_data( Material { ..material_defaults }, (), ) }); world .create_entity() .with(mesh) .with(material) .with(trans) .with(velocity) .with(Boid { flap_stage: WingFlapStage::Up, flap_time: 0.0, step_time: 0.0, hunger: 0.0, flock_id: 0, }) }
use super::player_control::PlayerControl; use super::velocity::Velocity; use amethyst::{ assets::AssetLoaderSystemData, core::{math:
f64, pub step_time: f64, pub hunger: f32, pub flock_id: u8, } impl Component for Boid { type Storage = VecStorage<Self>; } pub fn initialize_boid_default(world: &mut World) { initialize_boid( world, Vector3::new(0.0, 0.0, 0.0), Velocity { velocity: 0.0, direction: Vector3::new(0.0, 0.0, 0.0), }, 0.0, 0.0, ) } pub fn initialize_boid( world: &mut World, position: Vector3<f32>, velocity: Velocity, direction: f32, pitch: f32, ) { setup_boid(world, position, velocity, direction, pitch).build(); } pub fn initialize_player_boid_default(world: &mut World) { initialize_player_boid( world, Vector3::new(0.0, 0.0, 0.0), Velocity { velocity: 0.0, direction: Vector3::new(0.0, 0.0, 0.0), }, 0.0, 0.0, ) } pub fn initialize_player_boid( world: &mut World, position: Vector3<f32>, velocity: Velocity, direction: f32, pitch: f32, ) { setup_boid(world, position, velocity, direction, pitch) .with(PlayerControl {}) .build(); } fn setup_boid( world: &mut World, position: Vector3<f32>, velocity: Velocity, direction: f32, pitch: f32, ) -> EntityBuilder<'_> { let mut trans = Transform::default(); trans .set_translation_xyz(position[0], position[1], position[2]) .set_rotation_euler(direction, pitch, 0.0); let mesh = world.exec(|loader: AssetLoaderSystemData<'_, Mesh>| { loader.load_from_data( Shape::Cone(100) .generate::<(Vec<Position>, Vec<Normal>, Vec<Tangent>, Vec<TexCoord>)>(None) .into(), (), ) }); let material_defaults = world.read_resource::<MaterialDefaults>().0.clone(); let material = world.exec(|loader: AssetLoaderSystemData<'_, Material>| { loader.load_from_data( Material { ..material_defaults }, (), ) }); world .create_entity() .with(mesh) .with(material) .with(trans) .with(velocity) .with(Boid { flap_stage: WingFlapStage::Up, flap_time: 0.0, step_time: 0.0, hunger: 0.0, flock_id: 0, }) }
:Vector3, transform::Transform}, ecs::{prelude::EntityBuilder, Component, VecStorage, World}, prelude::*, renderer::{ rendy::mesh::{Normal, Position, Tangent, TexCoord}, shape::Shape, Material, MaterialDefaults, Mesh, }, }; use serde::{Deserialize, Serialize}; pub enum WingFlapStage { Up, Middle, Down, Ground, } #[derive(Debug, Deserialize, Serialize)] pub enum BoidSpecies { Test, Sparrow, Robin, Cardinal, Bluejay, Eagle, Duck, Goose, Falcon, } pub struct Boid { pub flap_stage: WingFlapStage, pub flap_time:
random
[]
Rust
crates/nu-parser/src/lite_parse.rs
Amanita-muscaria/nushell
416ba1407b8553f5da4a6f8ad59c64b85fda3fb4
use std::iter::Peekable; use std::str::CharIndices; use nu_source::{Span, Spanned, SpannedItem}; use crate::errors::{ParseError, ParseResult}; type Input<'t> = Peekable<CharIndices<'t>>; #[derive(Debug, Clone)] pub struct LiteCommand { pub name: Spanned<String>, pub args: Vec<Spanned<String>>, } impl LiteCommand { fn new(name: Spanned<String>) -> LiteCommand { LiteCommand { name, args: vec![] } } pub(crate) fn span(&self) -> Span { let start = self.name.span.start(); let end = if let Some(x) = self.args.last() { x.span.end() } else { self.name.span.end() }; Span::new(start, end) } } #[derive(Debug, Clone)] pub struct LitePipeline { pub commands: Vec<LiteCommand>, } #[derive(Debug, Clone)] pub struct LiteBlock { pub block: Vec<LitePipeline>, } impl From<Spanned<String>> for LiteCommand { fn from(v: Spanned<String>) -> LiteCommand { LiteCommand::new(v) } } fn skip_whitespace(src: &mut Input) { while let Some((_, x)) = src.peek() { if x.is_whitespace() { let _ = src.next(); } else { break; } } } enum BlockKind { Paren, CurlyBracket, SquareBracket, } fn bare(src: &mut Input, span_offset: usize) -> ParseResult<Spanned<String>> { skip_whitespace(src); let mut bare = String::new(); let start_offset = if let Some((pos, _)) = src.peek() { *pos } else { 0 }; let mut inside_quote: Option<char> = None; let mut block_level: Vec<BlockKind> = vec![]; while let Some((_, c)) = src.peek() { let c = *c; if inside_quote.is_some() { if Some(c) == inside_quote { inside_quote = None; } } else if c == '\'' || c == '"' || c == '`' { inside_quote = Some(c); } else if c == '[' { block_level.push(BlockKind::SquareBracket); } else if c == ']' { if let Some(BlockKind::SquareBracket) = block_level.last() { let _ = block_level.pop(); } } else if c == '{' { block_level.push(BlockKind::CurlyBracket); } else if c == '}' { if let Some(BlockKind::CurlyBracket) = block_level.last() { let _ = block_level.pop(); } } else if c == '(' { block_level.push(BlockKind::Paren); } else if c == ')' { if let Some(BlockKind::Paren) = block_level.last() { let _ = block_level.pop(); } } else if block_level.is_empty() && (c.is_whitespace() || c == '|' || c == ';') { break; } bare.push(c); let _ = src.next(); } let span = Span::new( start_offset + span_offset, start_offset + span_offset + bare.len(), ); if let Some(block) = block_level.last() { return Err(ParseError { cause: nu_errors::ParseError::unexpected_eof( match block { BlockKind::Paren => ")", BlockKind::SquareBracket => "]", BlockKind::CurlyBracket => "}", }, span, ), partial: Some(bare.spanned(span)), }); } if let Some(delimiter) = inside_quote { bare.push(delimiter); let span = Span::new( start_offset + span_offset, start_offset + span_offset + bare.len(), ); return Err(ParseError { cause: nu_errors::ParseError::unexpected_eof(delimiter.to_string(), span), partial: Some(bare.spanned(span)), }); } if bare.is_empty() { return Err(ParseError { cause: nu_errors::ParseError::unexpected_eof("command", span), partial: Some(bare.spanned(span)), }); } Ok(bare.spanned(span)) } fn command(src: &mut Input, span_offset: usize) -> ParseResult<LiteCommand> { let mut cmd = match bare(src, span_offset) { Ok(v) => LiteCommand::new(v), Err(e) => { return Err(ParseError { cause: e.cause, partial: e.partial.map(LiteCommand::new), }); } }; loop { skip_whitespace(src); if let Some((_, c)) = src.peek() { match c { ';' => { break; } '|' => { let _ = src.next(); if let Some((pos, next_c)) = src.peek() { if *next_c == '|' { let span = Span::new(pos - 1 + span_offset, pos + 1 + span_offset); cmd.args.push("||".to_string().spanned(span)); let _ = src.next(); } else { break; } } else { break; } } _ => { match bare(src, span_offset) { Ok(v) => { cmd.args.push(v); } Err(e) => { if let Some(v) = e.partial { cmd.args.push(v); } return Err(ParseError { cause: e.cause, partial: Some(cmd), }); } } } } } else { break; } } Ok(cmd) } fn pipeline(src: &mut Input, span_offset: usize) -> ParseResult<LiteBlock> { let mut block = vec![]; let mut commands = vec![]; skip_whitespace(src); while src.peek().is_some() { let cmd = match command(src, span_offset) { Ok(v) => v, Err(e) => { if let Some(partial) = e.partial { commands.push(partial); block.push(LitePipeline { commands }); } return Err(ParseError { cause: e.cause, partial: Some(LiteBlock { block }), }); } }; commands.push(cmd); skip_whitespace(src); if let Some((_, ';')) = src.peek() { let _ = src.next(); if !commands.is_empty() { block.push(LitePipeline { commands }); commands = vec![]; } } } if !commands.is_empty() { block.push(LitePipeline { commands }); } Ok(LiteBlock { block }) } pub fn lite_parse(src: &str, span_offset: usize) -> ParseResult<LiteBlock> { pipeline(&mut src.char_indices().peekable(), span_offset) } #[cfg(test)] mod tests { use super::*; mod bare { use super::*; #[test] fn simple_1() { let input = "foo bar baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 3); } #[test] fn simple_2() { let input = "'foo bar' baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 9); } #[test] fn simple_3() { let input = "'foo\" bar' baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 10); } #[test] fn simple_4() { let input = "[foo bar] baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 9); } #[test] fn simple_5() { let input = "'foo 'bar baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 9); } #[test] fn simple_6() { let input = "''foo baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 5); } #[test] fn simple_7() { let input = "'' foo"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 2); } #[test] fn simple_8() { let input = " '' foo"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 1); assert_eq!(result.span.end(), 3); } #[test] fn simple_9() { let input = " 'foo' foo"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 1); assert_eq!(result.span.end(), 6); } #[test] fn ignore_future() { let input = "foo 'bar"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 3); } #[test] fn invalid_1() { let input = "'foo bar"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0); assert_eq!(result.is_ok(), false); } #[test] fn invalid_2() { let input = "'bar"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0); assert_eq!(result.is_ok(), false); } #[test] fn invalid_4() { let input = " 'bar"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0); assert_eq!(result.is_ok(), false); } } mod lite_parse { use super::*; #[test] fn simple_1() { let result = lite_parse("foo", 0).unwrap(); assert_eq!(result.block.len(), 1); assert_eq!(result.block[0].commands.len(), 1); assert_eq!(result.block[0].commands[0].name.span.start(), 0); assert_eq!(result.block[0].commands[0].name.span.end(), 3); } #[test] fn simple_offset() { let result = lite_parse("foo", 10).unwrap(); assert_eq!(result.block.len(), 1); assert_eq!(result.block[0].commands.len(), 1); assert_eq!(result.block[0].commands[0].name.span.start(), 10); assert_eq!(result.block[0].commands[0].name.span.end(), 13); } #[test] fn incomplete_result() { let result = lite_parse("my_command \"foo' --test", 10).unwrap_err(); assert!(matches!(result.cause.reason(), nu_errors::ParseErrorReason::Eof { .. })); let result = result.partial.unwrap(); assert_eq!(result.block.len(), 1); assert_eq!(result.block[0].commands.len(), 1); assert_eq!(result.block[0].commands[0].name.item, "my_command"); assert_eq!(result.block[0].commands[0].args.len(), 1); assert_eq!(result.block[0].commands[0].args[0].item, "\"foo' --test\""); } } }
use std::iter::Peekable; use std::str::CharIndices; use nu_source::{Span, Spanned, SpannedItem}; use crate::errors::{ParseError, ParseResult}; type Input<'t> = Peekable<CharIndices<'t>>; #[derive(Debug, Clone)] pub struct LiteCommand { pub name: Spanned<String>, pub args: Vec<Spanned<String>>, } impl LiteCommand { fn new(name: Spanned<String>) -> LiteCommand { LiteCommand { name, args: vec![] } } pub(crate) fn span(&self) -> Span { let start = self.name.span.start(); let end = if let Some(x) = self.args.last() { x.span.end() } else { self.name.span.end() }; Span::new(start, end) } } #[derive(Debug, Clone)] pub struct LitePipeline { pub commands: Vec<LiteCommand>, } #[derive(Debug, Clone)] pub struct LiteBlock { pub block: Vec<LitePipeline>, } impl From<Spanned<String>> for LiteCommand { fn from(v: Spanned<String>) -> LiteCommand { LiteCommand::new(v) } } fn skip_whitespace(src: &mut Input) { while let Some((_, x)) = src.peek() { if x.is_whitespace() { let _ = src.next(); } else { break; } } } enum BlockKind { Paren, CurlyBracket, SquareBracket, } fn bare(src: &mut Input, span_offset: usize) -> ParseResult<Spanned<String>> { skip_whitespace(src); let mut bare = String::new(); let start_offset = if let Some((pos, _)) = src.peek() { *pos } else { 0 }; let mut inside_quote: Option<char> = None; let mut block_level: Vec<BlockKind> = vec![]; while let Some((_, c)) = src.peek() { let c = *c; if inside_quote.is_some() { if Some(c) == inside_quote { inside_quote = None; } } else if c == '\'' || c == '"' || c == '`' { inside_quote = Some(c); } else if c == '[' { block_level.push(BlockKind::SquareBracket); } else if c == ']' { if let Some(BlockKind::SquareBracket) = block_level.last() { let _ = block_level.pop(); } } else if c == '{' { block_level.push(BlockKind::CurlyBracket); } else if c == '}' { if let Some(BlockKind::CurlyBracket) = block_level.last() { let _ = block_level.pop(); } } else if c == '(' { block_level.push(BlockKind::Paren); } else if c == ')' { if let Some(BlockKind::Paren) = block_level.last() { let _ = block_level.pop(); } } else if block_level.is_empty() && (c.is_whitespace() || c == '|' || c == ';') { break; } bare.push(c); let _ = src.next(); } let span = Span::new( start_offset + span_offset, start_offset + span_offset + bare.len(), ); if let Some(block) = block_level.last() { return Err(ParseError { cause: nu_errors::ParseError::unexpected_eof(
, span, ), partial: Some(bare.spanned(span)), }); } if let Some(delimiter) = inside_quote { bare.push(delimiter); let span = Span::new( start_offset + span_offset, start_offset + span_offset + bare.len(), ); return Err(ParseError { cause: nu_errors::ParseError::unexpected_eof(delimiter.to_string(), span), partial: Some(bare.spanned(span)), }); } if bare.is_empty() { return Err(ParseError { cause: nu_errors::ParseError::unexpected_eof("command", span), partial: Some(bare.spanned(span)), }); } Ok(bare.spanned(span)) } fn command(src: &mut Input, span_offset: usize) -> ParseResult<LiteCommand> { let mut cmd = match bare(src, span_offset) { Ok(v) => LiteCommand::new(v), Err(e) => { return Err(ParseError { cause: e.cause, partial: e.partial.map(LiteCommand::new), }); } }; loop { skip_whitespace(src); if let Some((_, c)) = src.peek() { match c { ';' => { break; } '|' => { let _ = src.next(); if let Some((pos, next_c)) = src.peek() { if *next_c == '|' { let span = Span::new(pos - 1 + span_offset, pos + 1 + span_offset); cmd.args.push("||".to_string().spanned(span)); let _ = src.next(); } else { break; } } else { break; } } _ => { match bare(src, span_offset) { Ok(v) => { cmd.args.push(v); } Err(e) => { if let Some(v) = e.partial { cmd.args.push(v); } return Err(ParseError { cause: e.cause, partial: Some(cmd), }); } } } } } else { break; } } Ok(cmd) } fn pipeline(src: &mut Input, span_offset: usize) -> ParseResult<LiteBlock> { let mut block = vec![]; let mut commands = vec![]; skip_whitespace(src); while src.peek().is_some() { let cmd = match command(src, span_offset) { Ok(v) => v, Err(e) => { if let Some(partial) = e.partial { commands.push(partial); block.push(LitePipeline { commands }); } return Err(ParseError { cause: e.cause, partial: Some(LiteBlock { block }), }); } }; commands.push(cmd); skip_whitespace(src); if let Some((_, ';')) = src.peek() { let _ = src.next(); if !commands.is_empty() { block.push(LitePipeline { commands }); commands = vec![]; } } } if !commands.is_empty() { block.push(LitePipeline { commands }); } Ok(LiteBlock { block }) } pub fn lite_parse(src: &str, span_offset: usize) -> ParseResult<LiteBlock> { pipeline(&mut src.char_indices().peekable(), span_offset) } #[cfg(test)] mod tests { use super::*; mod bare { use super::*; #[test] fn simple_1() { let input = "foo bar baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 3); } #[test] fn simple_2() { let input = "'foo bar' baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 9); } #[test] fn simple_3() { let input = "'foo\" bar' baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 10); } #[test] fn simple_4() { let input = "[foo bar] baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 9); } #[test] fn simple_5() { let input = "'foo 'bar baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 9); } #[test] fn simple_6() { let input = "''foo baz"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 5); } #[test] fn simple_7() { let input = "'' foo"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 2); } #[test] fn simple_8() { let input = " '' foo"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 1); assert_eq!(result.span.end(), 3); } #[test] fn simple_9() { let input = " 'foo' foo"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 1); assert_eq!(result.span.end(), 6); } #[test] fn ignore_future() { let input = "foo 'bar"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0).unwrap(); assert_eq!(result.span.start(), 0); assert_eq!(result.span.end(), 3); } #[test] fn invalid_1() { let input = "'foo bar"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0); assert_eq!(result.is_ok(), false); } #[test] fn invalid_2() { let input = "'bar"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0); assert_eq!(result.is_ok(), false); } #[test] fn invalid_4() { let input = " 'bar"; let input = &mut input.char_indices().peekable(); let result = bare(input, 0); assert_eq!(result.is_ok(), false); } } mod lite_parse { use super::*; #[test] fn simple_1() { let result = lite_parse("foo", 0).unwrap(); assert_eq!(result.block.len(), 1); assert_eq!(result.block[0].commands.len(), 1); assert_eq!(result.block[0].commands[0].name.span.start(), 0); assert_eq!(result.block[0].commands[0].name.span.end(), 3); } #[test] fn simple_offset() { let result = lite_parse("foo", 10).unwrap(); assert_eq!(result.block.len(), 1); assert_eq!(result.block[0].commands.len(), 1); assert_eq!(result.block[0].commands[0].name.span.start(), 10); assert_eq!(result.block[0].commands[0].name.span.end(), 13); } #[test] fn incomplete_result() { let result = lite_parse("my_command \"foo' --test", 10).unwrap_err(); assert!(matches!(result.cause.reason(), nu_errors::ParseErrorReason::Eof { .. })); let result = result.partial.unwrap(); assert_eq!(result.block.len(), 1); assert_eq!(result.block[0].commands.len(), 1); assert_eq!(result.block[0].commands[0].name.item, "my_command"); assert_eq!(result.block[0].commands[0].args.len(), 1); assert_eq!(result.block[0].commands[0].args[0].item, "\"foo' --test\""); } } }
match block { BlockKind::Paren => ")", BlockKind::SquareBracket => "]", BlockKind::CurlyBracket => "}", }
if_condition
[ { "content": "pub fn span_for_spanned_list(mut iter: impl Iterator<Item = Span>) -> Span {\n\n let first = iter.next();\n\n\n\n let first = match first {\n\n None => return Span::unknown(),\n\n Some(first) => first,\n\n };\n\n\n\n let last = iter.last();\n\n\n\n match last {\n\n ...
Rust
crates/revm/src/evm.rs
mattsse/revm
247d4d0e19b15feb0cf400e8d5dd93921b41a9d7
use crate::{ db::{Database, DatabaseCommit, DatabaseRef, RefDBWrapper}, error::ExitReason, evm_impl::{EVMImpl, Transact}, subroutine::State, BerlinSpec, ByzantineSpec, Env, Inspector, IstanbulSpec, LatestSpec, LondonSpec, NoOpInspector, Spec, SpecId, TransactOut, }; use alloc::boxed::Box; use revm_precompiles::Precompiles; pub struct EVM<DB> { pub env: Env, pub db: Option<DB>, } pub fn new<DB>() -> EVM<DB> { EVM::new() } impl<DB: Database + DatabaseCommit> EVM<DB> { pub fn transact_commit(&mut self) -> (ExitReason, TransactOut, u64) { let (exit, out, gas, state) = self.transact(); self.db.as_mut().unwrap().commit(state); (exit, out, gas) } pub fn inspect_commit<INSP: Inspector>( &mut self, inspector: INSP, ) -> (ExitReason, TransactOut, u64) { let (exit, out, gas, state) = self.inspect(inspector); self.db.as_mut().unwrap().commit(state); (exit, out, gas) } } impl<DB: Database> EVM<DB> { pub fn transact(&mut self) -> (ExitReason, TransactOut, u64, State) { if let Some(db) = self.db.as_mut() { let mut noop = NoOpInspector {}; let out = evm_inner::<DB, false>(&self.env, db, &mut noop).transact(); out } else { panic!("Database needs to be set"); } } pub fn inspect<INSP: Inspector>( &mut self, mut inspector: INSP, ) -> (ExitReason, TransactOut, u64, State) { if let Some(db) = self.db.as_mut() { evm_inner::<DB, true>(&self.env, db, &mut inspector).transact() } else { panic!("Database needs to be set"); } } } impl<DB: DatabaseRef> EVM<DB> { pub fn transact_ref(&self) -> (ExitReason, TransactOut, u64, State) { if let Some(db) = self.db.as_ref() { let mut noop = NoOpInspector {}; let mut db = RefDBWrapper::new(db); let db = &mut db; let out = evm_inner::<RefDBWrapper, false>(&self.env, db, &mut noop).transact(); out } else { panic!("Database needs to be set"); } } pub fn inspect_ref<INSP: Inspector>( &self, mut inspector: INSP, ) -> (ExitReason, TransactOut, u64, State) { if let Some(db) = self.db.as_ref() { let mut db = RefDBWrapper::new(db); let db = &mut db; let out = evm_inner::<RefDBWrapper, true>(&self.env, db, &mut inspector).transact(); out } else { panic!("Database needs to be set"); } } } impl<DB> EVM<DB> { pub fn new() -> Self { Self { env: Env::default(), db: None, } } pub fn database(&mut self, db: DB) { self.db = Some(db); } pub fn db(&mut self) -> Option<&mut DB> { self.db.as_mut() } pub fn take_db(&mut self) -> DB { core::mem::take(&mut self.db).unwrap() } } macro_rules! create_evm { ($spec:ident, $db:ident,$env:ident,$inspector:ident) => { Box::new(EVMImpl::<'a, $spec, DB, INSPECT>::new( $db, $env, $inspector, Precompiles::new::<{ SpecId::to_precompile_id($spec::SPEC_ID) }>(), )) as Box<dyn Transact + 'a> }; } pub fn evm_inner<'a, DB: Database, const INSPECT: bool>( env: &'a Env, db: &'a mut DB, insp: &'a mut dyn Inspector, ) -> Box<dyn Transact + 'a> { match env.cfg.spec_id { SpecId::LATEST => create_evm!(LatestSpec, db, env, insp), SpecId::LONDON => create_evm!(LondonSpec, db, env, insp), SpecId::BERLIN => create_evm!(BerlinSpec, db, env, insp), SpecId::ISTANBUL => create_evm!(IstanbulSpec, db, env, insp), SpecId::BYZANTINE => create_evm!(ByzantineSpec, db, env, insp), _ => panic!("Spec Not supported"), } }
use crate::{ db::{Database, DatabaseCommit, DatabaseRef, RefDBWrapper}, error::ExitReason, evm_impl::{EVMImpl, Transact}, subroutine::State, BerlinSpec, ByzantineSpec, Env, Inspector, IstanbulSpec, LatestSpec, LondonSpec, NoOpInspector, Spec, SpecId, TransactOut, }; use alloc::boxed::Box; use revm_precompiles::Precompiles; pub struct EVM<DB> { pub env: Env, pub db: Option<DB>, } pub fn new<DB>() -> EVM<DB> { EVM::new() } impl<DB: Database + DatabaseCommit> EVM<DB> { pub fn transact_commit(&mut self) -> (ExitReason, TransactOut, u64) { let (exit, out, gas, state) = self.transact(); self.db.as_mut().unwrap().commit(state); (exit, out, gas) } pub fn inspect_commit<INSP: Inspector>( &mut self, inspector: INSP, ) -> (
} impl<DB: Database> EVM<DB> { pub fn transact(&mut self) -> (ExitReason, TransactOut, u64, State) { if let Some(db) = self.db.as_mut() { let mut noop = NoOpInspector {}; let out = evm_inner::<DB, false>(&self.env, db, &mut noop).transact(); out } else { panic!("Database needs to be set"); } } pub fn inspect<INSP: Inspector>( &mut self, mut inspector: INSP, ) -> (ExitReason, TransactOut, u64, State) { if let Some(db) = self.db.as_mut() { evm_inner::<DB, true>(&self.env, db, &mut inspector).transact() } else { panic!("Database needs to be set"); } } } impl<DB: DatabaseRef> EVM<DB> { pub fn transact_ref(&self) -> (ExitReason, TransactOut, u64, State) { if let Some(db) = self.db.as_ref() { let mut noop = NoOpInspector {}; let mut db = RefDBWrapper::new(db); let db = &mut db; let out = evm_inner::<RefDBWrapper, false>(&self.env, db, &mut noop).transact(); out } else { panic!("Database needs to be set"); } } pub fn inspect_ref<INSP: Inspector>( &self, mut inspector: INSP, ) -> (ExitReason, TransactOut, u64, State) { if let Some(db) = self.db.as_ref() { let mut db = RefDBWrapper::new(db); let db = &mut db; let out = evm_inner::<RefDBWrapper, true>(&self.env, db, &mut inspector).transact(); out } else { panic!("Database needs to be set"); } } } impl<DB> EVM<DB> { pub fn new() -> Self { Self { env: Env::default(), db: None, } } pub fn database(&mut self, db: DB) { self.db = Some(db); } pub fn db(&mut self) -> Option<&mut DB> { self.db.as_mut() } pub fn take_db(&mut self) -> DB { core::mem::take(&mut self.db).unwrap() } } macro_rules! create_evm { ($spec:ident, $db:ident,$env:ident,$inspector:ident) => { Box::new(EVMImpl::<'a, $spec, DB, INSPECT>::new( $db, $env, $inspector, Precompiles::new::<{ SpecId::to_precompile_id($spec::SPEC_ID) }>(), )) as Box<dyn Transact + 'a> }; } pub fn evm_inner<'a, DB: Database, const INSPECT: bool>( env: &'a Env, db: &'a mut DB, insp: &'a mut dyn Inspector, ) -> Box<dyn Transact + 'a> { match env.cfg.spec_id { SpecId::LATEST => create_evm!(LatestSpec, db, env, insp), SpecId::LONDON => create_evm!(LondonSpec, db, env, insp), SpecId::BERLIN => create_evm!(BerlinSpec, db, env, insp), SpecId::ISTANBUL => create_evm!(IstanbulSpec, db, env, insp), SpecId::BYZANTINE => create_evm!(ByzantineSpec, db, env, insp), _ => panic!("Spec Not supported"), } }
ExitReason, TransactOut, u64) { let (exit, out, gas, state) = self.inspect(inspector); self.db.as_mut().unwrap().commit(state); (exit, out, gas) }
function_block-function_prefix_line
[ { "content": "#[inline(always)]\n\nfn gas_call_l64_after<SPEC: Spec>(machine: &mut Machine) -> Result<u64, ExitReason> {\n\n if SPEC::enabled(TANGERINE) {\n\n //EIP-150: Gas cost changes for IO-heavy operations\n\n let gas = machine.gas().remaining();\n\n Ok(gas - gas / 64)\n\n } else...
Rust
src/lib.rs
DerickEddington/cycle_deep_safe_compare
3c3d4f5615c9d434f4037e373a7390ae34656464
#![cfg_attr(unix, doc = include_str!("../README.md"))] #![cfg_attr(windows, doc = include_str!("..\\README.md"))] #![cfg_attr( not(feature = "std"), doc = "\n", doc = "Note: This crate was built without its `std` feature and some premade items are \ unavailable, and so custom types must be provided and used with the items of the \ [`generic`] module, to have cycle-safety and/or deep-safety." )] #![cfg_attr( all(not(feature = "std"), feature = "alloc"), doc = "\n", doc = "Note: This crate was built with its `alloc` feature, and so some premade items, \ that use the [`alloc`](https://doc.rust-lang.org/alloc/) crate, are available." )] #![no_std] #![forbid(unsafe_code)] #![warn( future_incompatible, nonstandard_style, rust_2018_compatibility, rust_2018_idioms, rust_2021_compatibility, unused, clippy::all, clippy::pedantic, clippy::restriction, clippy::cargo, macro_use_extern_crate, meta_variable_misuse, missing_docs, noop_method_call, pointer_structural_match, single_use_lifetimes, trivial_casts, trivial_numeric_casts, unreachable_pub, unused_extern_crates, unused_import_braces, unused_lifetimes, unused_qualifications, unused_results, variant_size_differences, )] #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![allow( clippy::implicit_return, clippy::blanket_clippy_restriction_lints, clippy::default_numeric_fallback, clippy::separated_literal_suffix, clippy::single_char_lifetime_names, clippy::missing_docs_in_private_items, clippy::pattern_type_mismatch, clippy::shadow_reuse )] #![cfg_attr( all(feature = "anticipate", not(rust_lib_feature = "step_trait")), feature(step_trait) )] #![cfg_attr( all(feature = "anticipate", not(rust_lib_feature = "unwrap_infallible")), feature(unwrap_infallible) )] #![cfg_attr( all(feature = "anticipate", not(rust_lang_feature = "never_type")), feature(never_type) )] #[cfg(feature = "std")] pub mod robust; pub mod cycle_safe; #[cfg(feature = "alloc")] pub mod deep_safe; #[cfg(feature = "alloc")] pub mod wide_safe; pub mod basic; pub mod generic; pub mod utils; cfg_if::cfg_if! { if #[cfg(feature = "anticipate")] { mod anticipated; use anticipated as anticipated_or_like; use core::iter::Step; } else { mod like_anticipated; use like_anticipated as anticipated_or_like; pub use like_anticipated::Step; } } use core::{ cmp::Ordering, hash::Hash, }; pub trait Node: Sized { type Cmp: Cmp; type Id: Eq + Hash + Clone; type Index: Step + Default + Ord; fn id(&self) -> Self::Id; #[must_use] fn get_edge( &self, index: &Self::Index, ) -> Option<Self>; fn equiv_modulo_edges( &self, other: &Self, ) -> Self::Cmp; } pub trait Cmp { fn new_equiv() -> Self; fn is_equiv(&self) -> bool; fn from_ord(ord: Ordering) -> Self; } impl Cmp for bool { #[inline] fn new_equiv() -> Self { true } #[inline] fn is_equiv(&self) -> bool { *self } #[inline] fn from_ord(ord: Ordering) -> Self { ord.is_eq() } } impl Cmp for Ordering { #[inline] fn new_equiv() -> Self { Ordering::Equal } #[inline] fn is_equiv(&self) -> bool { self.is_eq() } #[inline] fn from_ord(ord: Ordering) -> Self { ord } }
#![cfg_attr(unix, doc = include_str!("../README.md"))] #![cfg_attr(windows, doc = include_str!("..\\README.md"))] #![cfg_attr( not(feature = "std"), doc = "\n", doc = "Note: This crate was built without its `std` feature and some premade items are \ unavailable, and so custom types must be provided and used with the items of the \ [`generic`] module, to have cycle-safety and/or deep-safety." )] #![cfg_attr( all(not(feature = "std"), feature = "alloc"), doc = "\n", doc = "Note: This crate was built with its `alloc` feature, and so some premade items, \ that use the [`alloc`](https://doc.rust-lang.org/alloc/) crate, are available." )] #![no_std] #![forbid(unsafe_code)] #![warn( future_incompatible, nonstandard_style, rust_2018_compatibility, rust_2018_idioms, rust_2021_compatibility, unused, clippy::all, clippy::pedantic, clippy::restriction, clippy::cargo,
self } #[inline] fn from_ord(ord: Ordering) -> Self { ord.is_eq() } } impl Cmp for Ordering { #[inline] fn new_equiv() -> Self { Ordering::Equal } #[inline] fn is_equiv(&self) -> bool { self.is_eq() } #[inline] fn from_ord(ord: Ordering) -> Self { ord } }
macro_use_extern_crate, meta_variable_misuse, missing_docs, noop_method_call, pointer_structural_match, single_use_lifetimes, trivial_casts, trivial_numeric_casts, unreachable_pub, unused_extern_crates, unused_import_braces, unused_lifetimes, unused_qualifications, unused_results, variant_size_differences, )] #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![allow( clippy::implicit_return, clippy::blanket_clippy_restriction_lints, clippy::default_numeric_fallback, clippy::separated_literal_suffix, clippy::single_char_lifetime_names, clippy::missing_docs_in_private_items, clippy::pattern_type_mismatch, clippy::shadow_reuse )] #![cfg_attr( all(feature = "anticipate", not(rust_lib_feature = "step_trait")), feature(step_trait) )] #![cfg_attr( all(feature = "anticipate", not(rust_lib_feature = "unwrap_infallible")), feature(unwrap_infallible) )] #![cfg_attr( all(feature = "anticipate", not(rust_lang_feature = "never_type")), feature(never_type) )] #[cfg(feature = "std")] pub mod robust; pub mod cycle_safe; #[cfg(feature = "alloc")] pub mod deep_safe; #[cfg(feature = "alloc")] pub mod wide_safe; pub mod basic; pub mod generic; pub mod utils; cfg_if::cfg_if! { if #[cfg(feature = "anticipate")] { mod anticipated; use anticipated as anticipated_or_like; use core::iter::Step; } else { mod like_anticipated; use like_anticipated as anticipated_or_like; pub use like_anticipated::Step; } } use core::{ cmp::Ordering, hash::Hash, }; pub trait Node: Sized { type Cmp: Cmp; type Id: Eq + Hash + Clone; type Index: Step + Default + Ord; fn id(&self) -> Self::Id; #[must_use] fn get_edge( &self, index: &Self::Index, ) -> Option<Self>; fn equiv_modulo_edges( &self, other: &Self, ) -> Self::Cmp; } pub trait Cmp { fn new_equiv() -> Self; fn is_equiv(&self) -> bool; fn from_ord(ord: Ordering) -> Self; } impl Cmp for bool { #[inline] fn new_equiv() -> Self { true } #[inline] fn is_equiv(&self) -> bool { *
random
[ { "content": "struct Args<N>(PhantomData<N>);\n\n\n\nimpl<N: Node> interleave::Params for Args<N>\n\n{\n\n type Node = N;\n\n type RNG = default::RandomNumberGenerator;\n\n type Table = hash_map::Table<Self>;\n\n}\n\n\n\nimpl<N: Node> hash_map::Params for Args<N>\n\n{\n\n type Node = N;\n\n}\n\n\n\n...
Rust
src/proto/par_vec.rs
gereeter/collect-rs
dc4380faac395ef412937dba58249e72873414e9
extern crate alloc; use self::alloc::arc; use std::cmp::min; use std::fmt::{Formatter, Show}; use std::fmt::Error as FmtError; use std::iter::range_inclusive; use std::sync::Arc; use std::mem; use std::ops; pub struct ParVec<T> { data: Arc<Vec<T>>, } impl<T: Send + Sync> ParVec<T> { pub fn new(vec: Vec<T>, slices: uint) -> (ParVec<T>, Vec<ParSlice<T>>) { let data = Arc::new(vec); let par_slices = sub_slices(data.as_slice(), slices).into_iter() .map(|slice| ParSlice { _vec: data.clone(), data: unsafe { mem::transmute(slice) }, } ).collect(); let par_vec = ParVec { data: data, }; (par_vec, par_slices) } pub fn into_inner_opt(self) -> Result<Vec<T>, ParVec<T>> { if arc::strong_count(&self.data) == 1 { let vec_ptr: &mut Vec<T> = unsafe { mem::transmute(&*self.data) }; Ok(mem::replace(vec_ptr, Vec::new())) } else { Err(self) } } pub fn into_inner(mut self) -> Vec<T> { loop { match self.into_inner_opt() { Ok(vec) => return vec, Err(new_self) => self = new_self, } } } } fn sub_slices<T>(parent: &[T], slice_count: uint) -> Vec<&[T]> { let mut slices = Vec::new(); let len = parent.len(); let mut start = 0u; for curr in range_inclusive(1, slice_count).rev() { let slice_len = (len - start) / curr; let end = min(start + slice_len, len); slices.push(parent.slice(start, end)); start += slice_len; } slices } pub struct ParSlice<T: Send> { _vec: Arc<Vec<T>>, data: &'static mut [T], } impl<T: Send> ops::Deref for ParSlice<T> { type Target = [T]; fn deref<'a>(&'a self) -> &'a [T] { self.data } } impl<T: Send> ops::DerefMut for ParSlice<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.data } } impl<T: Send> Show for ParSlice<T> where T: Show { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { write!(f, "{}", self.data) } } #[cfg(test)] mod test { extern crate test; use self::test::Bencher; use super::ParVec; use std::mem; use std::rand::{thread_rng, Rng}; use std::iter::range_inclusive; const TEST_SLICES: uint = 8; const TEST_MAX: u32 = 1000; #[test] fn test_unwrap_safely() { let (vec, slices) = ParVec::new([5u; TEST_MAX as uint].to_vec(), TEST_SLICES); mem::drop(slices); let vec = vec.into_inner(); assert_eq!(&*vec, [5u; TEST_MAX as uint].as_slice()); } #[test] fn test_slices() { let (_, slices) = ParVec::new(range(1u32, TEST_MAX).collect(), TEST_SLICES); assert_eq!(slices.len(), TEST_SLICES); } #[bench] fn seq_prime_factors_1000(b: &mut Bencher) { let vec: Vec<u32> = range_inclusive(1, TEST_MAX).collect(); b.iter(|| { let _: Vec<(u32, Vec<u32>)> = vec.iter() .map(|&x| (x, get_prime_factors(x))) .collect(); }); } #[bench] fn par_prime_factors_1000(b: &mut Bencher) { use std::sync::TaskPool; let mut rng = thread_rng(); let pool = TaskPool::new(TEST_SLICES); b.iter(|| { let mut vec: Vec<(u32, Vec<u32>)> = range_inclusive(1, TEST_MAX) .map(|x| (x, Vec::new())).collect(); rng.shuffle(&mut *vec); let (par_vec, par_slices) = ParVec::new(vec, TEST_SLICES); for mut slice in par_slices.into_iter() { pool.execute(move || for pair in slice.iter_mut() { let (x, ref mut x_primes) = *pair; *x_primes = get_prime_factors(x); } ); } let mut vec = par_vec.into_inner(); vec.sort(); }); } fn get_prime_factors(x: u32) -> Vec<u32> { range(1, x).filter(|&y| x % y == 0 && is_prime(y)).collect() } fn is_prime(x: u32) -> bool { use std::iter::range_step; if x < 3 { return true; } if x & 1 == 0 { return false; } for i in range_step(3, x, 2) { if x % i == 0 { return false; } } true } }
extern crate alloc; use self::alloc::arc; use std::cmp::min; use std::fmt::{Formatter, Show}; use std::fmt::Error as FmtError; use std::iter::range_inclusive; use std::sync::Arc; use std::mem; use std::ops; pub struct ParVec<T> { data: Arc<Vec<T>>, } impl<T: Send + Sync> ParVec<T> { pub fn new(vec: Vec<T>, slices: uint) -> (ParVec<T>, Vec<ParSlice<T>>) { let data = Arc::new(vec); let par_slices = sub_slices(data.as_slice(), slices).into_iter() .map(|slice| ParSlice { _vec: data.clone(), data: unsafe { mem::transmute(slice) }, } ).collect(); let par_vec = ParVec { data: data, }; (par_vec, par_slices) } pub fn into_inner_opt(self) -> Result<Vec<T>, ParVec<T>> {
} pub fn into_inner(mut self) -> Vec<T> { loop { match self.into_inner_opt() { Ok(vec) => return vec, Err(new_self) => self = new_self, } } } } fn sub_slices<T>(parent: &[T], slice_count: uint) -> Vec<&[T]> { let mut slices = Vec::new(); let len = parent.len(); let mut start = 0u; for curr in range_inclusive(1, slice_count).rev() { let slice_len = (len - start) / curr; let end = min(start + slice_len, len); slices.push(parent.slice(start, end)); start += slice_len; } slices } pub struct ParSlice<T: Send> { _vec: Arc<Vec<T>>, data: &'static mut [T], } impl<T: Send> ops::Deref for ParSlice<T> { type Target = [T]; fn deref<'a>(&'a self) -> &'a [T] { self.data } } impl<T: Send> ops::DerefMut for ParSlice<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.data } } impl<T: Send> Show for ParSlice<T> where T: Show { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { write!(f, "{}", self.data) } } #[cfg(test)] mod test { extern crate test; use self::test::Bencher; use super::ParVec; use std::mem; use std::rand::{thread_rng, Rng}; use std::iter::range_inclusive; const TEST_SLICES: uint = 8; const TEST_MAX: u32 = 1000; #[test] fn test_unwrap_safely() { let (vec, slices) = ParVec::new([5u; TEST_MAX as uint].to_vec(), TEST_SLICES); mem::drop(slices); let vec = vec.into_inner(); assert_eq!(&*vec, [5u; TEST_MAX as uint].as_slice()); } #[test] fn test_slices() { let (_, slices) = ParVec::new(range(1u32, TEST_MAX).collect(), TEST_SLICES); assert_eq!(slices.len(), TEST_SLICES); } #[bench] fn seq_prime_factors_1000(b: &mut Bencher) { let vec: Vec<u32> = range_inclusive(1, TEST_MAX).collect(); b.iter(|| { let _: Vec<(u32, Vec<u32>)> = vec.iter() .map(|&x| (x, get_prime_factors(x))) .collect(); }); } #[bench] fn par_prime_factors_1000(b: &mut Bencher) { use std::sync::TaskPool; let mut rng = thread_rng(); let pool = TaskPool::new(TEST_SLICES); b.iter(|| { let mut vec: Vec<(u32, Vec<u32>)> = range_inclusive(1, TEST_MAX) .map(|x| (x, Vec::new())).collect(); rng.shuffle(&mut *vec); let (par_vec, par_slices) = ParVec::new(vec, TEST_SLICES); for mut slice in par_slices.into_iter() { pool.execute(move || for pair in slice.iter_mut() { let (x, ref mut x_primes) = *pair; *x_primes = get_prime_factors(x); } ); } let mut vec = par_vec.into_inner(); vec.sort(); }); } fn get_prime_factors(x: u32) -> Vec<u32> { range(1, x).filter(|&y| x % y == 0 && is_prime(y)).collect() } fn is_prime(x: u32) -> bool { use std::iter::range_step; if x < 3 { return true; } if x & 1 == 0 { return false; } for i in range_step(3, x, 2) { if x % i == 0 { return false; } } true } }
if arc::strong_count(&self.data) == 1 { let vec_ptr: &mut Vec<T> = unsafe { mem::transmute(&*self.data) }; Ok(mem::replace(vec_ptr, Vec::new())) } else { Err(self) }
if_condition
[ { "content": "pub fn insert_seq_n<M, I, R>(n: uint,\n\n map: &mut M,\n\n b: &mut Bencher,\n\n mut insert: I,\n\n mut remove: R) where\n\n I: FnMut(&mut M, uint),\n\n R: FnMut(&mut M, uint),\n\n{...
Rust
postgres/src/transaction.rs
dvic/rust-postgres
5d08af01ec520cba1a8642cb7c66ce070b03f4ca
use crate::{ CancelToken, CopyInWriter, CopyOutReader, GenericClient, Portal, RowIter, Rt, Statement, ToStatement, }; use tokio::runtime::Runtime; use tokio_postgres::types::{ToSql, Type}; use tokio_postgres::{Error, Row, SimpleQueryMessage}; pub struct Transaction<'a> { runtime: &'a mut Runtime, transaction: tokio_postgres::Transaction<'a>, } impl<'a> Transaction<'a> { pub(crate) fn new( runtime: &'a mut Runtime, transaction: tokio_postgres::Transaction<'a>, ) -> Transaction<'a> { Transaction { runtime, transaction, } } fn rt(&mut self) -> Rt<'_> { Rt(self.runtime) } pub fn commit(self) -> Result<(), Error> { self.runtime.block_on(self.transaction.commit()) } pub fn rollback(self) -> Result<(), Error> { self.runtime.block_on(self.transaction.rollback()) } pub fn prepare(&mut self, query: &str) -> Result<Statement, Error> { self.runtime.block_on(self.transaction.prepare(query)) } pub fn prepare_typed(&mut self, query: &str, types: &[Type]) -> Result<Statement, Error> { self.runtime .block_on(self.transaction.prepare_typed(query, types)) } pub fn execute<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<u64, Error> where T: ?Sized + ToStatement, { self.runtime .block_on(self.transaction.execute(query, params)) } pub fn query<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<Vec<Row>, Error> where T: ?Sized + ToStatement, { self.runtime.block_on(self.transaction.query(query, params)) } pub fn query_one<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<Row, Error> where T: ?Sized + ToStatement, { self.runtime .block_on(self.transaction.query_one(query, params)) } pub fn query_opt<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)], ) -> Result<Option<Row>, Error> where T: ?Sized + ToStatement, { self.runtime .block_on(self.transaction.query_opt(query, params)) } pub fn query_raw<'b, T, I>(&mut self, query: &T, params: I) -> Result<RowIter<'_>, Error> where T: ?Sized + ToStatement, I: IntoIterator<Item = &'b dyn ToSql>, I::IntoIter: ExactSizeIterator, { let stream = self .runtime .block_on(self.transaction.query_raw(query, params))?; Ok(RowIter::new(self.rt(), stream)) } pub fn bind<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<Portal, Error> where T: ?Sized + ToStatement, { self.runtime.block_on(self.transaction.bind(query, params)) } pub fn query_portal(&mut self, portal: &Portal, max_rows: i32) -> Result<Vec<Row>, Error> { self.runtime .block_on(self.transaction.query_portal(portal, max_rows)) } pub fn query_portal_raw( &mut self, portal: &Portal, max_rows: i32, ) -> Result<RowIter<'_>, Error> { let stream = self .runtime .block_on(self.transaction.query_portal_raw(portal, max_rows))?; Ok(RowIter::new(self.rt(), stream)) } pub fn copy_in<T>(&mut self, query: &T) -> Result<CopyInWriter<'_>, Error> where T: ?Sized + ToStatement, { let sink = self.runtime.block_on(self.transaction.copy_in(query))?; Ok(CopyInWriter::new(self.rt(), sink)) } pub fn copy_out<T>(&mut self, query: &T) -> Result<CopyOutReader<'_>, Error> where T: ?Sized + ToStatement, { let stream = self.runtime.block_on(self.transaction.copy_out(query))?; Ok(CopyOutReader::new(self.rt(), stream)) } pub fn simple_query(&mut self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> { self.runtime.block_on(self.transaction.simple_query(query)) } pub fn batch_execute(&mut self, query: &str) -> Result<(), Error> { self.runtime.block_on(self.transaction.batch_execute(query)) } pub fn cancel_token(&self) -> CancelToken { CancelToken::new(self.transaction.cancel_token()) } pub fn transaction(&mut self) -> Result<Transaction<'_>, Error> { let transaction = self.runtime.block_on(self.transaction.transaction())?; Ok(Transaction { runtime: self.runtime, transaction, }) } } impl<'a> GenericClient for Transaction<'a> { fn execute<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<u64, Error> where T: ?Sized + ToStatement, { self.execute(query, params) } fn query<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<Vec<Row>, Error> where T: ?Sized + ToStatement, { self.query(query, params) } fn prepare(&mut self, query: &str) -> Result<Statement, Error> { self.prepare(query) } fn transaction(&mut self) -> Result<Transaction<'_>, Error> { self.transaction() } }
use crate::{ CancelToken, CopyInWriter, CopyOutReader, GenericClient, Portal, RowIter, Rt, Statement, ToStatement, }; use tokio::runtime::Runtime; use tokio_postgres::types::{ToSql, Type}; use tokio_postgres::{Error, Row, SimpleQueryMessage}; pub struct Transaction<'a> { runtime: &'a mut Runtime, transaction: tokio_postgres::Transaction<'a>, } impl<'a> Transaction<'a> { pub(crate) fn new( runtime: &'a mut Runtime, transaction: tokio_postgres::Transaction<'a>, ) -> Transaction<'a> { Transaction { runtime, transaction, } } fn rt(&mut self) -> Rt<'_> { Rt(self.runtime) } pub fn commit(self) -> Result<(), Error> { self.runtime.block_on(self.transaction.commit()) } pub fn rollback(self) -> Result<(), Error> { self.runtime.block_on(self.transaction.rollback()) } pub fn prepare(&mut self, query: &str) -> Result<Statement, Error> { self.runtime.block_on(self.transaction.prepare(query)) } pub fn prepare_typed(&mut self, query: &str, types: &[Type]) -> Result<Statement, Error> { self.runtime .block_on(self.transaction.prepare_typed(query, types)) } pub fn execute<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<u64, Error> where T: ?Sized + ToStatement, { self.runtime .block_on(self.transaction.execute(query, params)) } pub fn query<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<Vec<Row>, Error> where T: ?Sized + ToStatement, { self.runtime.block_on(self.transaction.query(query, params)) } pub fn query_one<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<Row, Error> where T: ?Sized + ToStatement, { self.runtime .block_on(self.transaction.query_one(query, params)) } pub fn query_opt<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)], ) -> Result<Option<Row>, Error> where T: ?Sized + ToStatement, { self.runtime .block_on(self.transaction.query_opt(query, params)) } pub fn query_raw<'b, T, I>(&mut self, query: &T, params: I) -> Result<RowIter<'_>, Error> where T: ?Sized + ToStatement, I: IntoIterator<Item = &'b dyn ToSql>, I::IntoIter: ExactSizeIterator, { let stream = self .runtime .block_on(self.transaction.query_raw(query, params))?; Ok(RowIter::new(self.rt(), stream)) } pub fn bind<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<Portal, Error> where T: ?Sized + ToStatement, { self.runtime.block_on(self.transaction.bind(query, params)) } pub fn query_portal(&mut self, portal: &Portal, max_rows: i32) -> Result<Vec<Row>, Error> { self.runtime .block_on(self.transaction.query_portal(portal, max_rows)) } pub fn query_portal_raw( &mut self, portal: &Portal, max_rows: i32, ) -> Result<RowIter<'_>, Error> { let stream = self .runtime .block_on(self.transaction.query_portal_raw(portal, max_rows))?; Ok(RowIter::new(self.rt(), stream)) } pub fn copy_in<T>(&mut self, query: &T) -> Result<CopyInWriter<'_>, Error> where T: ?Sized + ToStatement, { let sink = self.runtime.block_on(self.transaction.copy_in(query))?; Ok(CopyInWriter::new(self.rt(), sink)) } pub fn copy_out<T>(&mut self, query: &T) -> Result<CopyOutReader<'_>, Error> where T: ?Sized + ToStatement, { let stream = self.runtime.block_on(self.transaction.copy_out(query))?; Ok(CopyOutReader::new(self.rt(), stream)) } pub fn simple_query(&mut self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> { self.runtime.block_on(self.transaction.simple_query(query)) } pub fn batch_execute(&mut self, query: &str) -> Result<(), Error> { self.runtime.block_on(self.transaction.batch_execute(query)) } pub fn cancel_token(&self) -> CancelToken { CancelToken::new(self.transaction.cancel_token()) } pub fn transaction(&mut self) -> Result<Transaction<'_>, Error> { let transaction = self.runtime.block_on(self.transactio
s) } fn query<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<Vec<Row>, Error> where T: ?Sized + ToStatement, { self.query(query, params) } fn prepare(&mut self, query: &str) -> Result<Statement, Error> { self.prepare(query) } fn transaction(&mut self) -> Result<Transaction<'_>, Error> { self.transaction() } }
n.transaction())?; Ok(Transaction { runtime: self.runtime, transaction, }) } } impl<'a> GenericClient for Transaction<'a> { fn execute<T>(&mut self, query: &T, params: &[&(dyn ToSql + Sync)]) -> Result<u64, Error> where T: ?Sized + ToStatement, { self.execute(query, param
random
[ { "content": "pub fn read_be_i32(buf: &mut &[u8]) -> Result<i32, Box<dyn Error + Sync + Send>> {\n\n if buf.len() < 4 {\n\n return Err(\"invalid buffer size\".into());\n\n }\n\n let mut bytes = [0; 4];\n\n bytes.copy_from_slice(&buf[..4]);\n\n *buf = &buf[4..];\n\n Ok(i32::from_be_bytes...
Rust
termwiz/src/widgets/mod.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
#![allow(clippy::new_without_default)] use crate::color::ColorAttribute; use crate::input::InputEvent; use crate::surface::{Change, CursorShape, Position, SequenceNo, Surface}; use anyhow::Error; use fnv::FnvHasher; use std::collections::{HashMap, VecDeque}; use std::hash::BuildHasherDefault; type FnvHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FnvHasher>>; pub mod layout; pub enum WidgetEvent { Input(InputEvent), } #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct CursorShapeAndPosition { pub shape: CursorShape, pub coords: ParentRelativeCoords, pub color: ColorAttribute, } #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Rect { pub x: usize, pub y: usize, pub width: usize, pub height: usize, } pub struct RenderArgs<'a> { pub id: WidgetId, pub is_focused: bool, pub cursor: &'a mut CursorShapeAndPosition, pub surface: &'a mut Surface, } pub struct UpdateArgs<'a> { pub id: WidgetId, pub cursor: &'a mut CursorShapeAndPosition, } pub trait Widget { fn render(&mut self, args: &mut RenderArgs); fn get_size_constraints(&self) -> layout::Constraints { Default::default() } fn process_event(&mut self, _event: &WidgetEvent, _args: &mut UpdateArgs) -> bool { false } } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ParentRelativeCoords { pub x: usize, pub y: usize, } impl ParentRelativeCoords { pub fn new(x: usize, y: usize) -> Self { Self { x, y } } } impl From<(usize, usize)> for ParentRelativeCoords { fn from(coords: (usize, usize)) -> ParentRelativeCoords { ParentRelativeCoords::new(coords.0, coords.1) } } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ScreenRelativeCoords { pub x: usize, pub y: usize, } impl ScreenRelativeCoords { pub fn new(x: usize, y: usize) -> Self { Self { x, y } } pub fn offset_by(&self, rel: &ParentRelativeCoords) -> Self { Self { x: self.x + rel.x, y: self.y + rel.y, } } } static WIDGET_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicUsize::new(0); #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct WidgetId(usize); impl WidgetId { pub fn new() -> Self { WidgetId(WIDGET_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)) } } impl Default for WidgetId { fn default() -> Self { Self::new() } } struct RenderData<'widget> { surface: Surface, cursor: CursorShapeAndPosition, coordinates: ParentRelativeCoords, widget: Box<dyn Widget + 'widget>, } #[derive(Default)] struct Graph { root: Option<WidgetId>, children: FnvHashMap<WidgetId, Vec<WidgetId>>, parent: FnvHashMap<WidgetId, WidgetId>, } impl Graph { fn add(&mut self, parent: Option<WidgetId>) -> WidgetId { let id = WidgetId::new(); if self.root.is_none() { self.root = Some(id); } self.children.insert(id, Vec::new()); if let Some(parent) = parent { self.parent.insert(id, parent); self.children.get_mut(&parent).unwrap().push(id); } id } fn children(&self, id: WidgetId) -> &[WidgetId] { self.children .get(&id) .map(|v| v.as_slice()) .unwrap_or_else(|| &[]) } } #[derive(Default)] pub struct Ui<'widget> { graph: Graph, render: FnvHashMap<WidgetId, RenderData<'widget>>, input_queue: VecDeque<WidgetEvent>, focused: Option<WidgetId>, } impl<'widget> Ui<'widget> { pub fn new() -> Self { Default::default() } pub fn add<W: Widget + 'widget>(&mut self, parent: Option<WidgetId>, w: W) -> WidgetId { let id = self.graph.add(parent); self.render.insert( id, RenderData { surface: Surface::new(1, 1), cursor: Default::default(), coordinates: Default::default(), widget: Box::new(w), }, ); if parent.is_none() && self.focused.is_none() { self.focused = Some(id); } id } pub fn set_root<W: Widget + 'widget>(&mut self, w: W) -> WidgetId { self.add(None, w) } pub fn add_child<W: Widget + 'widget>(&mut self, parent: WidgetId, w: W) -> WidgetId { self.add(Some(parent), w) } fn do_deliver(&mut self, id: WidgetId, event: &WidgetEvent) -> bool { let render_data = self.render.get_mut(&id).unwrap(); let mut args = UpdateArgs { id, cursor: &mut render_data.cursor, }; render_data.widget.process_event(event, &mut args) } fn deliver_event(&mut self, mut id: WidgetId, event: &WidgetEvent) { loop { let handled = match event { WidgetEvent::Input(InputEvent::Resized { .. }) => true, WidgetEvent::Input(InputEvent::Mouse(m)) => { let mut m = m.clone(); let coords = self.to_widget_coords( id, &ScreenRelativeCoords::new(m.x as usize, m.y as usize), ); m.x = coords.x as u16; m.y = coords.y as u16; self.do_deliver(id, &WidgetEvent::Input(InputEvent::Mouse(m))) } WidgetEvent::Input(InputEvent::Paste(_)) | WidgetEvent::Input(InputEvent::Key(_)) | WidgetEvent::Input(InputEvent::Wake) => self.do_deliver(id, event), }; if handled { return; } id = match self.graph.parent.get(&id) { Some(parent) => *parent, None => return, }; } } fn hovered_widget(&self, coords: &ScreenRelativeCoords) -> Option<WidgetId> { let root = match self.graph.root { Some(id) => id, _ => return None, }; let depth = 0; let mut best = (depth, root); self.hovered_recursive(root, depth, coords.x, coords.y, &mut best); Some(best.1) } fn hovered_recursive( &self, widget: WidgetId, depth: usize, x: usize, y: usize, best: &mut (usize, WidgetId), ) { let render = &self.render[&widget]; if depth >= best.0 && x >= render.coordinates.x && y >= render.coordinates.y { let (width, height) = render.surface.dimensions(); if (x - render.coordinates.x < width) && (y - render.coordinates.y < height) { *best = (depth, widget); } } for child in self.graph.children(widget) { self.hovered_recursive( *child, depth + 1, x + render.coordinates.x, y + render.coordinates.y, best, ); } } pub fn process_event_queue(&mut self) -> Result<(), Error> { while let Some(event) = self.input_queue.pop_front() { match event { WidgetEvent::Input(InputEvent::Resized { rows, cols }) => { self.compute_layout(cols, rows)?; } WidgetEvent::Input(InputEvent::Mouse(ref m)) => { if let Some(hover) = self.hovered_widget(&ScreenRelativeCoords::new(m.x as usize, m.y as usize)) { self.deliver_event(hover, &event); } } WidgetEvent::Input(InputEvent::Key(_)) | WidgetEvent::Input(InputEvent::Paste(_)) | WidgetEvent::Input(InputEvent::Wake) => { if let Some(focus) = self.focused { self.deliver_event(focus, &event); } } } } Ok(()) } pub fn queue_event(&mut self, event: WidgetEvent) { self.input_queue.push_back(event); } pub fn set_focus(&mut self, id: WidgetId) { self.focused = Some(id); } fn render_recursive( &mut self, id: WidgetId, screen: &mut Surface, abs_coords: &ScreenRelativeCoords, ) -> Result<(), Error> { let (x, y) = { let render_data = self.render.get_mut(&id).unwrap(); let surface = &mut render_data.surface; { let mut args = RenderArgs { id, cursor: &mut render_data.cursor, surface, is_focused: self.focused.map(|f| f == id).unwrap_or(false), }; render_data.widget.render(&mut args); } screen.draw_from_screen(surface, abs_coords.x, abs_coords.y); surface.flush_changes_older_than(SequenceNo::max_value()); (render_data.coordinates.x, render_data.coordinates.y) }; for child in self.graph.children(id).to_vec() { self.render_recursive( child, screen, &ScreenRelativeCoords::new(x + abs_coords.x, y + abs_coords.y), )?; } Ok(()) } fn compute_layout(&mut self, width: usize, height: usize) -> Result<bool, Error> { let mut layout = layout::LayoutState::new(); let root = self.graph.root.unwrap(); self.add_widget_to_layout(&mut layout, root)?; let mut changed = false; #[cfg_attr(feature = "cargo-clippy", allow(clippy::identity_conversion))] for result in layout.compute_constraints(width, height, root)? { let render_data = self.render.get_mut(&result.widget).unwrap(); let coords = ParentRelativeCoords::new(result.rect.x, result.rect.y); if coords != render_data.coordinates { render_data.coordinates = coords; changed = true; } if (result.rect.width, result.rect.height) != render_data.surface.dimensions() { render_data .surface .resize(result.rect.width, result.rect.height); changed = true; } } Ok(changed) } fn add_widget_to_layout( &mut self, layout: &mut layout::LayoutState, widget: WidgetId, ) -> Result<(), Error> { let constraints = self.render[&widget].widget.get_size_constraints(); let children = self.graph.children(widget).to_vec(); layout.add_widget(widget, &constraints, &children); for child in children { self.add_widget_to_layout(layout, child)?; } Ok(()) } pub fn render_to_screen(&mut self, screen: &mut Surface) -> Result<bool, Error> { if let Some(root) = self.graph.root { self.render_recursive(root, screen, &ScreenRelativeCoords::new(0, 0))?; } if let Some(id) = self.focused { let cursor = &self.render[&id].cursor; let coords = self.to_screen_coords(id, &cursor.coords); screen.add_changes(vec![ Change::CursorShape(cursor.shape), Change::CursorColor(cursor.color), Change::CursorPosition { x: Position::Absolute(coords.x), y: Position::Absolute(coords.y), }, ]); } let (width, height) = screen.dimensions(); self.compute_layout(width, height) } fn coord_walk<F: Fn(usize, usize) -> usize>( &self, widget: WidgetId, mut x: usize, mut y: usize, f: F, ) -> (usize, usize) { let mut widget = widget; loop { let render = &self.render[&widget]; x = f(x, render.coordinates.x); y = f(y, render.coordinates.y); widget = match self.graph.parent.get(&widget) { Some(parent) => *parent, None => break, }; } (x, y) } pub fn to_screen_coords( &self, widget: WidgetId, coords: &ParentRelativeCoords, ) -> ScreenRelativeCoords { let (x, y) = self.coord_walk(widget, coords.x, coords.y, |a, b| a + b); ScreenRelativeCoords { x, y } } pub fn to_widget_coords( &self, widget: WidgetId, coords: &ScreenRelativeCoords, ) -> ParentRelativeCoords { let (x, y) = self.coord_walk(widget, coords.x, coords.y, |a, b| a - b); ParentRelativeCoords { x, y } } }
#![allow(clippy::new_without_default)] use crate::color::ColorAttribute; use crate::input::InputEvent; use crate::surface::{Change, CursorShape, Position, SequenceNo, Surface}; use anyhow::Error; use fnv::FnvHasher; use std::collections::{HashMap, VecDeque}; use std::hash::BuildHasherDefault; type FnvHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FnvHasher>>; pub mod layout; pub enum WidgetEvent { Input(InputEvent), } #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct CursorShapeAndPosition { pub shape: CursorShape, pub coords: ParentRelativeCoords, pub color: ColorAttribute, } #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Rect { pub x: usize, pub y: usize, pub width: usize, pub height: usize, } pub struct RenderArgs<'a> { pub id: WidgetId, pub is_focused: bool, pub cursor: &'a mut CursorShapeAndPosition, pub surface: &'a mut Surface, } pub struct UpdateArgs<'a> { pub id: WidgetId, pub cursor: &'a mut CursorShapeAndPosition, } pub trait Widget { fn render(&mut self, args: &mut RenderArgs); fn get_size_constraints(&self) -> layout::Constraints { Default::default() } fn process_event(&mut self, _event: &WidgetEvent, _args: &mut UpdateArgs) -> bool { false } } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ParentRelativeCoords { pub x: usize, pub y: usize, } impl ParentRelativeCoords { pub fn new(x: usize, y: usize) -> Self { Self { x, y } } } impl From<(usize, usize)> for ParentRelativeCoords { fn from(coords: (usize, usize)) -> ParentRelativeCoords { ParentRelativeCoords::new(coords.0, coords.1) } } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ScreenRelativeCoords { pub x: usize, pub y: usize, } impl ScreenRelativeCoords { pub fn new(x: usize, y: usize) -> Self { Self { x, y } } pub fn offset_by(&self, rel: &ParentRelativeCoords) -> Self { Self { x: self.x + rel.x, y: self.y + rel.y, } } } static WIDGET_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicUsize::new(0); #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct WidgetId(usize); impl WidgetId { pub fn new() -> Self { WidgetId(WIDGET_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)) } } impl Default for WidgetId { fn default() -> Self { Self::new() } } struct RenderData<'widget> { surface: Surface, cursor: CursorShapeAndPosition, coordinates: ParentRelativeCoords, widget: Box<dyn Widget + 'widget>, } #[derive(Default)] struct Graph { root: Option<WidgetId>, children: FnvHashMap<WidgetId, Vec<WidgetId>>, parent: FnvHashMap<WidgetId, WidgetId>, } impl Graph { fn add(&mut self, parent: Option<WidgetId>) -> WidgetId { let id = WidgetId::new(); if self.root.is_none() { self.root = Some(id); } self.children.insert(id, Vec::new()); if let Some(parent) = parent { self.parent.insert(id, parent); self.children.get_mut(&parent).unwrap().push(id); } id } fn children(&self, id: WidgetId) -> &[WidgetId] { self.children .get(&id) .map(|v| v.as_slice()) .unwrap_or_else(|| &[]) } } #[derive(Default)] pub struct Ui<'widget> { graph: Graph, render: FnvHashMap<WidgetId, RenderData<'widget>>, input_queue: VecDeque<WidgetEvent>, focused: Option<WidgetId>, } impl<'widget> Ui<'widget> { pub fn new() -> Self { Default::default() } pub fn add<W: Widget + 'widget>(&mut self, parent: Option<WidgetId>, w: W) -> WidgetId { let id = self.graph.add(parent); self.render.insert( id, RenderData { surface: Surface::new(1, 1), cursor: Default::default(), coordinates: Default::default(), widget: Box::new(w), }, ); if parent.is_none() && self.focused.is_none() { self.focused = Some(id); } id } pub fn set_root<W: Widget + 'widget>(&mut self, w: W) -> WidgetId { self.add(None, w) } pub fn add_child<W: Widget + 'widget>(&mut self, parent: WidgetId, w: W) -> WidgetId { self.add(Some(parent), w) } fn do_deliver(&mut self, id: WidgetId, event: &WidgetEvent) -> bool { let render_data = self.render.get_mut(&id).unwrap(); let mut args = UpdateArgs { id, cursor: &mut render_data.cursor, }; render_data.widget.process_event(event, &mut args) } fn deliver_event(&mut self, mut id: WidgetId, event: &WidgetEvent) { loop { let handled = match event { WidgetEvent::Input(InputEvent::Resized { .. }) => true, WidgetEvent::Input(InputEvent::Mouse(m)) => { let mut m = m.clone(); let coords = self.to_widget_coords( id, &ScreenRelativeCoords::new(m.x as usize, m.y as usize), ); m.x = coords.x as u16; m.y = coords.y as u16; self.do_deliver(id, &WidgetEvent::Input(InputEvent::Mouse(m))) } WidgetEvent::Input(InputEvent::Paste(_)) | WidgetEvent::Input(InputEvent::Key(_)) | WidgetEvent::Input(InputEvent::Wake) => self.do_deliver(id, event), }; if handled { return; } id = match self.graph.parent.get(&id) { Some(parent) => *parent, None => return, }; } } fn hovered_widget(&self, coords: &ScreenRelativeCoords) -> Option<WidgetId> {
fn hovered_recursive( &self, widget: WidgetId, depth: usize, x: usize, y: usize, best: &mut (usize, WidgetId), ) { let render = &self.render[&widget]; if depth >= best.0 && x >= render.coordinates.x && y >= render.coordinates.y { let (width, height) = render.surface.dimensions(); if (x - render.coordinates.x < width) && (y - render.coordinates.y < height) { *best = (depth, widget); } } for child in self.graph.children(widget) { self.hovered_recursive( *child, depth + 1, x + render.coordinates.x, y + render.coordinates.y, best, ); } } pub fn process_event_queue(&mut self) -> Result<(), Error> { while let Some(event) = self.input_queue.pop_front() { match event { WidgetEvent::Input(InputEvent::Resized { rows, cols }) => { self.compute_layout(cols, rows)?; } WidgetEvent::Input(InputEvent::Mouse(ref m)) => { if let Some(hover) = self.hovered_widget(&ScreenRelativeCoords::new(m.x as usize, m.y as usize)) { self.deliver_event(hover, &event); } } WidgetEvent::Input(InputEvent::Key(_)) | WidgetEvent::Input(InputEvent::Paste(_)) | WidgetEvent::Input(InputEvent::Wake) => { if let Some(focus) = self.focused { self.deliver_event(focus, &event); } } } } Ok(()) } pub fn queue_event(&mut self, event: WidgetEvent) { self.input_queue.push_back(event); } pub fn set_focus(&mut self, id: WidgetId) { self.focused = Some(id); } fn render_recursive( &mut self, id: WidgetId, screen: &mut Surface, abs_coords: &ScreenRelativeCoords, ) -> Result<(), Error> { let (x, y) = { let render_data = self.render.get_mut(&id).unwrap(); let surface = &mut render_data.surface; { let mut args = RenderArgs { id, cursor: &mut render_data.cursor, surface, is_focused: self.focused.map(|f| f == id).unwrap_or(false), }; render_data.widget.render(&mut args); } screen.draw_from_screen(surface, abs_coords.x, abs_coords.y); surface.flush_changes_older_than(SequenceNo::max_value()); (render_data.coordinates.x, render_data.coordinates.y) }; for child in self.graph.children(id).to_vec() { self.render_recursive( child, screen, &ScreenRelativeCoords::new(x + abs_coords.x, y + abs_coords.y), )?; } Ok(()) } fn compute_layout(&mut self, width: usize, height: usize) -> Result<bool, Error> { let mut layout = layout::LayoutState::new(); let root = self.graph.root.unwrap(); self.add_widget_to_layout(&mut layout, root)?; let mut changed = false; #[cfg_attr(feature = "cargo-clippy", allow(clippy::identity_conversion))] for result in layout.compute_constraints(width, height, root)? { let render_data = self.render.get_mut(&result.widget).unwrap(); let coords = ParentRelativeCoords::new(result.rect.x, result.rect.y); if coords != render_data.coordinates { render_data.coordinates = coords; changed = true; } if (result.rect.width, result.rect.height) != render_data.surface.dimensions() { render_data .surface .resize(result.rect.width, result.rect.height); changed = true; } } Ok(changed) } fn add_widget_to_layout( &mut self, layout: &mut layout::LayoutState, widget: WidgetId, ) -> Result<(), Error> { let constraints = self.render[&widget].widget.get_size_constraints(); let children = self.graph.children(widget).to_vec(); layout.add_widget(widget, &constraints, &children); for child in children { self.add_widget_to_layout(layout, child)?; } Ok(()) } pub fn render_to_screen(&mut self, screen: &mut Surface) -> Result<bool, Error> { if let Some(root) = self.graph.root { self.render_recursive(root, screen, &ScreenRelativeCoords::new(0, 0))?; } if let Some(id) = self.focused { let cursor = &self.render[&id].cursor; let coords = self.to_screen_coords(id, &cursor.coords); screen.add_changes(vec![ Change::CursorShape(cursor.shape), Change::CursorColor(cursor.color), Change::CursorPosition { x: Position::Absolute(coords.x), y: Position::Absolute(coords.y), }, ]); } let (width, height) = screen.dimensions(); self.compute_layout(width, height) } fn coord_walk<F: Fn(usize, usize) -> usize>( &self, widget: WidgetId, mut x: usize, mut y: usize, f: F, ) -> (usize, usize) { let mut widget = widget; loop { let render = &self.render[&widget]; x = f(x, render.coordinates.x); y = f(y, render.coordinates.y); widget = match self.graph.parent.get(&widget) { Some(parent) => *parent, None => break, }; } (x, y) } pub fn to_screen_coords( &self, widget: WidgetId, coords: &ParentRelativeCoords, ) -> ScreenRelativeCoords { let (x, y) = self.coord_walk(widget, coords.x, coords.y, |a, b| a + b); ScreenRelativeCoords { x, y } } pub fn to_widget_coords( &self, widget: WidgetId, coords: &ScreenRelativeCoords, ) -> ParentRelativeCoords { let (x, y) = self.coord_walk(widget, coords.x, coords.y, |a, b| a - b); ParentRelativeCoords { x, y } } }
let root = match self.graph.root { Some(id) => id, _ => return None, }; let depth = 0; let mut best = (depth, root); self.hovered_recursive(root, depth, coords.x, coords.y, &mut best); Some(best.1) }
function_block-function_prefix_line
[]
Rust
arci-ros/src/ros_localization_client.rs
OpenRR/OpenRR
bfafe3707164cf8ca1143b5daa039f60b1831fdb
use std::borrow::Borrow; use arci::*; use nalgebra as na; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{msg, rosrust_utils::*}; rosrust::rosmsg_include! { std_srvs / Empty } const AMCL_POSE_TOPIC: &str = "/amcl_pose"; const NO_MOTION_UPDATE_SERVICE: &str = "request_nomotion_update"; #[derive(Debug, Serialize, Deserialize, Clone, JsonSchema)] #[serde(deny_unknown_fields)] pub struct RosLocalizationClientConfig { pub request_final_nomotion_update_hack: bool, #[serde(default = "default_nomotion_update_service_name")] pub nomotion_update_service_name: String, #[serde(default = "default_amcl_pose_topic_name")] pub amcl_pose_topic_name: String, } #[derive(Clone, Debug)] pub struct RosLocalizationClientBuilder { amcl_pose_topic_name: String, nomotion_update_service_name: String, request_final_nomotion_update_hack: bool, } impl RosLocalizationClientBuilder { pub fn new() -> Self { Self { amcl_pose_topic_name: AMCL_POSE_TOPIC.to_string(), nomotion_update_service_name: NO_MOTION_UPDATE_SERVICE.to_string(), request_final_nomotion_update_hack: false, } } pub fn request_final_nomotion_update_hack(mut self, val: bool) -> Self { self.request_final_nomotion_update_hack = val; self } pub fn finalize(self) -> RosLocalizationClient { RosLocalizationClient::new( self.request_final_nomotion_update_hack, self.nomotion_update_service_name, self.amcl_pose_topic_name, ) } } impl Default for RosLocalizationClientBuilder { fn default() -> Self { Self::new() } } pub struct RosLocalizationClient { pose_subscriber: SubscriberHandler<msg::geometry_msgs::PoseWithCovarianceStamped>, nomotion_update_client: Option<rosrust::Client<msg::std_srvs::Empty>>, amcl_pose_topic_name: String, } impl RosLocalizationClient { pub fn new( request_final_nomotion_update_hack: bool, nomotion_update_service_name: String, amcl_pose_topic_name: String, ) -> Self { let pose_subscriber = SubscriberHandler::new(&amcl_pose_topic_name, 1); let nomotion_update_client = if request_final_nomotion_update_hack { rosrust::wait_for_service( &nomotion_update_service_name, Some(std::time::Duration::from_secs(10)), ) .unwrap(); Some(rosrust::client::<msg::std_srvs::Empty>(&nomotion_update_service_name).unwrap()) } else { None }; Self { pose_subscriber, nomotion_update_client, amcl_pose_topic_name, } } pub fn new_from_config(config: RosLocalizationClientConfig) -> Self { Self::new( config.request_final_nomotion_update_hack, config.nomotion_update_service_name, config.amcl_pose_topic_name, ) } pub fn request_nomotion_update(&self) { self.nomotion_update_client .borrow() .as_ref() .unwrap() .req(&msg::std_srvs::EmptyReq {}) .unwrap() .unwrap(); } } impl Localization for RosLocalizationClient { fn current_pose(&self, _frame_id: &str) -> Result<na::Isometry2<f64>, Error> { self.pose_subscriber.wait_message(100); let pose_with_cov_stamped = self.pose_subscriber .get()? .ok_or_else(|| Error::Connection { message: format!("Failed to get pose from {}", self.amcl_pose_topic_name), })?; let pose: na::Isometry3<f64> = pose_with_cov_stamped.pose.pose.into(); Ok(na::Isometry2::new( na::Vector2::new(pose.translation.vector[0], pose.translation.vector[1]), pose.rotation.euler_angles().2, )) } } fn default_nomotion_update_service_name() -> String { NO_MOTION_UPDATE_SERVICE.to_string() } fn default_amcl_pose_topic_name() -> String { AMCL_POSE_TOPIC.to_string() }
use std::borrow::Borrow; use arci::*; use nalgebra as na; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{msg, rosrust_utils::*}; rosrust::rosmsg_include! { std_srvs / Empty } const AMCL_POSE_TOPIC: &str = "/amcl_pose"; const NO_MOTION_UPDATE_SERVICE: &str = "request_nomotion_update"; #[derive(Debug, Serialize, Deserialize, Clone, JsonSchema)] #[serde(deny_unknown_fields)] pub struct RosLocalizationClientConfig { pub request_final_nomotion_update_hack: bool, #[serde(default = "default_nomotion_update_service_name")] pub nomotion_update_service_name: String, #[serde(default = "default_amcl_pose_topic_name")] pub amcl_pose_topic_name: String, } #[derive(Clone, Debug)] pub struct RosLocalizationClientBuilder { amcl_pose_topic_name: String, nomotion_update_service_name: String, request_final_nomotion_update_hack: bool, } impl RosLocalizationClientBuilder { pub fn new() -> Self { Self { amcl_pose_topic_name: AMCL_POSE_TOPIC.to_string(), nomotion_update_service_name: NO_MOTION_UPDATE_SERVICE.to_string(), request_final_nomotion_update_hack: false, } } pub fn request_final_nomotion_update_hack(mut self, val: bool) -> Self { self.request_final_nomotion_update_hack = val; self } pub fn finalize(self) -> RosLocalizationClient { RosLocalizationClient::new( self.request_final_nomotion_update_hack, self.nomotion_update_service_name, self.amcl_pose_topic_name, ) } } impl Default for RosLocalizationClientBuilder { fn default() -> Self { Self::new() } } pub struct RosLocalizationClient { pose_subscriber: SubscriberHandler<msg::geometry_msgs::PoseWithCovarianceStamped>, nomotion_update_client: Option<rosrust::Client<msg::std_srvs::Empty>>, amcl_pose_topic_name: String, } impl RosLocalizationClient { pub fn new( request_final_nomotion_update_hack: bool, nomotion_update_service_name: String, amcl_pose_topic_name: String, ) -> Self { let pose_subscriber = SubscriberHandler::new(&amcl_pose_topic_name, 1); let nomotion_update_client = if request_final_nomotion_update_hack { rosrust::wait_for_service( &nomotion_update_service_name, Some(std::time::Duration::from_secs(10)), ) .unwrap(); Some(rosrust::client::<msg::std_srvs::Empty>(&nomotion_update_service_name).unwrap()) } else { None }; Self { pose_subscriber, nomotion_update_client, amcl_pose_topic_name, } } pub fn new_from_config(config: RosLocalizationClientConfig) -> Self { Self::new( config.request_final_nomotion_update_hack, config.nomotion_update_service_name, config.amcl_pose_topic_name, ) } pub fn request_nomotion_update(&self) { self.nomotion_update_client .borrow() .as_ref() .unwrap() .req(&msg::std_srvs::EmptyReq {}) .unwrap() .unwrap(); } } impl Localization for RosLocalizationClient {
} fn default_nomotion_update_service_name() -> String { NO_MOTION_UPDATE_SERVICE.to_string() } fn default_amcl_pose_topic_name() -> String { AMCL_POSE_TOPIC.to_string() }
fn current_pose(&self, _frame_id: &str) -> Result<na::Isometry2<f64>, Error> { self.pose_subscriber.wait_message(100); let pose_with_cov_stamped = self.pose_subscriber .get()? .ok_or_else(|| Error::Connection { message: format!("Failed to get pose from {}", self.amcl_pose_topic_name), })?; let pose: na::Isometry3<f64> = pose_with_cov_stamped.pose.pose.into(); Ok(na::Isometry2::new( na::Vector2::new(pose.translation.vector[0], pose.translation.vector[1]), pose.rotation.euler_angles().2, )) }
function_block-function_prefix_line
[ { "content": "/// Replaces the contents of the specified TOML document based on the specified scripts,\n\n/// returning edited document as string.\n\n///\n\n/// See [`overwrite`] for more.\n\npub fn overwrite_str(doc: &str, scripts: &str) -> Result<String> {\n\n let mut doc: toml::Value = toml::from_str(doc)...
Rust
src/build/windows.rs
kungfoo/boon
788d1265e9e6edd822cf651e5b3be8f2d12483c8
#![allow(clippy::too_many_lines)] use crate::build::{Iterator, collect_zip_directory, get_love_file_name, get_love_version_path, get_output_filename, get_zip_output_filename}; use crate::types::{Bitness, BuildSettings, BuildStatistics, LoveVersion, Platform, Project}; use glob::glob; use remove_dir_all::remove_dir_all; use anyhow::{anyhow, ensure, Context, Result}; use std::collections::HashSet; use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; pub fn create_exe( project: &Project, build_settings: &BuildSettings, version: LoveVersion, bitness: Bitness, ) -> Result<BuildStatistics> { let start = std::time::Instant::now(); let app_dir_path = get_love_version_path(version, Platform::Windows, bitness)?; let mut app_dir_path_clone = PathBuf::new(); app_dir_path_clone.clone_from(&app_dir_path); let mut love_exe_path = app_dir_path; love_exe_path.push("love.exe"); ensure!(love_exe_path.exists(), format!("love.exe not found at '{}'\nhint: You may need to download LÖVE first: `boon love download {}`", love_exe_path.display(), version.to_string())); let exe_file_name = get_output_filename(project, Platform::Windows, bitness); let zip_output_file_name = &get_zip_output_filename(project, Platform::Windows, bitness); let mut output_path = project.get_release_path(build_settings); output_path.push(zip_output_file_name); if output_path.exists() { println!("Removing existing directory {}", output_path.display()); std::fs::remove_dir_all(&output_path).with_context(|| { format!( "Could not remove output directory '{}'", output_path.display() ) })?; } std::fs::create_dir(&output_path).with_context(|| { format!( "Could not create build directory '{}'", output_path.display() ) })?; output_path.push(exe_file_name); println!("Copying love from {}", love_exe_path.display()); println!("Outputting exe to {}", output_path.display()); let mut output_file = File::create(&output_path) .with_context(|| format!("Could not create output file '{}'", output_path.display()))?; let love_file_name = get_love_file_name(project); let mut local_love_file_path = project.get_release_path(build_settings); local_love_file_path.push(love_file_name); println!( "Copying project .love from {}", local_love_file_path.display() ); let mut copy_options = fs_extra::file::CopyOptions::new(); copy_options.overwrite = true; let dll_glob = glob( app_dir_path_clone .join("*.dll") .to_str() .context("Could not convert string")?, )?; let txt_glob = glob( app_dir_path_clone .join("*.txt") .to_str() .context("Could not convert string")?, )?; let ico_glob = glob( app_dir_path_clone .join("*.ico") .to_str() .context("Could not convert string")?, )?; for entry in dll_glob.chain(txt_glob).chain(ico_glob) { match entry { Ok(path) => { let local_file_name = path .file_name() .with_context(|| { format!("Could not get file name from path '{}'", path.display()) })? .to_str() .context("Could not do string conversion")?; fs_extra::file::copy( &path, &project .get_release_path(build_settings) .join(zip_output_file_name) .join(local_file_name), &copy_options, )?; } Err(e) => { return Err(anyhow!( "Path matched for '{}' but file was unreadable: {}", e.path().display(), e.error() )) } } } let paths = &[love_exe_path.as_path(), local_love_file_path.as_path()]; let mut buffer = Vec::new(); for path in paths { if path.is_file() { let mut file = File::open(path)?; file.read_to_end(&mut buffer)?; output_file.write_all(&buffer)?; buffer.clear(); } } let zip_output_file_name = get_zip_output_filename(project, Platform::Windows, bitness); let output_path = project .get_release_path(build_settings) .join(zip_output_file_name); let src_dir = output_path.clone(); let src_dir = src_dir.to_str().context("Could not do string conversion")?; let mut dst_file_path = output_path; dst_file_path.set_extension("zip"); let dst_file = dst_file_path .to_str() .context("Could not do string conversion")?; collect_zip_directory( src_dir, dst_file, zip::CompressionMethod::Deflated, &HashSet::new(), ) .with_context(|| { format!( "Error while zipping files from `{}` to `{}`", src_dir, dst_file ) })??; let path = PathBuf::new().join(src_dir); println!("Removing {}", path.display()); remove_dir_all(&path)?; let build_metadata = std::fs::metadata(dst_file) .with_context(|| format!("Failed to read file metadata for '{}'", dst_file))?; Ok(BuildStatistics { name: format!("Windows {}", bitness.to_string()), file_name: dst_file_path .file_name() .unwrap() .to_str() .unwrap() .to_string(), time: start.elapsed(), size: build_metadata.len(), }) }
#![allow(clippy::too_many_lines)] use crate::build::{Iterator, collect_zip_directory, get_love_file_name, get_love_version_path, get_output_filename, get_zip_output_filename}; use crate::types::{Bitness, BuildSettings, BuildStatistics, LoveVersion, Platform, Project}; use glob::glob; use remove_dir_all::remove_dir_all; use anyhow::{anyhow, ensure, Context, Result}; use std::collections::HashSet; use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; pub fn create_exe( project: &Project, build_settings: &BuildSettings, version: LoveVersion, bitness: Bitness, ) -> Result<BuildStatistics> { let start = std::time::Instant::now(); let app_dir_path = get_love_version_path(version, Platform::Windows, bitness)?; let mut app_dir_path_clone = PathBuf::new(); app_dir_path_clone.clone_from(&app_dir_path); let mut love_exe_path = app_dir_path; love_exe_path.push("love.exe"); ensure!(love_exe_path.exists(), format!("love.exe not found at '{}'\nhint: You may need to download LÖVE first: `boon love download {}`", love_exe_path.display(), version.to_string())); let exe_file_name = get_output_filename(project, Platform::Windows, bitness); let zip_output_file_name = &get_zip_output_filename(project, Platform::Windows, bitness); let mut output_path = project.get_release_path(build_settings); output_path.push(zip_output_file_name); if output_path.exists() { println!("Removing existing directory {}", output_path.display()); std::fs::remove_dir_all(&output_path).with_context(|| { format!( "Could not remove output directory '{}'", output_path.display() ) })?; } std::fs::create_dir(&output_path).with_context(|| { format!( "Could not create build directory '{}'", output_path.display() ) })?; output_path.push(exe_file_name); println!("Copying love from {}", love_exe_path.display()); println!("Outputting exe to {}", output_path.display()); let mut output_file = File::create(&output_path) .with_context(|| format!("Could not create output file '{}'", output_path.display()))?; let love_file_name = get_love_file_name(project); let mut local_love_file_path = project.get_release_path(build_settings); local_love_file_path.push(love_file_name); println!( "Copying project .love from {}", local_love_file_path.display() ); let mut copy_options = fs_extra::file::CopyOptions::new(); copy_options.overwrite = true; let dll_glob = glob( app_dir_path_clone .join("*.dll") .to_str() .context("Could not convert string")?, )?; let txt_glob = glob( app_dir_path_clone .join("*.txt") .to_str() .context("Could not convert string")?, )?; let ico_glob = glob( app_dir_path_clone .join("*.ico") .to_str() .context("Could not convert string")?, )?; for entry in dll_glob.chain(txt_glob).chain(ico_glob) { match entry { Ok(path) => { let local_file_name = path .file_name() .with_context(|| { format!("Could not get file name from path '{}'", path.display()) })? .to_str() .context("Could not do string conversion")?; fs_extra::file::copy( &path, &project .get_release_path(build_settings) .join(zip_output_file_name) .join(local_file_name), &copy_options, )?; } Err(e) => { return Err(anyhow!( "Path matched for '{}' but file was unreadable: {}", e.path().display(), e.error() )) } } } let paths = &[love_exe_path.as_path(), local_love_file_path.as_path()]; let mut buffer = Vec::new(); for path in paths {
} let zip_output_file_name = get_zip_output_filename(project, Platform::Windows, bitness); let output_path = project .get_release_path(build_settings) .join(zip_output_file_name); let src_dir = output_path.clone(); let src_dir = src_dir.to_str().context("Could not do string conversion")?; let mut dst_file_path = output_path; dst_file_path.set_extension("zip"); let dst_file = dst_file_path .to_str() .context("Could not do string conversion")?; collect_zip_directory( src_dir, dst_file, zip::CompressionMethod::Deflated, &HashSet::new(), ) .with_context(|| { format!( "Error while zipping files from `{}` to `{}`", src_dir, dst_file ) })??; let path = PathBuf::new().join(src_dir); println!("Removing {}", path.display()); remove_dir_all(&path)?; let build_metadata = std::fs::metadata(dst_file) .with_context(|| format!("Failed to read file metadata for '{}'", dst_file))?; Ok(BuildStatistics { name: format!("Windows {}", bitness.to_string()), file_name: dst_file_path .file_name() .unwrap() .to_str() .unwrap() .to_string(), time: start.elapsed(), size: build_metadata.len(), }) }
if path.is_file() { let mut file = File::open(path)?; file.read_to_end(&mut buffer)?; output_file.write_all(&buffer)?; buffer.clear(); }
if_condition
[ { "content": "pub fn download_love(version: LoveVersion, platform: Platform, bitness: Bitness) -> Result<()> {\n\n let file_info = get_love_download_location(version, platform, bitness).with_context(|| {\n\n format!(\n\n \"Could not get download location for LÖVE {} on {} {}\",\n\n ...
Rust
compiler/rustc_middle/src/ty/consts/int.rs
cchiw/rust
469ee7cc68aa4d64d6c3bcff4e4108d0c8b97240
use rustc_apfloat::ieee::{Double, Single}; use rustc_apfloat::Float; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_target::abi::Size; use std::convert::{TryFrom, TryInto}; use std::fmt; use crate::ty::TyCtxt; #[derive(Copy, Clone)] pub struct ConstInt { int: ScalarInt, signed: bool, is_ptr_sized_integral: bool, } impl ConstInt { pub fn new(int: ScalarInt, signed: bool, is_ptr_sized_integral: bool) -> Self { Self { int, signed, is_ptr_sized_integral } } } impl std::fmt::Debug for ConstInt { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { int, signed, is_ptr_sized_integral } = *self; let size = int.size().bytes(); let raw = int.data; if signed { let bit_size = size * 8; let min = 1u128 << (bit_size - 1); let max = min - 1; if raw == min { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "isize::MIN"), (1, _) => write!(fmt, "i8::MIN"), (2, _) => write!(fmt, "i16::MIN"), (4, _) => write!(fmt, "i32::MIN"), (8, _) => write!(fmt, "i64::MIN"), (16, _) => write!(fmt, "i128::MIN"), _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } } else if raw == max { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "isize::MAX"), (1, _) => write!(fmt, "i8::MAX"), (2, _) => write!(fmt, "i16::MAX"), (4, _) => write!(fmt, "i32::MAX"), (8, _) => write!(fmt, "i64::MAX"), (16, _) => write!(fmt, "i128::MAX"), _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } } else { match size { 1 => write!(fmt, "{}", raw as i8)?, 2 => write!(fmt, "{}", raw as i16)?, 4 => write!(fmt, "{}", raw as i32)?, 8 => write!(fmt, "{}", raw as i64)?, 16 => write!(fmt, "{}", raw as i128)?, _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } if fmt.alternate() { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "_isize")?, (1, _) => write!(fmt, "_i8")?, (2, _) => write!(fmt, "_i16")?, (4, _) => write!(fmt, "_i32")?, (8, _) => write!(fmt, "_i64")?, (16, _) => write!(fmt, "_i128")?, _ => bug!(), } } Ok(()) } } else { let max = Size::from_bytes(size).truncate(u128::MAX); if raw == max { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "usize::MAX"), (1, _) => write!(fmt, "u8::MAX"), (2, _) => write!(fmt, "u16::MAX"), (4, _) => write!(fmt, "u32::MAX"), (8, _) => write!(fmt, "u64::MAX"), (16, _) => write!(fmt, "u128::MAX"), _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } } else { match size { 1 => write!(fmt, "{}", raw as u8)?, 2 => write!(fmt, "{}", raw as u16)?, 4 => write!(fmt, "{}", raw as u32)?, 8 => write!(fmt, "{}", raw as u64)?, 16 => write!(fmt, "{}", raw as u128)?, _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } if fmt.alternate() { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "_usize")?, (1, _) => write!(fmt, "_u8")?, (2, _) => write!(fmt, "_u16")?, (4, _) => write!(fmt, "_u32")?, (8, _) => write!(fmt, "_u64")?, (16, _) => write!(fmt, "_u128")?, _ => bug!(), } } Ok(()) } } } } #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] #[repr(packed)] pub struct ScalarInt { data: u128, size: u8, } impl<CTX> crate::ty::HashStable<CTX> for ScalarInt { fn hash_stable(&self, hcx: &mut CTX, hasher: &mut crate::ty::StableHasher) { { self.data }.hash_stable(hcx, hasher); self.size.hash_stable(hcx, hasher); } } impl<S: Encoder> Encodable<S> for ScalarInt { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u128(self.data)?; s.emit_u8(self.size) } } impl<D: Decoder> Decodable<D> for ScalarInt { fn decode(d: &mut D) -> ScalarInt { ScalarInt { data: d.read_u128(), size: d.read_u8() } } } impl ScalarInt { pub const TRUE: ScalarInt = ScalarInt { data: 1_u128, size: 1 }; pub const FALSE: ScalarInt = ScalarInt { data: 0_u128, size: 1 }; pub const ZST: ScalarInt = ScalarInt { data: 0_u128, size: 0 }; #[inline] pub fn size(self) -> Size { Size::from_bytes(self.size) } #[inline(always)] fn check_data(self) { debug_assert_eq!( self.size().truncate(self.data), { self.data }, "Scalar value {:#x} exceeds size of {} bytes", { self.data }, self.size ); } #[inline] pub fn null(size: Size) -> Self { Self { data: 0, size: size.bytes() as u8 } } #[inline] pub fn is_null(self) -> bool { self.data == 0 } #[inline] pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> { let data = i.into(); if size.truncate(data) == data { Some(Self { data, size: size.bytes() as u8 }) } else { None } } #[inline] pub fn try_from_int(i: impl Into<i128>, size: Size) -> Option<Self> { let i = i.into(); let truncated = size.truncate(i as u128); if size.sign_extend(truncated) as i128 == i { Some(Self { data: truncated, size: size.bytes() as u8 }) } else { None } } #[inline] pub fn assert_bits(self, target_size: Size) -> u128 { self.to_bits(target_size).unwrap_or_else(|size| { bug!("expected int of size {}, but got size {}", target_size.bytes(), size.bytes()) }) } #[inline] pub fn to_bits(self, target_size: Size) -> Result<u128, Size> { assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST"); if target_size.bytes() == u64::from(self.size) { self.check_data(); Ok(self.data) } else { Err(self.size()) } } #[inline] pub fn try_to_machine_usize<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Result<u64, Size> { Ok(self.to_bits(tcx.data_layout.pointer_size)? as u64) } } macro_rules! from { ($($ty:ty),*) => { $( impl From<$ty> for ScalarInt { #[inline] fn from(u: $ty) -> Self { Self { data: u128::from(u), size: std::mem::size_of::<$ty>() as u8, } } } )* } } macro_rules! try_from { ($($ty:ty),*) => { $( impl TryFrom<ScalarInt> for $ty { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(std::mem::size_of::<$ty>())) .map(|u| u.try_into().unwrap()) } } )* } } from!(u8, u16, u32, u64, u128, bool); try_from!(u8, u16, u32, u64, u128); impl TryFrom<ScalarInt> for bool { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(1)).and_then(|u| match u { 0 => Ok(false), 1 => Ok(true), _ => Err(Size::from_bytes(1)), }) } } impl From<char> for ScalarInt { #[inline] fn from(c: char) -> Self { Self { data: c as u128, size: std::mem::size_of::<char>() as u8 } } } impl TryFrom<ScalarInt> for char { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(std::mem::size_of::<char>())) .map(|u| char::from_u32(u.try_into().unwrap()).unwrap()) } } impl From<Single> for ScalarInt { #[inline] fn from(f: Single) -> Self { Self { data: f.to_bits(), size: 4 } } } impl TryFrom<ScalarInt> for Single { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(4)).map(Self::from_bits) } } impl From<Double> for ScalarInt { #[inline] fn from(f: Double) -> Self { Self { data: f.to_bits(), size: 8 } } } impl TryFrom<ScalarInt> for Double { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(8)).map(Self::from_bits) } } impl fmt::Debug for ScalarInt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.size == 0 { self.check_data(); write!(f, "<ZST>") } else { write!(f, "0x{:x}", self) } } } impl fmt::LowerHex for ScalarInt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.check_data(); write!(f, "{:01$x}", { self.data }, self.size as usize * 2) } } impl fmt::UpperHex for ScalarInt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.check_data(); write!(f, "{:01$X}", { self.data }, self.size as usize * 2) } }
use rustc_apfloat::ieee::{Double, Single}; use rustc_apfloat::Float; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_target::abi::Size; use std::convert::{TryFrom, TryInto}; use std::fmt; use crate::ty::TyCtxt; #[derive(Copy, Clone)] pub struct ConstInt { int: ScalarInt, signed: bool, is_ptr_sized_integral: bool, } impl ConstInt { pub fn new(int: ScalarInt, signed: bool, is_ptr_sized_integral: bool) -> Self { Self { int, signed, is_ptr_sized_integral } } } impl std::fmt::Debug for ConstInt { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { int, signed, is_ptr_sized_integral } = *self; let size = int.size().bytes(); let raw = int.data; if signed { let bit_size = size * 8; let min = 1u128 << (bit_size - 1); let max = min - 1; if raw == min { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "isize::MIN"), (1, _) => write!(fmt, "i8::MIN"), (2, _) => write!(fmt, "i16::MIN"), (4, _) => write!(fmt, "i32::MIN"), (8, _) => write!(fmt, "i64::MIN"), (16, _) => write!(fmt, "i128::MIN"), _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } } else if raw == max { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "isize::MAX"), (1, _) => write!(fmt, "i8::MAX"), (2, _) => write!(fmt, "i16::MAX"), (4, _) => write!(fmt, "i32::MAX"), (8, _) => write!(fmt, "i64::MAX"), (16, _) => write!(fmt, "i128::MAX"), _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } } else { match size { 1 => write!(fmt, "{}", raw as i8)?, 2 => write!(fmt, "{}", raw as i16)?, 4 => write!(fmt, "{}", raw as i32)?, 8 => write!(fmt, "{}", raw as i64)?, 16 => write!(fmt, "{}", raw as i128)?, _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } if fmt.alternate() { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "_isize")?, (1, _) => write!(fmt, "_i8")?, (2, _) => write!(fmt, "_i16")?, (4, _) => write!(fmt, "_i32")?, (8, _) => write!(fmt, "_i64")?, (16, _) => write!(fmt, "_i128")?, _ => bug!(), } } Ok(()) } } else { let max = Size::from_bytes(size).truncate(u128::MAX); if raw == max { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "usize::MAX"), (1, _) => write!(fmt, "u8::MAX"), (2, _) => write!(fmt, "u16::MAX"), (4, _) => write!(fmt, "u32::MAX"), (8, _) => write!(fmt, "u64::MAX"), (16, _) => write!(fmt, "u128::MAX"), _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } } else { match size { 1 => write!(fmt, "{}", raw as u8)?, 2 => write!(fmt, "{}", raw as u16)?, 4 => write!(fmt, "{}", raw as u32)?, 8 => write!(fmt, "{}", raw as u64)?, 16 => write!(fmt, "{}", raw as u128)?, _ => bug!("ConstInt 0x{:x} with size = {} and signed = {}", raw, size, signed), } if fmt.alternate() { match (size, is_ptr_sized_integral) { (_, true) => write!(fmt, "_usize")?, (1, _) => write!(fmt, "_u8")?, (2, _) => write!(fmt, "_u16")?, (4, _) => write!(fmt, "_u32")?, (8, _) => write!(fmt, "_u64")?, (16, _) => write!(fmt, "_u128")?, _ => bug!(), } } Ok(()) } } } } #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] #[repr(packed)] pub struct ScalarInt { data: u128, size: u8, } impl<CTX> crate::ty::HashStable<CTX> for ScalarInt { fn hash_stable(&self, hcx: &mut CTX, hasher: &mut crate::ty::StableHasher) { { self.data }.hash_stable(hcx, hasher); self.size.hash_stable(hcx, hasher); } } impl<S: Encoder> Encodable<S> for ScalarInt { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u128(self.data)?; s.emit_u8(self.size) } } impl<D: Decoder> Decodable<D> for ScalarInt { fn decode(d: &mut D) -> ScalarInt { ScalarInt { data: d.read_u128(), size: d.read_u8() } } } impl ScalarInt { pub const TRUE: ScalarInt = ScalarInt { data: 1_u128, size: 1 }; pub const FALSE: ScalarInt = ScalarInt { data: 0_u128, size: 1 }; pub const ZST: ScalarInt = ScalarInt { data: 0_u128, size: 0 }; #[inline] pub fn size(self) -> Size { Size::from_bytes(self.size) } #[inline(always)] fn check_data(self) { debug_assert_eq!( self.size().truncate(self.data), { self.data }, "Scalar value {:#x} exceeds size of {} bytes", { self.data }, self.size ); } #[inline] pub fn null(size: Size) -> Self { Self { data: 0, size: size.bytes() as u8 } } #[inline] pub fn is_null(self) -> bool { self.data == 0 } #[inline]
#[inline] pub fn try_from_int(i: impl Into<i128>, size: Size) -> Option<Self> { let i = i.into(); let truncated = size.truncate(i as u128); if size.sign_extend(truncated) as i128 == i { Some(Self { data: truncated, size: size.bytes() as u8 }) } else { None } } #[inline] pub fn assert_bits(self, target_size: Size) -> u128 { self.to_bits(target_size).unwrap_or_else(|size| { bug!("expected int of size {}, but got size {}", target_size.bytes(), size.bytes()) }) } #[inline] pub fn to_bits(self, target_size: Size) -> Result<u128, Size> { assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST"); if target_size.bytes() == u64::from(self.size) { self.check_data(); Ok(self.data) } else { Err(self.size()) } } #[inline] pub fn try_to_machine_usize<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Result<u64, Size> { Ok(self.to_bits(tcx.data_layout.pointer_size)? as u64) } } macro_rules! from { ($($ty:ty),*) => { $( impl From<$ty> for ScalarInt { #[inline] fn from(u: $ty) -> Self { Self { data: u128::from(u), size: std::mem::size_of::<$ty>() as u8, } } } )* } } macro_rules! try_from { ($($ty:ty),*) => { $( impl TryFrom<ScalarInt> for $ty { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(std::mem::size_of::<$ty>())) .map(|u| u.try_into().unwrap()) } } )* } } from!(u8, u16, u32, u64, u128, bool); try_from!(u8, u16, u32, u64, u128); impl TryFrom<ScalarInt> for bool { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(1)).and_then(|u| match u { 0 => Ok(false), 1 => Ok(true), _ => Err(Size::from_bytes(1)), }) } } impl From<char> for ScalarInt { #[inline] fn from(c: char) -> Self { Self { data: c as u128, size: std::mem::size_of::<char>() as u8 } } } impl TryFrom<ScalarInt> for char { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(std::mem::size_of::<char>())) .map(|u| char::from_u32(u.try_into().unwrap()).unwrap()) } } impl From<Single> for ScalarInt { #[inline] fn from(f: Single) -> Self { Self { data: f.to_bits(), size: 4 } } } impl TryFrom<ScalarInt> for Single { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(4)).map(Self::from_bits) } } impl From<Double> for ScalarInt { #[inline] fn from(f: Double) -> Self { Self { data: f.to_bits(), size: 8 } } } impl TryFrom<ScalarInt> for Double { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result<Self, Size> { int.to_bits(Size::from_bytes(8)).map(Self::from_bits) } } impl fmt::Debug for ScalarInt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.size == 0 { self.check_data(); write!(f, "<ZST>") } else { write!(f, "0x{:x}", self) } } } impl fmt::LowerHex for ScalarInt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.check_data(); write!(f, "{:01$x}", { self.data }, self.size as usize * 2) } } impl fmt::UpperHex for ScalarInt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.check_data(); write!(f, "{:01$X}", { self.data }, self.size as usize * 2) } }
pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> { let data = i.into(); if size.truncate(data) == data { Some(Self { data, size: size.bytes() as u8 }) } else { None } }
function_block-full_function
[]
Rust
libsplinter/src/collections/mod.rs
davececchi/splinter
92bc0fdec6e66aa53bc37db13b5521343235b016
use std::collections::hash_map::{Iter, Keys, Values}; use std::collections::HashMap; use std::hash::Hash; #[derive(Clone, Debug, PartialEq, Default)] pub struct BiHashMap<K: Hash + Eq, V: Hash + Eq> { kv_hash_map: HashMap<K, V>, vk_hash_map: HashMap<V, K>, } impl<K: Hash + Eq, V: Hash + Eq> BiHashMap<K, V> where K: std::clone::Clone, V: std::clone::Clone, { pub fn new() -> Self { BiHashMap { kv_hash_map: HashMap::new(), vk_hash_map: HashMap::new(), } } pub fn with_capacity(capacity: usize) -> Self { BiHashMap { kv_hash_map: HashMap::with_capacity(capacity), vk_hash_map: HashMap::with_capacity(capacity), } } pub fn capacity(&self) -> usize { self.kv_hash_map.capacity() } pub fn reserve(&mut self, additional: usize) { self.kv_hash_map.reserve(additional); self.vk_hash_map.reserve(additional); } pub fn shrink_to_fit(&mut self) { self.kv_hash_map.shrink_to_fit(); self.vk_hash_map.shrink_to_fit(); } pub fn keys(&self) -> Keys<K, V> { self.kv_hash_map.keys() } pub fn values(&self) -> Values<K, V> { self.kv_hash_map.values() } pub fn iter_by_keys(&self) -> Iter<K, V> { self.kv_hash_map.iter() } pub fn iter_by_values(&self) -> Iter<V, K> { self.vk_hash_map.iter() } pub fn len(&self) -> usize { self.kv_hash_map.len() } pub fn is_empty(&self) -> bool { self.kv_hash_map.is_empty() } pub fn clear(&mut self) { self.kv_hash_map.clear(); self.vk_hash_map.clear(); } pub fn get_by_key(&self, key: &K) -> Option<&V> { self.kv_hash_map.get(key) } pub fn get_by_value(&self, value: &V) -> Option<&K> { self.vk_hash_map.get(value) } pub fn contains_key(&self, key: &K) -> bool { self.kv_hash_map.contains_key(key) } pub fn contains_value(&self, value: &V) -> bool { self.vk_hash_map.contains_key(value) } pub fn insert(&mut self, key: K, value: V) -> (Option<K>, Option<V>) { let old_value = self.kv_hash_map.insert(key.clone(), value.clone()); let old_key = self.vk_hash_map.insert(value, key); (old_key, old_value) } pub fn remove_by_key(&mut self, key: &K) -> Option<(K, V)> { let value = self.kv_hash_map.remove(key); if let Some(value) = value { let key = self.vk_hash_map.remove(&value); if let Some(key) = key { return Some((key, value)); } } None } pub fn remove_by_value(&mut self, value: &V) -> Option<(K, V)> { let key = self.vk_hash_map.remove(value); if let Some(key) = key { let value = self.kv_hash_map.remove(&key); if let Some(value) = value { return Some((key, value)); } } None } } #[cfg(test)] pub mod tests { use super::*; #[test] fn test_capacity() { let map: BiHashMap<String, usize> = BiHashMap::new(); let capacity = map.capacity(); assert_eq!(capacity, 0); let map_with_capacity: BiHashMap<String, usize> = BiHashMap::with_capacity(5); let capacity = map_with_capacity.capacity(); assert!(capacity >= 5); } #[test] fn test_reserve() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); let capacity = map.capacity(); assert_eq!(capacity, 0); map.reserve(5); let capacity = map.capacity(); assert!(capacity >= 5); } #[test] fn test_shrink_to_fit() { let mut map: BiHashMap<String, usize> = BiHashMap::with_capacity(100); let capacity = map.capacity(); assert!(capacity >= 100); map.shrink_to_fit(); let capacity = map.capacity(); assert_eq!(capacity, 0); } #[test] fn test_insert() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); assert_eq!((None, None), map.insert("ONE".to_string(), 1)); assert_eq!( (Some("ONE".to_string()), Some(1)), map.insert("ONE".to_string(), 1) ); assert_eq!( (Some("ONE".to_string()), None), map.insert("TWO".to_string(), 1) ); assert_eq!((None, Some(1)), map.insert("ONE".to_string(), 3)); } #[test] fn test_keys_and_values() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); let mut keys: Vec<String> = map.keys().map(|key| key.to_string()).collect(); keys.sort(); assert_eq!( keys, ["ONE".to_string(), "THREE".to_string(), "TWO".to_string()] ); let mut values: Vec<usize> = map.values().map(|value| value.clone()).collect(); values.sort(); assert_eq!(values, [1, 2, 3]) } #[test] fn test_iter_keys_and_values() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); let keys = vec!["ONE".to_string(), "THREE".to_string(), "TWO".to_string()]; let values = vec![1, 2, 3]; for (key, value) in map.iter_by_keys() { assert!(keys.contains(key)); assert!(values.contains(value)); } for (value, key) in map.iter_by_values() { assert!(keys.contains(key)); assert!(values.contains(value)); } } #[test] fn test_clear_and_is_empty() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); assert_eq!(map.len(), 0); assert!(map.is_empty()); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); assert_eq!(map.len(), 3); assert!(!map.is_empty()); map.clear(); assert_eq!(map.len(), 0); assert!(map.is_empty()); } #[test] fn test_get() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); assert_eq!(map.get_by_key(&"ONE".to_string()), Some(&1)); assert_eq!(map.get_by_key(&"TWO".to_string()), Some(&2)); assert_eq!(map.get_by_key(&"THREE".to_string()), Some(&3)); assert_eq!(map.get_by_key(&"FOUR".to_string()), None); assert_eq!(map.get_by_value(&1), Some(&"ONE".to_string())); assert_eq!(map.get_by_value(&2), Some(&"TWO".to_string())); assert_eq!(map.get_by_value(&3), Some(&"THREE".to_string())); assert_eq!(map.get_by_value(&4), None); } #[test] fn test_contains_key_and_value() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); assert!(map.contains_key(&"ONE".to_string())); assert!(map.contains_value(&1)); assert!(!map.contains_key(&"TWO".to_string())); assert!(!map.contains_value(&2)); } #[test] fn test_removes() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); let removed = map.remove_by_key(&"ONE".to_string()); assert_eq!(removed, Some(("ONE".to_string(), 1))); let removed = map.remove_by_key(&"ONE".to_string()); assert_eq!(removed, None); let removed = map.remove_by_value(&2); assert_eq!(removed, Some(("TWO".to_string(), 2))); let removed = map.remove_by_value(&2); assert_eq!(removed, None); } }
use std::collections::hash_map::{Iter, Keys, Values}; use std::collections::HashMap; use std::hash::Hash; #[derive(Clone, Debug, PartialEq, Default)] pub struct BiHashMap<K: Hash + Eq, V: Hash + Eq> { kv_hash_map: HashMap<K, V>, vk_hash_map: HashMap<V, K>, } impl<K: Hash + Eq, V: Hash + Eq> BiHashMap<K, V> where K: std::clone::Clone, V: std::clone::Clone, { pub fn new() -> Self { BiHashMap { kv_hash_map: HashMap::new(), vk_hash_map: HashMap::new(), } } pub fn with_capacity(capacity: usize) -> Self { BiHashMap { kv_hash_map: HashMap::with_capacity(capacity), vk_hash_map: HashMap::with_capacity(capacity), } } pub fn capacity(&self) -> usize { self.kv_hash_map.capacity() } pub fn reserve(&mut self, additional: usize) { self.kv_hash_map.reserve(additional); self.vk_hash_map.reserve(additional); } pub fn shrink_to_fit(&mut self) { self.kv_hash_map.shrink_to_fit(); self.vk_hash_map.shrink_to_fit(); } pub fn keys(&self) -> Keys<K, V> { self.kv_hash_map.keys() } pub fn values(&self) -> Values<K, V> { self.kv_hash_map.values() } pub fn iter_by_keys(&self) -> Iter<K, V> { self.kv_hash_map.iter() } pub fn iter_by_values(&self) -> Iter<V, K> { self.vk_hash_map.iter() } pub fn len(&self) -> usize { self.kv_hash_map.len() } pub fn is_empty(&self) -> bool { self.kv_hash_map.is_empty() } pub fn clear(&mut self) { self.kv_hash_map.clear(); self.vk_hash_map.clear(); } pub fn get_by_key(&self, key: &K) -> Option<&V> { self.kv_hash_map.get(key) } pub fn get_by_value(&self, value: &V) -> Option<&K> { self.vk_hash_map.get(value) } pub fn contains_key(&self, key: &K) -> bool { self.kv_hash_map.contains_key(key) } pub fn contains_value(&self, value: &V) -> bool { self.vk_hash_map.contains_key(value) } pub fn insert(&mut self, key: K, value: V) -> (Option<K>, Option<V>) { let old_value = self.kv_hash_map.insert(key.clone(), value.clone()); let old_key = self.vk_hash_map.insert(value, key); (old_key, old_value) } pub fn remove_by_key(&mut self, key: &K) -> Option<(K, V)> { let value = self.kv_hash_map.remove(key); if let Some(value) = value { let key = self.vk_hash_map.remove(&value); if let Some(key) = key { return Some((key, value)); } } None } pub fn remove_by_value(&mut self, value: &V) -> Option<(K, V)> { let key = self.vk_hash_map.remove(value); if let Some(key) = key { let value = self.kv_hash_map.remove(&key); if let Some(value) = value { return Some((key, value)); } } None } } #[cfg(test)] pub mod tests { use super::*; #[test] fn test_capacity() { let map: BiHashMap<String, usize> = BiHashMap::new(); let capacity = map.capacity(); assert_eq!(capacity, 0); let map_with_capacity: BiHashMap<String, usize> = BiHashMap::with_capacity(5); let capacity = map_with_capacity.capacity(); assert!(capacity >= 5); } #[test] fn test_reserve() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); let capacity = map.capacity(); assert_eq!(capacity, 0); map.reserve(5); let capacity = map.capacity(); assert!(capacity >= 5); } #[test] fn test_shrink_to_fit() { let mut map: BiHashMap<String, usize> = BiHashMap::with_capacity(100); let capacity = map.capacity(); assert!(capacity >= 100); map.shrink_to_fit(); let capacity = map.capacity(); assert_eq!(capacity, 0); } #[test] fn test_insert() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); assert_eq!((None, None), map.insert("ONE".to_string(), 1)); assert_eq!( (Some("ONE".to_string()), Some(1)), map.insert("ONE".to_string(), 1) ); assert_eq!( (Some("ONE".to_string()), None), map.insert("TWO".to_string(), 1) ); assert_eq!((None, Some(1)), map.insert("ONE".to_string(), 3)); } #[test] fn test_keys_and_values() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); let mut keys: Vec<String> = map.keys().map(|key| key.to_string()).collect(); keys.sort(); assert_eq!( keys, ["ONE".to_string(), "THREE".to_string(), "TWO".to_string()] ); let mut values: Vec<usize> = map.values().map(|value| value.clone()).collect(); values.sort(); assert_eq!(values, [1, 2, 3]) } #[test] fn test_iter_keys_and_values() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); let keys = vec!["ONE".to_string(), "THREE".to_string(), "TWO".to_string()]; let values = vec![1, 2, 3]; for (key, value) in map.iter_by_keys() { assert!(keys.contains(key)); assert!(values.contains(value)); } for (value, key) in map.iter_by_values() { assert!(keys.contains(key)); assert!(values.contains(value)); } } #[test] fn test_clear_and_is_empty() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); assert_eq!(map.len(), 0); assert!(map.is_empty()); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); assert_eq!(map.len(), 3); assert!(!map.is_empty()); map.clear(); assert_eq!(map.len(), 0); assert!(map.is_empty()); } #[test] fn test_get() {
#[test] fn test_contains_key_and_value() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); assert!(map.contains_key(&"ONE".to_string())); assert!(map.contains_value(&1)); assert!(!map.contains_key(&"TWO".to_string())); assert!(!map.contains_value(&2)); } #[test] fn test_removes() { let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); let removed = map.remove_by_key(&"ONE".to_string()); assert_eq!(removed, Some(("ONE".to_string(), 1))); let removed = map.remove_by_key(&"ONE".to_string()); assert_eq!(removed, None); let removed = map.remove_by_value(&2); assert_eq!(removed, Some(("TWO".to_string(), 2))); let removed = map.remove_by_value(&2); assert_eq!(removed, None); } }
let mut map: BiHashMap<String, usize> = BiHashMap::new(); map.insert("ONE".to_string(), 1); map.insert("TWO".to_string(), 2); map.insert("THREE".to_string(), 3); assert_eq!(map.get_by_key(&"ONE".to_string()), Some(&1)); assert_eq!(map.get_by_key(&"TWO".to_string()), Some(&2)); assert_eq!(map.get_by_key(&"THREE".to_string()), Some(&3)); assert_eq!(map.get_by_key(&"FOUR".to_string()), None); assert_eq!(map.get_by_value(&1), Some(&"ONE".to_string())); assert_eq!(map.get_by_value(&2), Some(&"TWO".to_string())); assert_eq!(map.get_by_value(&3), Some(&"THREE".to_string())); assert_eq!(map.get_by_value(&4), None); }
function_block-function_prefix_line
[ { "content": "/// The HandlerWrapper provides a typeless wrapper for typed Handler instances.\n\nstruct HandlerWrapper<MT: Hash + Eq + Debug + Clone> {\n\n inner: InnerHandler<MT>,\n\n}\n\n\n\nimpl<MT: Hash + Eq + Debug + Clone> HandlerWrapper<MT> {\n\n fn handle(\n\n &self,\n\n message_byte...
Rust
src/wasm/terrain_generator/src/rivers.rs
Havegum/Terrain-Generator
8e562f173f0474d1bf7d53ca04ede75768fa96cd
use super::erosion::get_flux; type River = Vec<(usize, f64)>; pub fn get_river( heights: &Vec<f64>, adjacent: &Vec<Vec<usize>>, flux: &Vec<f64>, sea_level: f64, voronoi_cells: &Vec<Vec<usize>>, cell_heights: &Vec<f64>, mut visited: &mut [bool], i: usize, mut river: Vec<(usize, f64)>, ) -> (River, Vec<River>) { visited[i] = true; let height = heights[i]; if height < sea_level { let cells = &voronoi_cells[i]; let num_adjacent = cells .iter() .filter(|cell| cell_heights[**cell] > sea_level) .count(); if num_adjacent < 2 { return (river, Vec::new()); } } river.push((i, flux[i])); let mut tributaries: Vec<River> = Vec::new(); let mut main_branch_found = false; let mut neighbors = adjacent[i].clone(); neighbors.sort_unstable_by(|&a, &b| flux[a].partial_cmp(&flux[b]).unwrap().reverse()); for neighbor in neighbors { if visited[neighbor] { continue; } if adjacent[neighbor].iter().any(|n| heights[*n] < height) { continue; } if !main_branch_found { main_branch_found = true; let (new_river, mut new_tributaries) = get_river( &heights, &adjacent, &flux, sea_level, &voronoi_cells, &cell_heights, &mut visited, neighbor, river, ); river = new_river; tributaries.append(&mut new_tributaries); } else { let (new_river, mut new_tributaries) = get_river( &heights, &adjacent, &flux, sea_level, &voronoi_cells, &cell_heights, &mut visited, neighbor, vec![(i, flux[i])], ); tributaries.push(new_river); tributaries.append(&mut new_tributaries); } } (river, tributaries) } pub fn get_rivers( heights: &Vec<f64>, adjacent: &Vec<Vec<usize>>, sea_level: f64, voronoi_cells: &Vec<Vec<usize>>, cell_heights: &Vec<f64>, ) -> Vec<River> { let flux = get_flux(heights, adjacent); let mut points_by_height = (0..heights.len()).collect::<Vec<usize>>(); points_by_height.sort_unstable_by(|a, b| heights[*a].partial_cmp(&heights[*b]).unwrap()); let mut visited = vec![false; heights.len()]; let mut rivers: Vec<River> = Vec::new(); for &i in points_by_height.iter() { if visited[i] { continue; } let (new_river, mut new_tributaries) = get_river( &heights, &adjacent, &flux, sea_level, &voronoi_cells, &cell_heights, &mut visited, i, Vec::new(), ); rivers.push(new_river); rivers.append(&mut new_tributaries); } rivers .into_iter() .filter(|r| r.len() > 1) .collect::<Vec<River>>() }
use super::erosion::get_flux; type River = Vec<(usize, f64)>; pub fn get_river( heights: &Vec<f64>, adjacent: &Vec<Vec<usize>>, flux: &Vec<f64>, sea_level: f64, voronoi_cells: &Vec<Vec<usize>>, cell_heights: &Vec<f64>, mut visited: &mut [bool], i: usize, mut river: Vec<(usize, f64)>, ) -> (River, Vec<River>) { visited[i] = true; let height = heights[i]; if height < sea_level { let cells = &voronoi_cells[i]; let num_adjacent = cells .iter() .filter(|cell| cell_heights[**cell] > sea_level) .count(); if num_adjacent < 2 { return (river, Vec::new()); } } river.push((i, flux[i])); let mut tributaries: Vec<River> = Vec::new(); let mut main_branch_found = false; let mut neighbors = adjacent[i].clone(); neighbors.sort_unstable_by(|&a, &b| flux[a].partial_cmp(&flux[b]).unwrap().reverse()); fo
pub fn get_rivers( heights: &Vec<f64>, adjacent: &Vec<Vec<usize>>, sea_level: f64, voronoi_cells: &Vec<Vec<usize>>, cell_heights: &Vec<f64>, ) -> Vec<River> { let flux = get_flux(heights, adjacent); let mut points_by_height = (0..heights.len()).collect::<Vec<usize>>(); points_by_height.sort_unstable_by(|a, b| heights[*a].partial_cmp(&heights[*b]).unwrap()); let mut visited = vec![false; heights.len()]; let mut rivers: Vec<River> = Vec::new(); for &i in points_by_height.iter() { if visited[i] { continue; } let (new_river, mut new_tributaries) = get_river( &heights, &adjacent, &flux, sea_level, &voronoi_cells, &cell_heights, &mut visited, i, Vec::new(), ); rivers.push(new_river); rivers.append(&mut new_tributaries); } rivers .into_iter() .filter(|r| r.len() > 1) .collect::<Vec<River>>() }
r neighbor in neighbors { if visited[neighbor] { continue; } if adjacent[neighbor].iter().any(|n| heights[*n] < height) { continue; } if !main_branch_found { main_branch_found = true; let (new_river, mut new_tributaries) = get_river( &heights, &adjacent, &flux, sea_level, &voronoi_cells, &cell_heights, &mut visited, neighbor, river, ); river = new_river; tributaries.append(&mut new_tributaries); } else { let (new_river, mut new_tributaries) = get_river( &heights, &adjacent, &flux, sea_level, &voronoi_cells, &cell_heights, &mut visited, neighbor, vec![(i, flux[i])], ); tributaries.push(new_river); tributaries.append(&mut new_tributaries); } } (river, tributaries) }
function_block-function_prefixed
[ { "content": "pub fn smooth(mut heights: Vec<f64>, adjacent: &Vec<Vec<usize>>) -> Vec<f64> {\n\n let alpha = 1.;\n\n let alpha = 0.66;\n\n\n\n for (i, height) in heights\n\n .clone()\n\n .into_iter()\n\n .enumerate()\n\n .collect::<Vec<(usize, f64)>>()\n\n {\n\n le...
Rust
src/conferencing.rs
ktaekwon000/fluminurs
edcbbba13f8f5bf23d713333518b6ee25be5294a
use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::SystemTime; use async_trait::async_trait; use futures_util::future; use reqwest::header::REFERER; use reqwest::{Method, Url}; use scraper::{Html, Selector}; use serde::Deserialize; use crate::resource; use crate::resource::{OverwriteMode, OverwriteResult, Resource}; use crate::util::{parse_time, sanitise_filename}; use crate::{Api, ApiData, Result}; const ZOOM_VALIDATE_MEETING_PASSWORD_URL: &str = "https://nus-sg.zoom.us/rec/validate_meet_passwd"; const ZOOM_PASSWORD_URL_PREFIX: &str = "/rec/share"; const ZOOM_DOWNLOAD_REFERER_URL: &str = "https://nus-sg.zoom.us/"; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct Conference { id: String, name: String, start_date: String, #[serde(rename = "isPublishRecordURL")] is_publish_record_url: bool, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct CloudRecord { code: Option<u32>, record_instances: Option<Vec<CloudRecordInstance>>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct CloudRecordInstance { #[serde(rename = "shareURL")] share_url: String, password: String, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct ZoomValidationResponse { status: bool, } pub struct ConferencingHandle { id: String, path: PathBuf, } #[derive(Debug)] pub struct ZoomRecording { id: String, path: PathBuf, share_url: String, password: String, start_date: SystemTime, } impl ConferencingHandle { pub fn new(id: String, path: PathBuf) -> ConferencingHandle { ConferencingHandle { id, path } } pub async fn load(self, api: &Api) -> Result<Vec<ZoomRecording>> { let conferencing_resp = api .api_as_json::<ApiData<Vec<Conference>>>( &format!( "zoom/Meeting/{}/Meetings?offset=0&sortby=startDate%20asc&populate=null", self.id ), Method::GET, None, ) .await?; match conferencing_resp.data { Some(conferences) => future::join_all( conferences .into_iter() .filter(|c| c.is_publish_record_url) .map(|c| load_cloud_record(api, c, &self.path)), ) .await .into_iter() .collect::<Result<Vec<_>>>() .map(|v| v.into_iter().flatten().collect::<Vec<_>>()), None => Err("Invalid API response from server: type mismatch"), } } } async fn load_cloud_record( api: &Api, conference: Conference, path: &Path, ) -> Result<Vec<ZoomRecording>> { let request_path = format!("zoom/Meeting/{}/cloudrecord", conference.id); let mut num_404_tries = 0; let cloud_record = loop { let cloud_record = api .api_as_json::<CloudRecord>(&request_path, Method::GET, None) .await?; if cloud_record.code != Some(400) && (cloud_record.code != Some(404) || num_404_tries >= 5) { break cloud_record; } if cloud_record.code == Some(404) { num_404_tries += 1; } }; let start_date = parse_time(&conference.start_date); let mut conference_id = conference.id; let conference_name: &str = &conference.name; match cloud_record.record_instances { Some(record_instances) => Ok(match record_instances.len() { 0 => vec![], 1 => record_instances .into_iter() .map(|cri| ZoomRecording { id: std::mem::take(&mut conference_id), path: path.join(make_mp4_extension(Path::new(&sanitise_filename( conference_name, )))), share_url: cri.share_url, password: cri.password, start_date, }) .collect::<Vec<_>>(), _ => record_instances .into_iter() .enumerate() .map(|(i, cri)| ZoomRecording { id: conference_id.clone(), path: path.join(make_mp4_extension(Path::new(&append_number( &sanitise_filename(conference_name), i + 1, )))), share_url: cri.share_url, password: cri.password, start_date, }) .collect::<Vec<_>>(), }), None => Ok(vec![]), } } fn make_mp4_extension(path: &Path) -> PathBuf { path.with_extension("mp4") } fn append_number(text: &str, number: usize) -> String { format!("{} ({})", text, number) } #[async_trait(?Send)] impl Resource for ZoomRecording { fn id(&self) -> &str { &self.id } fn path(&self) -> &Path { &self.path } fn path_mut(&mut self) -> &mut PathBuf { &mut self.path } fn last_updated(&self) -> SystemTime { self.start_date } async fn download( &self, api: &Api, destination: &Path, temp_destination: &Path, overwrite: OverwriteMode, ) -> Result<OverwriteResult> { resource::do_retryable_download( api, destination, temp_destination, overwrite, self.last_updated(), move |api| self.get_download_url(api), move |api, url, temp_destination| { resource::download_chunks(api, url, temp_destination, |req| { Api::add_desktop_user_agent(req) .header(reqwest::header::RANGE, "bytes=0-") .header(reqwest::header::REFERER, ZOOM_DOWNLOAD_REFERER_URL) }) }, ) .await } } impl ZoomRecording { async fn get_download_url(&self, api: &Api) -> Result<Url> { let share_url = Url::parse(&self.share_url).map_err(|_| "Unable to parse share URL")?; let share_resp = api .custom_request( share_url.clone(), Method::GET, None, Api::add_desktop_user_agent, ) .await?; let video_resp = if share_resp .url() .path() .starts_with(ZOOM_PASSWORD_URL_PREFIX) { let cloned_share_resp_url = share_resp.url().to_string(); let html = share_resp .text() .await .map_err(|_| "Unable to get HTML response")?; let document = Html::parse_document(&html); let id_selector = Selector::parse("#meetId").unwrap(); let mut form: HashMap<&str, &str> = HashMap::new(); form.insert( "id", document .select(&id_selector) .next() .and_then(|el| el.value().attr("value")) .ok_or("Unable to find conference id")?, ); form.insert("passwd", &self.password); form.insert("action", "viewdetailpage"); form.insert("recaptcha", ""); let validate_resp = api .custom_request( Url::parse(ZOOM_VALIDATE_MEETING_PASSWORD_URL) .expect("Unable to parse Zoom validation URL"), Method::POST, Some(&form), move |req| { Api::add_desktop_user_agent(req) .header(REFERER, cloned_share_resp_url.as_str()) }, ) .await?; let validate_resp_data = validate_resp .json::<ZoomValidationResponse>() .await .map_err(|_| "Unable to parse response JSON from Zoom validation")?; if !validate_resp_data.status { return Err("Recording password was rejected by Zoom"); } let resp = api .custom_request(share_url, Method::GET, None, Api::add_desktop_user_agent) .await?; if resp.url().path().starts_with(ZOOM_PASSWORD_URL_PREFIX) { return Err("Zoom still wants a password even though we already supplied it"); } resp } else { share_resp }; let resp_html = video_resp .text() .await .map_err(|_| "Unable to get response text")?; let video_url_regex = regex::Regex::new("viewMp4Url:[\\s]*\'([^\']*)\'").expect("Unable to parse regex"); let url = Url::parse( video_url_regex .captures(&resp_html) .ok_or("Parse error")? .get(1) .ok_or("Parse error")? .as_str(), ) .map_err(|_| "Unable to parse conference download URL")?; Ok(url) } }
use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::SystemTime; use async_trait::async_trait; use futures_util::future; use reqwest::header::REFERER; use reqwest::{Method, Url}; use scraper::{Html, Selector}; use serde::Deserialize; use crate::resource; use crate::resource::{OverwriteMode, OverwriteResult, Resource}; use crate::util::{parse_time, sanitise_filename}; use crate::{Api, ApiData, Result}; const ZOOM_VALIDATE_MEETING_PASSWORD_URL: &str = "https://nus-sg.zoom.us/rec/validate_meet_passwd"; const ZOOM_PASSWORD_URL_PREFIX: &str = "/rec/share"; const ZOOM_DOWNLOAD_REFERER_URL: &str = "https://nus-sg.zoom.us/"; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct Conference { id: String, name: String, start_date: String, #[serde(rename = "isPublishRecordURL")] is_publish_record_url: bool, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct CloudRecord { code: Option<u32>, record_instances: Option<Vec<CloudRecordInstance>>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct CloudRecordInstance { #[serde(rename = "shareURL")] share_url: String, password: String, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct ZoomValidationResponse { status: bool, } pub struct ConferencingHandle { id: String, path: PathBuf, } #[derive(Debug)] pub struct ZoomRecording { id: String, path: PathBuf, share_url: String, password: String, start_date: SystemTime, } impl ConferencingHandle { pub fn new(id: String, path: PathBuf) -> ConferencingHandle { ConferencingHandle { id, path } } pub async fn load(self, api: &Api) -> Result<Vec<ZoomRecording>> { let conferencing_resp = api .api_as_json::<ApiData<Vec<Conference>>>( &format!( "zoom/Meeting/{}/Meetings?offset=0&sortby=startDate%20asc&populate=null", self.id ), Method::GET, None, ) .await?; match conferencing_resp.data { Some(conferences) => future::join_all( conferences .into_iter() .filter(|c| c.is_publish_record_url) .map(|c| load_cloud_record(api, c, &self.path)), ) .awai
} async fn load_cloud_record( api: &Api, conference: Conference, path: &Path, ) -> Result<Vec<ZoomRecording>> { let request_path = format!("zoom/Meeting/{}/cloudrecord", conference.id); let mut num_404_tries = 0; let cloud_record = loop { let cloud_record = api .api_as_json::<CloudRecord>(&request_path, Method::GET, None) .await?; if cloud_record.code != Some(400) && (cloud_record.code != Some(404) || num_404_tries >= 5) { break cloud_record; } if cloud_record.code == Some(404) { num_404_tries += 1; } }; let start_date = parse_time(&conference.start_date); let mut conference_id = conference.id; let conference_name: &str = &conference.name; match cloud_record.record_instances { Some(record_instances) => Ok(match record_instances.len() { 0 => vec![], 1 => record_instances .into_iter() .map(|cri| ZoomRecording { id: std::mem::take(&mut conference_id), path: path.join(make_mp4_extension(Path::new(&sanitise_filename( conference_name, )))), share_url: cri.share_url, password: cri.password, start_date, }) .collect::<Vec<_>>(), _ => record_instances .into_iter() .enumerate() .map(|(i, cri)| ZoomRecording { id: conference_id.clone(), path: path.join(make_mp4_extension(Path::new(&append_number( &sanitise_filename(conference_name), i + 1, )))), share_url: cri.share_url, password: cri.password, start_date, }) .collect::<Vec<_>>(), }), None => Ok(vec![]), } } fn make_mp4_extension(path: &Path) -> PathBuf { path.with_extension("mp4") } fn append_number(text: &str, number: usize) -> String { format!("{} ({})", text, number) } #[async_trait(?Send)] impl Resource for ZoomRecording { fn id(&self) -> &str { &self.id } fn path(&self) -> &Path { &self.path } fn path_mut(&mut self) -> &mut PathBuf { &mut self.path } fn last_updated(&self) -> SystemTime { self.start_date } async fn download( &self, api: &Api, destination: &Path, temp_destination: &Path, overwrite: OverwriteMode, ) -> Result<OverwriteResult> { resource::do_retryable_download( api, destination, temp_destination, overwrite, self.last_updated(), move |api| self.get_download_url(api), move |api, url, temp_destination| { resource::download_chunks(api, url, temp_destination, |req| { Api::add_desktop_user_agent(req) .header(reqwest::header::RANGE, "bytes=0-") .header(reqwest::header::REFERER, ZOOM_DOWNLOAD_REFERER_URL) }) }, ) .await } } impl ZoomRecording { async fn get_download_url(&self, api: &Api) -> Result<Url> { let share_url = Url::parse(&self.share_url).map_err(|_| "Unable to parse share URL")?; let share_resp = api .custom_request( share_url.clone(), Method::GET, None, Api::add_desktop_user_agent, ) .await?; let video_resp = if share_resp .url() .path() .starts_with(ZOOM_PASSWORD_URL_PREFIX) { let cloned_share_resp_url = share_resp.url().to_string(); let html = share_resp .text() .await .map_err(|_| "Unable to get HTML response")?; let document = Html::parse_document(&html); let id_selector = Selector::parse("#meetId").unwrap(); let mut form: HashMap<&str, &str> = HashMap::new(); form.insert( "id", document .select(&id_selector) .next() .and_then(|el| el.value().attr("value")) .ok_or("Unable to find conference id")?, ); form.insert("passwd", &self.password); form.insert("action", "viewdetailpage"); form.insert("recaptcha", ""); let validate_resp = api .custom_request( Url::parse(ZOOM_VALIDATE_MEETING_PASSWORD_URL) .expect("Unable to parse Zoom validation URL"), Method::POST, Some(&form), move |req| { Api::add_desktop_user_agent(req) .header(REFERER, cloned_share_resp_url.as_str()) }, ) .await?; let validate_resp_data = validate_resp .json::<ZoomValidationResponse>() .await .map_err(|_| "Unable to parse response JSON from Zoom validation")?; if !validate_resp_data.status { return Err("Recording password was rejected by Zoom"); } let resp = api .custom_request(share_url, Method::GET, None, Api::add_desktop_user_agent) .await?; if resp.url().path().starts_with(ZOOM_PASSWORD_URL_PREFIX) { return Err("Zoom still wants a password even though we already supplied it"); } resp } else { share_resp }; let resp_html = video_resp .text() .await .map_err(|_| "Unable to get response text")?; let video_url_regex = regex::Regex::new("viewMp4Url:[\\s]*\'([^\']*)\'").expect("Unable to parse regex"); let url = Url::parse( video_url_regex .captures(&resp_html) .ok_or("Parse error")? .get(1) .ok_or("Parse error")? .as_str(), ) .map_err(|_| "Unable to parse conference download URL")?; Ok(url) } }
t .into_iter() .collect::<Result<Vec<_>>>() .map(|v| v.into_iter().flatten().collect::<Vec<_>>()), None => Err("Invalid API response from server: type mismatch"), } }
function_block-function_prefixed
[ { "content": "pub fn sanitise_filename(name: &str) -> String {\n\n if cfg!(windows) {\n\n sanitize_filename::sanitize_with_options(\n\n name.trim(),\n\n sanitize_filename::Options {\n\n windows: true,\n\n truncate: true,\n\n replacemen...
Rust
src/io_source.rs
YtFlow/mio-noafd
27bbb8dcb72a253ad86031ddc5f4ab2a1f2cda27
use std::ops::{Deref, DerefMut}; #[cfg(unix)] use std::os::unix::io::AsRawFd; #[cfg(windows)] use std::os::windows::io::AsRawSocket; #[cfg(debug_assertions)] use std::sync::atomic::{AtomicUsize, Ordering}; use std::{fmt, io}; #[cfg(any(unix, debug_assertions))] use crate::poll; use crate::sys::IoSourceState; use crate::{event, Interest, Registry, Token}; /* /// /// # Examples /// /// Basic usage. /// /// ``` /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// use mio::{Interest, Poll, Token}; /// use mio::IoSource; /// /// use std::net; /// /// let poll = Poll::new()?; /// /// // Bind a std TCP listener. /// let listener = net::TcpListener::bind("127.0.0.1:0")?; /// // Wrap it in the `IoSource` type. /// let mut listener = IoSource::new(listener); /// /// // Register the listener. /// poll.registry().register(&mut listener, Token(0), Interest::READABLE)?; /// # Ok(()) /// # } /// ``` */ pub struct IoSource<T> { state: IoSourceState, inner: T, #[cfg(debug_assertions)] selector_id: SelectorId, } #[allow(unused)] impl<T> IoSource<T> { pub fn new(io: T) -> IoSource<T> { IoSource { state: IoSourceState::new(), inner: io, #[cfg(debug_assertions)] selector_id: SelectorId::new(), } } pub fn do_io<F, R>(&self, f: F) -> io::Result<R> where F: FnOnce(&T) -> io::Result<R>, { self.state.do_io(f, &self.inner) } pub fn into_inner(self) -> T { self.inner } } impl<T> Deref for IoSource<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.inner } } impl<T> DerefMut for IoSource<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } #[cfg(unix)] impl<T> event::Source for IoSource<T> where T: AsRawFd, { fn register( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.associate(registry)?; poll::selector(registry).register(self.inner.as_raw_fd(), token, interests) } fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.check_association(registry)?; poll::selector(registry).reregister(self.inner.as_raw_fd(), token, interests) } fn deregister(&mut self, registry: &Registry) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.remove_association(registry)?; poll::selector(registry).deregister(self.inner.as_raw_fd()) } } #[cfg(windows)] impl<T> event::Source for IoSource<T> where T: AsRawSocket, { fn register( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.associate(registry)?; self.state .register(registry, token, interests, self.inner.as_raw_socket()) } fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.check_association(registry)?; self.state.reregister(registry, token, interests) } fn deregister(&mut self, _registry: &Registry) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.remove_association(_registry)?; self.state.deregister() } } impl<T> fmt::Debug for IoSource<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.inner.fmt(f) } } #[cfg(debug_assertions)] #[derive(Debug)] struct SelectorId { id: AtomicUsize, } #[cfg(debug_assertions)] impl SelectorId { const UNASSOCIATED: usize = 0; const fn new() -> SelectorId { SelectorId { id: AtomicUsize::new(Self::UNASSOCIATED), } } fn associate(&self, registry: &Registry) -> io::Result<()> { let registry_id = poll::selector(&registry).id(); let previous_id = self.id.swap(registry_id, Ordering::AcqRel); if previous_id == Self::UNASSOCIATED { Ok(()) } else { Err(io::Error::new( io::ErrorKind::AlreadyExists, "I/O source already registered with a `Registry`", )) } } fn check_association(&self, registry: &Registry) -> io::Result<()> { let registry_id = poll::selector(&registry).id(); let id = self.id.load(Ordering::Acquire); if id == registry_id { Ok(()) } else if id == Self::UNASSOCIATED { Err(io::Error::new( io::ErrorKind::NotFound, "I/O source not registered with `Registry`", )) } else { Err(io::Error::new( io::ErrorKind::AlreadyExists, "I/O source already registered with a different `Registry`", )) } } fn remove_association(&self, registry: &Registry) -> io::Result<()> { let registry_id = poll::selector(&registry).id(); let previous_id = self.id.swap(Self::UNASSOCIATED, Ordering::AcqRel); if previous_id == registry_id { Ok(()) } else { Err(io::Error::new( io::ErrorKind::NotFound, "I/O source not registered with `Registry`", )) } } } #[cfg(debug_assertions)] impl Clone for SelectorId { fn clone(&self) -> SelectorId { SelectorId { id: AtomicUsize::new(self.id.load(Ordering::Acquire)), } } }
use std::ops::{Deref, DerefMut}; #[cfg(unix)] use std::os::unix::io::AsRawFd; #[cfg(windows)] use std::os::windows::io::AsRawSocket; #[cfg(debug_assertions)] use std::sync::atomic::{AtomicUsize, Ordering}; use std::{fmt, io}; #[cfg(any(unix, debug_assertions))] use crate::poll; use crate::sys::IoSourceState; use crate::{event, Interest, Registry, Token}; /* /// /// # Examples /// /// Basic usage. /// /// ``` /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// use mio::{Interest, Poll, Token}; /// use mio::IoSource; /// /// use std::net; /// /// let poll = Poll::new()?; /// /// // Bind a std TCP listener. /// let listener = net::TcpListener::bind("127.0.0.1:0")?; /// // Wrap it in the `IoSource` type. /// let mut listener = IoSource::new(listener); /// /// // Register the listener. /// poll.registry().register(&mut listener, Token(0), Interest::READABLE)?; /// # Ok(()) /// # } /// ``` */ pub struct IoSource<T> { state: IoSourceState, inner: T, #[cfg(debug_assertions)] selector_id: SelectorId, } #[allow(unused)] impl<T> IoSource<T> { pub fn new(io: T) -> IoSource<T> { IoSource { state: IoSourceState::new(), inner: io, #[cfg(debug_assertions)] selector_id: SelectorId::new(), } } pub fn do_io<F, R>(&self, f: F) -> io::Result<R> where F: FnOnce(&T) -> io::Result<R>, { self.state.do_io(f, &self.inner) } pub fn into_inner(self) -> T { self.inner } } impl<T> Deref for IoSource<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.inner } } impl<T> DerefMut for IoSource<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } #[cfg(unix)] impl<T> event::Source for IoSource<T> where T: AsRawFd, { fn register( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.associate(registry)?; poll::selector(registry).register(self.inner.as_raw_fd(), token, interests) } fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.check_association(registry)?; poll::selector(registry).reregister(self.inner.as_raw_fd(), token, interests) } fn deregister(&mut self, registry: &Registry) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.remove_association(registry)?; poll::selector(registry).deregister(self.inner.as_raw_fd()) } } #[cfg(windows)] impl<T> event::Source for IoSource<T> where T: AsRawSocket, { fn register( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.associate(registry)?; self.state .register(registry, token, interests, self.inner.as_raw_socket()) }
fn deregister(&mut self, _registry: &Registry) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.remove_association(_registry)?; self.state.deregister() } } impl<T> fmt::Debug for IoSource<T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.inner.fmt(f) } } #[cfg(debug_assertions)] #[derive(Debug)] struct SelectorId { id: AtomicUsize, } #[cfg(debug_assertions)] impl SelectorId { const UNASSOCIATED: usize = 0; const fn new() -> SelectorId { SelectorId { id: AtomicUsize::new(Self::UNASSOCIATED), } } fn associate(&self, registry: &Registry) -> io::Result<()> { let registry_id = poll::selector(&registry).id(); let previous_id = self.id.swap(registry_id, Ordering::AcqRel); if previous_id == Self::UNASSOCIATED { Ok(()) } else { Err(io::Error::new( io::ErrorKind::AlreadyExists, "I/O source already registered with a `Registry`", )) } } fn check_association(&self, registry: &Registry) -> io::Result<()> { let registry_id = poll::selector(&registry).id(); let id = self.id.load(Ordering::Acquire); if id == registry_id { Ok(()) } else if id == Self::UNASSOCIATED { Err(io::Error::new( io::ErrorKind::NotFound, "I/O source not registered with `Registry`", )) } else { Err(io::Error::new( io::ErrorKind::AlreadyExists, "I/O source already registered with a different `Registry`", )) } } fn remove_association(&self, registry: &Registry) -> io::Result<()> { let registry_id = poll::selector(&registry).id(); let previous_id = self.id.swap(Self::UNASSOCIATED, Ordering::AcqRel); if previous_id == registry_id { Ok(()) } else { Err(io::Error::new( io::ErrorKind::NotFound, "I/O source not registered with `Registry`", )) } } } #[cfg(debug_assertions)] impl Clone for SelectorId { fn clone(&self) -> SelectorId { SelectorId { id: AtomicUsize::new(self.id.load(Ordering::Acquire)), } } }
fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.check_association(registry)?; self.state.reregister(registry, token, interests) }
function_block-full_function
[ { "content": "fn main() -> io::Result<()> {\n\n env_logger::init();\n\n\n\n // Create a poll instance.\n\n let mut poll = Poll::new()?;\n\n // Create storage for events.\n\n let mut events = Events::with_capacity(128);\n\n\n\n // Setup the TCP server socket.\n\n let addr = \"127.0.0.1:9000\...
Rust
src/gui/element/my_weakauras.rs
kawarimidoll/ajour
753e0ed24c83d183476a14ca918646a38dff23a3
use { super::{DEFAULT_FONT_SIZE, DEFAULT_PADDING}, crate::gui::{ style, AuraColumnKey, AuraColumnState, Interaction, Message, Mode, SortDirection, State, }, ajour_core::config::Flavor, ajour_core::theme::ColorPalette, ajour_weak_auras::Aura, ajour_widgets::TableRow, ajour_widgets::{header, Header}, iced::{ button, pick_list, Align, Button, Column, Container, Element, Length, PickList, Row, Space, Text, }, std::collections::HashMap, }; #[allow(clippy::too_many_arguments)] pub fn menu_container<'a>( color_palette: ColorPalette, flavor: Flavor, update_all_button_state: &'a mut button::State, refresh_button_state: &'a mut button::State, state: &HashMap<Mode, State>, num_auras: usize, updates_available: bool, is_updating: bool, updates_queued: bool, accounts_picklist_state: &'a mut pick_list::State<String>, accounts: &'a [String], chosen_account: Option<String>, ) -> Container<'a, Message> { let state = state .get(&Mode::MyWeakAuras(flavor)) .cloned() .unwrap_or_default(); let mut row = Row::new().height(Length::Units(35)); let mut update_all_button = Button::new( update_all_button_state, Text::new("Update All").size(DEFAULT_FONT_SIZE), ) .style(style::DefaultButton(color_palette)); let mut refresh_button = Button::new( refresh_button_state, Text::new("Refresh").size(DEFAULT_FONT_SIZE), ) .style(style::DefaultButton(color_palette)); let pick_list = PickList::new( accounts_picklist_state, accounts, chosen_account.clone(), Message::WeakAurasAccountSelected, ) .text_size(14) .width(Length::Units(120)) .style(style::PickList(color_palette)); if updates_available && !is_updating && !updates_queued { update_all_button = update_all_button.on_press(Interaction::UpdateAll(Mode::MyWeakAuras(flavor))); } if state == State::Ready { refresh_button = refresh_button.on_press(Interaction::Refresh(Mode::MyWeakAuras(flavor))); } let update_all_button: Element<Interaction> = update_all_button.into(); let refresh_button: Element<Interaction> = refresh_button.into(); let status_text = match state { State::Ready => { if updates_queued { Text::new("Updates queued. Finish them in-game.").size(DEFAULT_FONT_SIZE) } else { Text::new(format!("{} WeakAuras loaded", num_auras,)).size(DEFAULT_FONT_SIZE) } } _ => Text::new(""), }; let status_container = Container::new(status_text) .center_y() .padding(5) .style(style::NormalBackgroundContainer(color_palette)); let account_info_container = Container::new( Text::new(if chosen_account.is_some() { "" } else { "Select an Account" }) .size(DEFAULT_FONT_SIZE), ) .center_y() .padding(5) .style(style::NormalBackgroundContainer(color_palette)); row = row .push(Space::new(Length::Units(DEFAULT_PADDING), Length::Units(0))) .push(refresh_button.map(Message::Interaction)) .push(Space::new(Length::Units(7), Length::Units(0))) .push(update_all_button.map(Message::Interaction)) .push(Space::new(Length::Units(7), Length::Units(0))) .push(status_container) .push(Space::new(Length::Fill, Length::Units(0))) .push(account_info_container) .push(Space::new(Length::Units(7), Length::Units(0))) .push(pick_list) .push(Space::new(Length::Units(DEFAULT_PADDING), Length::Units(0))); let settings_column = Column::new() .push(Space::new(Length::Units(0), Length::Units(5))) .push(row); Container::new(settings_column) } pub fn data_row_container<'a, 'b>( color_palette: ColorPalette, aura: &'a Aura, column_config: &'b [(AuraColumnKey, Length, bool)], is_odd: Option<bool>, ) -> TableRow<'a, Message> { let default_height = Length::Units(26); let default_row_height = 26; let mut row_containers = vec![]; if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| { if *key == AuraColumnKey::Title && !hidden { Some((idx, width)) } else { None } }) .next() { let title = Text::new(aura.name()).size(DEFAULT_FONT_SIZE); let title_row = Row::new().push(title).spacing(3).align_items(Align::Center); let title_container = Container::new(title_row) .padding(5) .height(default_height) .width(*width) .center_y() .style(style::HoverableBrightForegroundContainer(color_palette)); row_containers.push((idx, title_container)); } if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| { if *key == AuraColumnKey::LocalVersion && !hidden { Some((idx, width)) } else { None } }) .next() { let local_version = Text::new(aura.installed_symver().unwrap_or("-")).size(DEFAULT_FONT_SIZE); let local_version_row = Row::new() .push(local_version) .spacing(3) .align_items(Align::Center); let local_version_container = Container::new(local_version_row) .height(default_height) .width(*width) .center_y() .style(style::HoverableForegroundContainer(color_palette)); row_containers.push((idx, local_version_container)); } if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| { if *key == AuraColumnKey::RemoteVersion && !hidden { Some((idx, width)) } else { None } }) .next() { let remote_version = Text::new(aura.remote_symver()).size(DEFAULT_FONT_SIZE); let remote_version_row = Row::new() .push(remote_version) .spacing(3) .align_items(Align::Center); let remote_version_container = Container::new(remote_version_row) .height(default_height) .width(*width) .center_y() .style(style::HoverableForegroundContainer(color_palette)); row_containers.push((idx, remote_version_container)); } if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| { if *key == AuraColumnKey::Author && !hidden { Some((idx, width)) } else { None } }) .next() { let author = Text::new(aura.author()).size(DEFAULT_FONT_SIZE); let author_row = Row::new() .push(author) .spacing(3) .align_items(Align::Center); let author_container = Container::new(author_row) .height(default_height) .width(*width) .center_y() .style(style::HoverableForegroundContainer(color_palette)); row_containers.push((idx, author_container)); } if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| { if *key == AuraColumnKey::Status && !hidden { Some((idx, width)) } else { None } }) .next() { let status = Text::new(aura.status().to_string()).size(DEFAULT_FONT_SIZE); let status_row = Row::new() .push(status) .spacing(3) .align_items(Align::Center); let status_container = Container::new(status_row) .height(default_height) .width(*width) .center_y() .style(style::HoverableForegroundContainer(color_palette)); row_containers.push((idx, status_container)); } let left_spacer = Space::new(Length::Units(DEFAULT_PADDING), Length::Units(0)); let right_spacer = Space::new(Length::Units(DEFAULT_PADDING + 5), Length::Units(0)); let mut row = Row::new().push(left_spacer).spacing(1); row_containers.sort_by(|a, b| a.0.cmp(&b.0)); for (_, elem) in row_containers.into_iter() { row = row.push(elem); } row = row.push(right_spacer); let mut table_row = TableRow::new(row) .width(Length::Fill) .inner_row_height(default_row_height); if let Some(url) = aura.url() { table_row = table_row .on_press(move |_| Message::Interaction(Interaction::OpenLink(url.to_string()))); } if is_odd == Some(true) { table_row = table_row.style(style::TableRowAlternate(color_palette)) } else { table_row = table_row.style(style::TableRow(color_palette)) } table_row } fn row_title<T: PartialEq>( column_key: T, previous_column_key: Option<T>, previous_sort_direction: Option<SortDirection>, title: &str, ) -> String { if Some(column_key) == previous_column_key { match previous_sort_direction { Some(SortDirection::Asc) => format!("{} ▲", title), Some(SortDirection::Desc) => format!("{} ▼", title), _ => title.to_string(), } } else { title.to_string() } } pub fn titles_row_header<'a>( color_palette: ColorPalette, auras: &[Aura], header_state: &'a mut header::State, column_state: &'a mut [AuraColumnState], previous_column_key: Option<AuraColumnKey>, previous_sort_direction: Option<SortDirection>, ) -> Header<'a, Message> { let mut row_titles = vec![]; for column in column_state.iter_mut().filter(|c| !c.hidden) { let column_key = column.key; let row_title = row_title( column_key, previous_column_key, previous_sort_direction, &column.key.title(), ); let mut row_header = Button::new( &mut column.btn_state, Text::new(row_title) .size(DEFAULT_FONT_SIZE) .width(Length::Fill), ) .width(Length::Fill) .on_press(Interaction::SortAuraColumn(column_key)); if previous_column_key == Some(column_key) { row_header = row_header.style(style::SelectedColumnHeaderButton(color_palette)); } else { row_header = row_header.style(style::ColumnHeaderButton(color_palette)); } let row_header: Element<Interaction> = row_header.into(); let row_container = Container::new(row_header.map(Message::Interaction)) .width(column.width) .style(style::NormalBackgroundContainer(color_palette)); if !auras.is_empty() { row_titles.push((column.key.as_string(), row_container)); } } Header::new( header_state, row_titles, Some(Length::Units(DEFAULT_PADDING)), Some(Length::Units(DEFAULT_PADDING + 5)), ) .spacing(1) .height(Length::Units(25)) .on_resize(3, |event| { Message::Interaction(Interaction::ResizeColumn( Mode::MyWeakAuras(Flavor::default()), event, )) }) }
use { super::{DEFAULT_FONT_SIZE, DEFAULT_PADDING}, crate::gui::{ style, AuraColumnKey, AuraColumnState, Interaction, Message, Mode, SortDirection, State, }, ajour_core::config::Flavor, ajour_core::theme::ColorPalette, ajour_weak_auras::Aura, ajour_widgets::TableRow, ajour_widgets::{header, Header}, iced::{ button, pick_list, Align, Button, Column, Container, Element, Length, PickList, Row, Space, Text, }, std::collections::HashMap, }; #[allow(clippy::too_many_arguments)] pub fn menu_container<'a>( color_palette: ColorPalette, flavor: Flavor, update_all_button_state: &'a mut button::State, refresh_button_state: &'a mut button::State, state: &HashMap<Mode, State>, num_auras: usize, updates_available: bool, is_updating: bool, updates_queued: bool, accounts_picklist_state: &'a mut pick_list::State<String>, accounts: &'a [String], chosen_account: Option<String>, ) -> Container<'a, Message> { let state = state .get(&Mode::MyWeakAuras(flavor)) .cloned() .unwrap_or_default(); let mut row = Row::new().height(Length::Units(35)); let mut update_all_button = Button::new( update_all_button_state, Text::new("Update All").size(DEFAULT_FONT_SIZE), ) .style(style::DefaultButton(color_palette)); let mut refresh_button = Button::new( refresh_button_state, Text::new("Refresh").size(DEFAULT_FONT_SIZE), ) .style(style::DefaultButton(color_palette)); let pick_list = PickList::new( accounts_picklist_state, accounts, chosen_account.clone(), Message::WeakAurasAccountSelected, ) .text_size(14) .width(Length::Units(120)) .style(style::PickList(color_palette)); if updates_available && !is_updating && !updates_queued { update_all_button = update_all_button.on_press(Interaction::UpdateAll(Mode::MyWeakAuras(flavor))); } if state == State::Ready { refresh_button = refresh_button.on_press(Interaction::Refresh(Mode::MyWeakAuras(flavor))); } let update_all_button: Element<Interaction> = update_all_button.into(); let refresh_button: Element<Interaction> = refresh_button.into(); let status_text = match state { State::Ready => { if updates_queued { Text::new("Updates queued. Finish them in-game.").size(DEFAULT_FONT_SIZE) } else { Text::new(format!("{} WeakAuras loaded", num_auras,)).size(DEFAULT_FONT_SIZE) } } _ => Text::new(""), }; let status_container = Container::new(status_text) .center_y() .padding(5) .style(style::NormalBackgroundContainer(color_palette)); let account_info_container = Container::new( Text::new(if chosen_account.is_some() { "" } else { "Select an Account" }) .size(DEFAULT_FONT_SIZE), ) .center_y() .padding(5) .style(style::NormalBackgroundContainer(color_palette)); row = row .push(Space::new(Length::Units(DEFAULT_PADDING), Length::Units(0))) .push(refresh_button.map(Message::Interaction)) .push(Space::new(Length::Units(7), Length::Units(0))) .push(update_all_button.map(Message::Interaction)) .push(Space::new(Length::Units(7), Length::Units(0))) .push(status_container) .push(Space::new(Length::Fill, Length::Units(0))) .push(account_info_container) .push(Space::new(Length::Units(7), Length::Units(0))) .push(pick_list) .push(Space::new(Length::Units(DEFAULT_PADDING), Length::Units(0))); let settings_column = Column::new() .push(Space::new(Length::Units(0), Length::Units(5))) .push(row); Container::new(settings_column) } pub fn data_row_container<'a, 'b>( color_palette: ColorPalette, aura: &'a Aura, column_config: &'b [(AuraColumnKey, Length, bool)], is_odd: Option<bool>, ) -> TableRow<'a, Message> { let default_height = Length::Units(26); let default_row_height = 26; let mut row_containers = vec![]; if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| { if *key == AuraColumnKey::Title && !hidden { Some((idx, width)) } else { None } }) .next() { let title = Text::new(aura.name()).size(DEFAULT_FONT_SIZE); let title_row = Row::new().push(title).spacing(3).align_items(Align::Center); let title_container = Container::new(title_row) .padding(5) .height(default_height) .width(*width) .center_y() .style(style::HoverableBrightForegroundContainer(color_palette)); row_containers.push((idx, title_container)); } if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| { if *key == AuraColumnKey::LocalVersion && !hidden { Some((idx, width)) } else { None } }) .next() { let local_version = Text::new(aura.installed_symver().unwrap_or("-")).size(DEFAULT_FONT_SIZE); let local_version_row = Row::new() .push(local_version) .spacing(3) .align_items(Align::Center); let local_version_container = Container::new(local_version_row) .height(default_height) .width(*width) .center_y() .style(style::HoverableForegroundContainer(color_palette)); row_containers.push((idx, local_version_container)); } if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| { if *key == AuraColumnKey::RemoteVersion && !hidden { Some((idx, width)) } else { None } }) .next() { let remote_version = Text::new(aura.remote_symver()).size(DEFAULT_FONT_SIZE); let remote_version_row = Row::new() .push(remote_version) .spacing(3) .align_items(Align::Center); let remote_version_container = Container::new(remote_version_row) .height(default_height) .width(*width) .center_y() .style(style::HoverableForegroundContainer(color_palette)); row_containers.push((idx, remote_version_container)); } if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| { if *key == AuraColumnKey::Author && !hidden { Some((idx, width)) } else { None } }) .next() { let author = Text::new(aura.author()).size(DEFAULT_FONT_SIZE); let author_row = Row::new() .push(author) .spacing(3) .align_items(Align::Center); let author_container = Container::new(author_row) .height(default_height) .width(*width) .center_y() .style(style::HoverableForegroundContainer(color_palette)); row_containers.push((idx, author_container)); } if let Some((idx, width)) = column_config .iter() .enumerate() .filter_map(|(idx, (key, width, hidden))| {
}) .next() { let status = Text::new(aura.status().to_string()).size(DEFAULT_FONT_SIZE); let status_row = Row::new() .push(status) .spacing(3) .align_items(Align::Center); let status_container = Container::new(status_row) .height(default_height) .width(*width) .center_y() .style(style::HoverableForegroundContainer(color_palette)); row_containers.push((idx, status_container)); } let left_spacer = Space::new(Length::Units(DEFAULT_PADDING), Length::Units(0)); let right_spacer = Space::new(Length::Units(DEFAULT_PADDING + 5), Length::Units(0)); let mut row = Row::new().push(left_spacer).spacing(1); row_containers.sort_by(|a, b| a.0.cmp(&b.0)); for (_, elem) in row_containers.into_iter() { row = row.push(elem); } row = row.push(right_spacer); let mut table_row = TableRow::new(row) .width(Length::Fill) .inner_row_height(default_row_height); if let Some(url) = aura.url() { table_row = table_row .on_press(move |_| Message::Interaction(Interaction::OpenLink(url.to_string()))); } if is_odd == Some(true) { table_row = table_row.style(style::TableRowAlternate(color_palette)) } else { table_row = table_row.style(style::TableRow(color_palette)) } table_row } fn row_title<T: PartialEq>( column_key: T, previous_column_key: Option<T>, previous_sort_direction: Option<SortDirection>, title: &str, ) -> String { if Some(column_key) == previous_column_key { match previous_sort_direction { Some(SortDirection::Asc) => format!("{} ▲", title), Some(SortDirection::Desc) => format!("{} ▼", title), _ => title.to_string(), } } else { title.to_string() } } pub fn titles_row_header<'a>( color_palette: ColorPalette, auras: &[Aura], header_state: &'a mut header::State, column_state: &'a mut [AuraColumnState], previous_column_key: Option<AuraColumnKey>, previous_sort_direction: Option<SortDirection>, ) -> Header<'a, Message> { let mut row_titles = vec![]; for column in column_state.iter_mut().filter(|c| !c.hidden) { let column_key = column.key; let row_title = row_title( column_key, previous_column_key, previous_sort_direction, &column.key.title(), ); let mut row_header = Button::new( &mut column.btn_state, Text::new(row_title) .size(DEFAULT_FONT_SIZE) .width(Length::Fill), ) .width(Length::Fill) .on_press(Interaction::SortAuraColumn(column_key)); if previous_column_key == Some(column_key) { row_header = row_header.style(style::SelectedColumnHeaderButton(color_palette)); } else { row_header = row_header.style(style::ColumnHeaderButton(color_palette)); } let row_header: Element<Interaction> = row_header.into(); let row_container = Container::new(row_header.map(Message::Interaction)) .width(column.width) .style(style::NormalBackgroundContainer(color_palette)); if !auras.is_empty() { row_titles.push((column.key.as_string(), row_container)); } } Header::new( header_state, row_titles, Some(Length::Units(DEFAULT_PADDING)), Some(Length::Units(DEFAULT_PADDING + 5)), ) .spacing(1) .height(Length::Units(25)) .on_resize(3, |event| { Message::Interaction(Interaction::ResizeColumn( Mode::MyWeakAuras(Flavor::default()), event, )) }) }
if *key == AuraColumnKey::Status && !hidden { Some((idx, width)) } else { None }
if_condition
[ { "content": "fn sort_auras(auras: &mut [Aura], sort_direction: SortDirection, column_key: AuraColumnKey) {\n\n match (column_key, sort_direction) {\n\n (AuraColumnKey::Title, SortDirection::Asc) => {\n\n auras.sort_by(|a, b| a.name().to_lowercase().cmp(&b.name().to_lowercase()));\n\n ...
Rust
mm0-rs/components/mmcc/src/mir_opt/ghost.rs
RESEARCHINGETERNITYEGPHILIPPOV/mm0
a4fff5c90f5787aacef23f2b5f0c9e064379658d
use std::{collections::HashSet, mem}; #[allow(clippy::wildcard_imports)] use super::*; #[repr(u8)] #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] pub enum Reachability { Dead, Unreachable, Reachable, } impl Default for Reachability { fn default() -> Self { Self::Dead } } impl Reachability { #[inline] #[must_use] pub fn reach(self) -> bool { matches!(self, Self::Reachable) } #[inline] #[must_use] pub fn dead(self) -> bool { matches!(self, Self::Dead) } } impl Domain for Reachability { fn join(&mut self, &other: &Self) -> bool { *self < other && { *self = other; true } } } #[derive(Debug)] pub struct GhostAnalysisResult(BlockVec<im::HashSet<VarId>>); impl Cfg { #[must_use] pub fn reachability_analysis(&self) -> BlockVec<Reachability> { struct ReachabilityAnalysis; fn side_effecting(t: &Terminator) -> bool { matches!(t, Terminator::Return(_) | Terminator::Exit(_) | Terminator::Assert(_, _, _, _) | Terminator::Call {se: true, ..}) } impl Analysis for ReachabilityAnalysis { type Dir = Backward; type Doms = BlockVec<Reachability>; fn bottom(&mut self, cfg: &Cfg) -> Self::Doms { BlockVec::bottom(cfg.blocks.len()) } fn apply_trans_for_block(&mut self, _: &Self::Doms, _: BlockId, bl: &BasicBlock, d: &mut Reachability ) { if side_effecting(bl.terminator()) { *d = Reachability::Reachable } } } let mut queue = WorkQueue::with_capacity(self.blocks.len()); let mut reachable = ReachabilityAnalysis.bottom(self); Backward::preferred_traverse(self, |id, _| { reachable[id] = Reachability::Unreachable; queue.insert(id); }); ReachabilityAnalysis.iterate_to_fixpoint_from(self, &mut queue, &mut reachable); for (i, d) in reachable.enum_iter_mut() { if *d != Reachability::Dead && side_effecting(self[i].terminator()) { *d = Reachability::Reachable } } reachable } pub fn apply_reachability_analysis(&mut self, reachable: &BlockVec<Reachability>) { for id in (0..self.blocks.len()).map(BlockId::from_usize) { let mut bl = &mut self.blocks[id]; match reachable[id] { Reachability::Dead => { *bl = BasicBlock::DEAD; continue } Reachability::Unreachable => { bl.reachable = false; continue } Reachability::Reachable => {} } match bl.term.as_mut() { Some(Terminator::Assert(_, _, reach, tgt) | Terminator::Call {reach, tgt, ..}) => *reach = reachable[*tgt].reach(), Some(&mut Terminator::If(_, [(_, tgt1), (_, tgt2)])) => { let reach1 = reachable[tgt1].reach(); if reach1 == reachable[tgt2].reach() { continue } let_unchecked!(Some(Terminator::If(_, [mut vtgt1, mut vtgt2])) = bl.term.take(), { if reach1 { mem::swap(&mut vtgt1, &mut vtgt2) } let (_, ty1) = &self.ctxs.head(self[vtgt1.1].ctx).2; let (e2, ty2) = &self.ctxs.head(self[vtgt2.1].ctx).2; bl = &mut self.blocks[id]; bl.stmts.push(Statement::Let( LetKind::Let(vtgt2.0, false, e2.clone()), ty2.clone(), Constant::contra(ty1.clone(), tgt1, vtgt1.0).into() )); bl.term = Some(Terminator::Jump1(tgt2)); }); } _ => {} } } } #[must_use] pub fn can_return(&self) -> bool { struct ReturnAnalysis; impl Analysis for ReturnAnalysis { type Dir = Backward; type Doms = BitSet<BlockId>; fn bottom(&mut self, cfg: &Cfg) -> Self::Doms { BitSet::bottom(cfg.blocks.len()) } fn apply_trans_for_block(&mut self, _: &Self::Doms, _: BlockId, bl: &BasicBlock, d: &mut bool) { match *bl.terminator() { Terminator::Return(_) | Terminator::Exit(_) => *d = true, Terminator::Assert(_, _, false, _) | Terminator::Call {reach: false, ..} => *d = false, Terminator::Assert(..) | Terminator::Call {..} | Terminator::Unreachable(_) | Terminator::Dead | Terminator::Jump(..) | Terminator::Jump1(..) | Terminator::If(..) => {} } } } let doms = ReturnAnalysis.iterate_to_fixpoint(self); ReturnAnalysis.get_applied(self, &doms, BlockId::ENTRY) } #[must_use] pub fn ghost_analysis(&self, reachable: &BlockVec<Reachability>, returns: &[Arg], ) -> GhostAnalysisResult { #[derive(Default)] struct GhostDom { active: OptBlockId, vars: im::HashSet<VarId>, } impl GhostDom { #[inline] fn apply_local(&mut self, v: VarId) { self.vars.insert(v); } #[inline] fn apply_place(&mut self, p: &Place) { self.apply_local(p.local) } fn apply_operand(&mut self, o: &Operand) { if let Operand::Copy(p) | Operand::Move(p) | Operand::Ref(p) = o { self.apply_place(p) } } fn apply_rvalue(&mut self, id: BlockId, rv: &RValue) { match rv { RValue::Use(o) => self.apply_operand(o), RValue::Unop(_, o) | RValue::Cast(_, o, _) => { self.active = OptBlockId::new(id); self.apply_operand(o) } RValue::Binop(_, o1, o2) | RValue::Eq(_, _, o1, o2) => { self.active = OptBlockId::new(id); self.apply_operand(o1); self.apply_operand(o2) } RValue::Pun(_, p) | RValue::Borrow(p) => self.apply_place(p), RValue::List(os) | RValue::Array(os) => { self.active = OptBlockId::new(id); for o in &**os { self.apply_operand(o) } } RValue::Ghost(_) | RValue::Mm0(..) | RValue::Typeof(_) => {} } } } struct GhostAnalysis<'a> { reachable: &'a BlockVec<Reachability>, returns: &'a [Arg], } struct GhostDoms { active: BlockVec<OptBlockId>, vars: BlockVec<im::HashSet<VarId>>, } impl Domains for GhostDoms { type Item = GhostDom; fn cloned(&self, id: BlockId) -> Self::Item { GhostDom { active: self.active[id], vars: self.vars.cloned(id), } } fn join(&mut self, id: BlockId, &GhostDom {active, ref vars}: &GhostDom) -> bool { let cur = &mut self.active[id]; let changed = match (cur.get(), active.get()) { (None, Some(_)) => { *cur = active; true } (Some(a), Some(b)) if a != b && a != id => { *cur = OptBlockId::new(id); true } _ => false, }; changed | self.vars.join(id, vars) } } impl<'a> Analysis for GhostAnalysis<'a> { type Dir = Backward; type Doms = GhostDoms; fn bottom(&mut self, cfg: &Cfg) -> Self::Doms { GhostDoms { active: BlockVec::bottom(cfg.blocks.len()), vars: BlockVec::bottom(cfg.blocks.len()), } } fn apply_statement(&mut self, _: &Self::Doms, loc: Location, stmt: &Statement, d: &mut GhostDom) { match stmt { Statement::Let(lk, _, rv) => { let needed = match *lk { LetKind::Let(v, vr, _) => vr && d.vars.contains(&v), LetKind::Own([(x, xr, _), (y, yr, _)]) => xr && d.vars.contains(&x) || yr && d.vars.contains(&y) }; if needed { d.apply_rvalue(loc.block, rv) } } Statement::Assign(_, _, rhs, vars) => { let mut needed = false; for v in &**vars { if v.rel && d.vars.contains(&v.to) { needed = true; d.apply_local(v.from); } } if needed { d.active = OptBlockId::new(loc.block); d.apply_operand(rhs) } } } } fn apply_terminator(&mut self, _: &Self::Doms, id: BlockId, term: &Terminator, d: &mut GhostDom) { match term { Terminator::Jump(_, args, _) => { let GhostDom {vars, ..} = mem::take(d); for &(v, vr, ref o) in args { if vr && vars.contains(&v) { d.active = OptBlockId::new(id); d.apply_operand(o) } } } Terminator::Jump1(_) | Terminator::Exit(_) => {} Terminator::Return(args) => { d.active = OptBlockId::new(id); for ((_, vr, o), ret) in args.iter().zip(self.returns) { if *vr && !ret.attr.contains(ArgAttr::GHOST) { d.apply_operand(o) } } } Terminator::Unreachable(_) | Terminator::Dead => unreachable!(), Terminator::If(o, _) => if d.active == OptBlockId::new(id) { d.apply_operand(o) } Terminator::Assert(o, _, _, _) => { d.active = OptBlockId::new(id); d.apply_operand(o) } &Terminator::Call {se: side_effect, ref args, reach, ref rets, ..} => { let needed = !reach || side_effect || rets.iter().any(|&(vr, v)| vr && d.vars.contains(&v)); if needed { d.active = OptBlockId::new(id); for &(r, ref o) in &**args { if r { d.apply_operand(o) } } } } } } fn apply_trans_for_block(&mut self, ds: &Self::Doms, id: BlockId, bl: &BasicBlock, d: &mut GhostDom) { if !self.reachable[id].reach() { *d = Default::default(); return } self.do_apply_trans_for_block(ds, id, bl, d) } } let mut analysis = GhostAnalysis { reachable, returns }; let result = analysis.iterate_to_fixpoint(self); GhostAnalysisResult((0..self.blocks.len()).map(BlockId::from_usize).map(|id| { analysis.get_applied(self, &result, id).vars }).collect()) } pub fn apply_ghost_analysis(&mut self, res: &GhostAnalysisResult, returns: &[Arg], ) { self.ctxs.reset_ghost(); for (id, res) in res.0.enum_iter() { let bl = &mut self.blocks[id]; if bl.is_dead() { continue } bl.relevance = Some(self.ctxs.set_ghost(bl.ctx, |v| res.contains(&v))); let get = |v| res.contains(&v); for stmt in &mut bl.stmts { match stmt { Statement::Let(LetKind::Let(v, r, _), _, _) => *r = get(*v), Statement::Let(LetKind::Own(vs), _, _) => for (v, r, _) in vs { *r = get(*v) } Statement::Assign(_, _, _, vs) => for v in &mut **vs { v.rel = get(v.to) } } } } let mut cache = BlockVec::<Option<HashSet<VarId>>>::from_default(self.blocks.len()); let Cfg {ctxs, blocks, ..} = self; for i in 0..blocks.len() { let blocks = &mut *blocks.0; if let Some(Terminator::Jump(tgt, ref mut args, _)) = blocks[i].term { let tgt_ctx = blocks[tgt.0 as usize].ctx; let s = cache[tgt].get_or_insert_with(|| { ctxs.rev_iter(tgt_ctx).filter(|p| p.1).map(|p| p.0).collect() }); for (v, r, _) in args { *r = s.contains(v) } } } } pub fn do_ghost_analysis(&mut self, reachable: &BlockVec<Reachability>, returns: &[Arg], ) { let ghost = self.ghost_analysis(reachable, returns); self.apply_ghost_analysis(&ghost, returns); } }
use std::{collections::HashSet, mem}; #[allow(clippy::wildcard_imports)] use super::*; #[repr(u8)] #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] pub enum Reachability { Dead, Unreachable, Reachable, } impl Default for Reachability { fn default() -> Self { Self::Dead } } impl Reachability { #[inline] #[must_use] pub fn reach(self) -> bool { matches!(self, Self::Reachable) } #[inline] #[must_use] pub fn dead(self) -> bool { matches!(self, Self::Dead) } } impl Domain for Reachability { fn join(&mut self, &other: &Self) -> bool { *self < other && { *self = other; true } } } #[derive(Debug)] pub struct GhostAnalysisResult(BlockVec<im::HashSet<VarId>>); impl Cfg { #[must_use] pub fn reachability_analysis(&self) -> BlockVec<Reachability> { struct ReachabilityAnalysis; fn side_effecting(t: &Terminator) -> bool { matches!(t, Terminator::Return(_) | Terminator::Exit(_) | Terminator::Assert(_, _, _, _) | Terminator::Call {se: true, ..}) } impl Analysis for ReachabilityAnalysis { type Dir = Backward; type Doms = BlockVec<Reachability>; fn bottom(&mut self, cfg: &Cfg) -> Self::Doms { BlockVec::bottom(cfg.blocks.len()) } fn apply_trans_for_block(&mut self, _: &Self::Doms, _: BlockId, bl: &BasicBlock, d: &mut Reachability ) { if side_effecting(bl.terminator()) { *d = Reachability::Reachable } } } let mut queue = WorkQueue::with_capacity(self.blocks.len()); let mut reachable = ReachabilityAnalysis.bottom(self); Backward::preferred_traverse(self, |id, _| { reachable[id] = Reachability::Unreachable; queue.insert(id); }); ReachabilityAnalysis.iterate_to_fixpoint_from(self, &mut queue, &mut reachable); for (i, d) in reachable.enum_iter_mut() { if *d != Reachability::Dead && side_effecting(self[i].terminator()) { *d = Reachability::Reachable } } reachable } pub fn apply_reachability_analysis(&mut self, reachable: &BlockVec<Reachability>) { for id in (0..self.blocks.len()).map(BlockId::from_usize) { let mut bl = &mut self.blocks[id]; match reachable[id] { Reachability::Dead => { *bl = BasicBlock::DEAD; continue } Reachability::Unreachable => { bl.reachable = false; continue } Reachability::Reachable => {} } match bl.term.as_mut() { Some(Terminator::Assert(_, _, reach, tgt) | Terminator::Call {reach, tgt, ..}) => *reach = reachable[*tgt].reach(), Some(&mut Terminator::If(_, [(_, tgt1), (_, tgt2)])) => { let reach1 = reachable[tgt1].reach(); if reach1 == reachable[tgt2].reach() { continue } let_unchecked!(Some(Terminator::If(_, [mut vtgt1, mut vtgt2])) = bl.term.take(), { if reach1 { mem::swap(&mut vtgt1, &mut vtgt2) } let (_, ty1) = &self.ctxs.head(self[vtgt1.1].ctx).2; let (e2, ty2) = &self.ctxs.head(self[vtgt2.1].ctx).2; bl = &mut self.blocks[id]; bl.stmts.push(Statement::Let( LetKind::Let(vtgt2.0, false, e2.clone()), ty2.clone(), Constant::contra(ty1.clone(), tgt1, vtgt1.0).into() )); bl.term = Some(Terminator::Jump1(tgt2)); }); } _ => {} } } } #[must_use] pub fn can_return(&self) -> bool { struct ReturnAnalysis; impl Analysis for ReturnAnalysis { type Dir = Backward; type Doms = BitSet<BlockId>; fn bottom(&mut self, cfg: &Cfg) -> Self::Doms { BitSet::bottom(cfg.blocks.len()) } fn apply_trans_for_block(&mut self, _: &Self::Doms, _: BlockId, bl: &BasicBlock, d: &mut bool) { match *bl.terminator() { Terminator::Return(_) | Terminator::Exit(_) => *d = true, Terminator::Assert(_, _, false, _) | Terminator::Call {reach: false, ..} => *d = false, Terminator::Assert(..) | Terminator::Call {..} | Terminator::Unreachable(_) | Terminator::Dead | Terminator::Jump(..) | Terminator::Jump1(..) | Terminator::If(..) => {} } } } let doms = ReturnAnalysis.iterate_to_fixpoint(self); ReturnAnalysis.get_applied(self, &doms, BlockId::ENTRY) } #[must_use] pub fn ghost_analysis(&self, reachable: &BlockVec<Reachability>, returns: &[Arg], ) -> GhostAnalysisResult { #[derive(Default)] struct GhostDom { active: OptBlockId, vars: im::HashSet<VarId>, } impl GhostDom { #[inline] fn apply_local(&mut self, v: VarId) { self.vars.insert(v); } #[inline] fn apply_place(&mut self, p: &Place) { self.apply_local(p.local) } fn apply_operand(&mut self, o: &Operand) { if let Operand::Copy(p) | Operand::Move(p) | Operand::Ref(p) = o { self.apply_place(p) } } fn apply_rvalue(&mut self, id: BlockId, rv: &RValue) { match rv { RValue::Use(o) => self.apply_operand(o), RValue::Unop(_, o) | RValue::Cast(_, o, _) => { self.active = OptBlockId::new(id); self.apply_operand(o) } RValue::Binop(_, o1, o2) | RValue::Eq(_, _, o1, o2) => { self.active = OptBlockId::new(id); self.apply_operand(o1); self.apply_operand(o2) } RValue::Pun(_, p) | RValue::Borrow(p) => self.apply_place(p), RValue::List(os) | RValue::Array(os) => { self.active = OptBlockId::new(id); for o in &**os { self.apply_operand(o) } } RValue::Ghost(_) | RValue::Mm0(..) | RValue
.rev_iter(tgt_ctx).filter(|p| p.1).map(|p| p.0).collect() }); for (v, r, _) in args { *r = s.contains(v) } } } } pub fn do_ghost_analysis(&mut self, reachable: &BlockVec<Reachability>, returns: &[Arg], ) { let ghost = self.ghost_analysis(reachable, returns); self.apply_ghost_analysis(&ghost, returns); } }
::Typeof(_) => {} } } } struct GhostAnalysis<'a> { reachable: &'a BlockVec<Reachability>, returns: &'a [Arg], } struct GhostDoms { active: BlockVec<OptBlockId>, vars: BlockVec<im::HashSet<VarId>>, } impl Domains for GhostDoms { type Item = GhostDom; fn cloned(&self, id: BlockId) -> Self::Item { GhostDom { active: self.active[id], vars: self.vars.cloned(id), } } fn join(&mut self, id: BlockId, &GhostDom {active, ref vars}: &GhostDom) -> bool { let cur = &mut self.active[id]; let changed = match (cur.get(), active.get()) { (None, Some(_)) => { *cur = active; true } (Some(a), Some(b)) if a != b && a != id => { *cur = OptBlockId::new(id); true } _ => false, }; changed | self.vars.join(id, vars) } } impl<'a> Analysis for GhostAnalysis<'a> { type Dir = Backward; type Doms = GhostDoms; fn bottom(&mut self, cfg: &Cfg) -> Self::Doms { GhostDoms { active: BlockVec::bottom(cfg.blocks.len()), vars: BlockVec::bottom(cfg.blocks.len()), } } fn apply_statement(&mut self, _: &Self::Doms, loc: Location, stmt: &Statement, d: &mut GhostDom) { match stmt { Statement::Let(lk, _, rv) => { let needed = match *lk { LetKind::Let(v, vr, _) => vr && d.vars.contains(&v), LetKind::Own([(x, xr, _), (y, yr, _)]) => xr && d.vars.contains(&x) || yr && d.vars.contains(&y) }; if needed { d.apply_rvalue(loc.block, rv) } } Statement::Assign(_, _, rhs, vars) => { let mut needed = false; for v in &**vars { if v.rel && d.vars.contains(&v.to) { needed = true; d.apply_local(v.from); } } if needed { d.active = OptBlockId::new(loc.block); d.apply_operand(rhs) } } } } fn apply_terminator(&mut self, _: &Self::Doms, id: BlockId, term: &Terminator, d: &mut GhostDom) { match term { Terminator::Jump(_, args, _) => { let GhostDom {vars, ..} = mem::take(d); for &(v, vr, ref o) in args { if vr && vars.contains(&v) { d.active = OptBlockId::new(id); d.apply_operand(o) } } } Terminator::Jump1(_) | Terminator::Exit(_) => {} Terminator::Return(args) => { d.active = OptBlockId::new(id); for ((_, vr, o), ret) in args.iter().zip(self.returns) { if *vr && !ret.attr.contains(ArgAttr::GHOST) { d.apply_operand(o) } } } Terminator::Unreachable(_) | Terminator::Dead => unreachable!(), Terminator::If(o, _) => if d.active == OptBlockId::new(id) { d.apply_operand(o) } Terminator::Assert(o, _, _, _) => { d.active = OptBlockId::new(id); d.apply_operand(o) } &Terminator::Call {se: side_effect, ref args, reach, ref rets, ..} => { let needed = !reach || side_effect || rets.iter().any(|&(vr, v)| vr && d.vars.contains(&v)); if needed { d.active = OptBlockId::new(id); for &(r, ref o) in &**args { if r { d.apply_operand(o) } } } } } } fn apply_trans_for_block(&mut self, ds: &Self::Doms, id: BlockId, bl: &BasicBlock, d: &mut GhostDom) { if !self.reachable[id].reach() { *d = Default::default(); return } self.do_apply_trans_for_block(ds, id, bl, d) } } let mut analysis = GhostAnalysis { reachable, returns }; let result = analysis.iterate_to_fixpoint(self); GhostAnalysisResult((0..self.blocks.len()).map(BlockId::from_usize).map(|id| { analysis.get_applied(self, &result, id).vars }).collect()) } pub fn apply_ghost_analysis(&mut self, res: &GhostAnalysisResult, returns: &[Arg], ) { self.ctxs.reset_ghost(); for (id, res) in res.0.enum_iter() { let bl = &mut self.blocks[id]; if bl.is_dead() { continue } bl.relevance = Some(self.ctxs.set_ghost(bl.ctx, |v| res.contains(&v))); let get = |v| res.contains(&v); for stmt in &mut bl.stmts { match stmt { Statement::Let(LetKind::Let(v, r, _), _, _) => *r = get(*v), Statement::Let(LetKind::Own(vs), _, _) => for (v, r, _) in vs { *r = get(*v) } Statement::Assign(_, _, _, vs) => for v in &mut **vs { v.rel = get(v.to) } } } } let mut cache = BlockVec::<Option<HashSet<VarId>>>::from_default(self.blocks.len()); let Cfg {ctxs, blocks, ..} = self; for i in 0..blocks.len() { let blocks = &mut *blocks.0; if let Some(Terminator::Jump(tgt, ref mut args, _)) = blocks[i].term { let tgt_ctx = blocks[tgt.0 as usize].ctx; let s = cache[tgt].get_or_insert_with(|| { ctxs
random
[ { "content": "/// Performs \"curly transformation\", turning `{x op y op z}` into `(op x y z)`.\n\n///\n\n/// A curly list is valid if\n\n/// - it is a proper list, and\n\n/// - it has at most two elements (in which case it is transformed to itself), or\n\n/// - it has an odd number of elements and the elements...
Rust
src/main.rs
magicgoose/oxipng
a857cfcc1e4379434c1848a58578e94ed231845a
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", warn(enum_glob_use))] #![cfg_attr(feature = "clippy", warn(if_not_else))] #![cfg_attr(feature = "clippy", warn(string_add))] #![cfg_attr(feature = "clippy", warn(string_add_assign))] #![warn(trivial_casts, trivial_numeric_casts, unused_import_braces)] #![deny(missing_debug_implementations, missing_copy_implementations)] extern crate clap; extern crate glob; extern crate oxipng; extern crate regex; use clap::{App, Arg, ArgMatches}; use glob::glob; use oxipng::AlphaOptim; use oxipng::Deflaters; use oxipng::Headers; use oxipng::{Options, PngError}; use regex::Regex; use std::collections::HashSet; use std::fs::DirBuilder; use std::path::PathBuf; use std::process::exit; fn main() { let matches = App::new("oxipng") .version(env!("CARGO_PKG_VERSION")) .author("Joshua Holmer <jholmer.in@gmail.com>") .about("Losslessly improves compression of PNG files") .arg(Arg::with_name("files") .help("File(s) to compress") .index(1) .multiple(true) .use_delimiter(false) .required(true)) .arg(Arg::with_name("optimization") .help("Optimization level - Default: 2") .short("o") .long("opt") .takes_value(true) .possible_value("0") .possible_value("1") .possible_value("2") .possible_value("3") .possible_value("4") .possible_value("5") .possible_value("6")) .arg(Arg::with_name("backup") .help("Back up modified files") .short("b") .long("backup")) .arg(Arg::with_name("force") .help("Write output even if larger than the original") .short("F") .long("force")) .arg(Arg::with_name("recursive") .help("Recurse into subdirectories") .short("r") .long("recursive")) .arg(Arg::with_name("output_dir") .help("Write output file(s) to <directory>") .long("dir") .takes_value(true) .conflicts_with("output_file") .conflicts_with("stdout")) .arg(Arg::with_name("output_file") .help("Write output file to <file>") .long("out") .takes_value(true) .conflicts_with("output_dir") .conflicts_with("stdout")) .arg(Arg::with_name("stdout") .help("Write output to stdout") .long("stdout") .conflicts_with("output_dir") .conflicts_with("output_file")) .arg(Arg::with_name("fix") .help("Enable error recovery") .long("fix")) .arg(Arg::with_name("no-clobber") .help("Do not overwrite existing files") .long("no-clobber")) .arg(Arg::with_name("pretend") .help("Do not write any files, only calculate compression gains") .short("P") .long("pretend")) .arg(Arg::with_name("preserve") .help("Preserve file attributes if possible") .short("p") .long("preserve")) .arg(Arg::with_name("quiet") .help("Run in quiet mode") .short("q") .long("quiet") .conflicts_with("verbose")) .arg(Arg::with_name("verbose") .help("Run in verbose mode") .short("v") .long("verbose") .conflicts_with("quiet")) .arg(Arg::with_name("filters") .help("PNG delta filters (0-5) - Default: 0,5") .short("f") .long("filters") .takes_value(true) .validator(|x| { match parse_numeric_range_opts(&x, 0, 5) { Ok(_) => Ok(()), Err(_) => Err("Invalid option for filters".to_owned()), } })) .arg(Arg::with_name("interlace") .help("PNG interlace type") .short("i") .long("interlace") .takes_value(true) .possible_value("0") .possible_value("1")) .arg(Arg::with_name("compression") .help("zlib compression levels (1-9) - Default: 9") .long("zc") .takes_value(true) .validator(|x| { match parse_numeric_range_opts(&x, 1, 9) { Ok(_) => Ok(()), Err(_) => Err("Invalid option for compression".to_owned()), } })) .arg(Arg::with_name("strategies") .help("zlib compression strategies (0-3) - Default: 0-3") .long("zs") .takes_value(true) .validator(|x| { match parse_numeric_range_opts(&x, 0, 3) { Ok(_) => Ok(()), Err(_) => Err("Invalid option for strategies".to_owned()), } })) .arg(Arg::with_name("window") .help("zlib window size - Default: 32k") .long("zw") .takes_value(true) .possible_value("256") .possible_value("512") .possible_value("1k") .possible_value("2k") .possible_value("4k") .possible_value("8k") .possible_value("16k") .possible_value("32k")) .arg(Arg::with_name("alpha") .help("Perform additional alpha optimizations") .short("a") .long("alpha")) .arg(Arg::with_name("no-bit-reduction") .help("No bit depth reduction") .long("nb")) .arg(Arg::with_name("no-color-reduction") .help("No color type reduction") .long("nc")) .arg(Arg::with_name("no-palette-reduction") .help("No palette reduction") .long("np")) .arg(Arg::with_name("no-reductions") .help("No reductions") .long("nx")) .arg(Arg::with_name("no-recoding") .help("No IDAT recoding unless necessary") .long("nz")) .arg(Arg::with_name("strip") .help("Strip metadata objects ['safe', 'all', or comma-separated list]") .long("strip") .takes_value(true) .conflicts_with("strip-safe")) .arg(Arg::with_name("strip-safe") .help("Strip safely-removable metadata objects") .short("s") .conflicts_with("strip")) .arg(Arg::with_name("zopfli") .help("Use the slower but better compressing Zopfli algorithm, overrides zlib-specific options") .short("Z") .long("zopfli")) .arg(Arg::with_name("threads") .help("Set number of threads to use - default 1.5x CPU cores") .long("threads") .short("t") .takes_value(true) .validator(|x| { match x.parse::<usize>() { Ok(val) => { if val > 0 { Ok(()) } else { Err("Thread count must be >= 1".to_owned()) } } Err(_) => Err("Thread count must be >= 1".to_owned()), } })) .after_help("Optimization levels: -o 0 => --zc 3 --nz (0 or 1 trials) -o 1 => --zc 9 (1 trial, determined heuristically) -o 2 => --zc 9 --zs 0-3 -f 0,5 (8 trials) -o 3 => --zc 9 --zs 0-3 -f 0-5 (24 trials) -o 4 => --zc 9 --zs 0-3 -f 0-5 -a (24 trials + 6 alpha trials) -o 5 => --zc 3-9 --zs 0-3 -f 0-5 -a (96 trials + 6 alpha trials) -o 6 => --zc 1-9 --zs 0-3 -f 0-5 -a (180 trials + 6 alpha trials) Manually specifying a compression option (zc, zs, etc.) will override the optimization preset, regardless of the order you write the arguments.") .get_matches(); let opts = match parse_opts_into_struct(&matches) { Ok(x) => x, Err(x) => { eprintln!("{}", x); exit(1) } }; if let Err(e) = handle_optimization( matches .values_of("files") .unwrap() .map(|pattern| glob(pattern).expect("Failed to parse input file path")) .flat_map(|paths| { paths .into_iter() .map(|path| path.expect("Failed to parse input file path")) }) .collect(), &opts, ) { eprintln!("{}", e); exit(1); } } fn handle_optimization(inputs: Vec<PathBuf>, opts: &Options) -> Result<(), PngError> { inputs.into_iter().fold(Ok(()), |res, input| { let mut current_opts = opts.clone(); if input.is_dir() { if current_opts.recursive { let cur_result = handle_optimization( input .read_dir() .unwrap() .map(|x| x.unwrap().path()) .collect(), &current_opts, ); return res.and(cur_result); } else { eprintln!("{} is a directory, skipping", input.display()); } return res; } if let Some(ref out_dir) = current_opts.out_dir { current_opts.out_file = Some(out_dir.join(input.file_name().unwrap())); } let cur_result = oxipng::optimize(&input, &current_opts); res.and(cur_result) }) } #[cfg_attr(feature = "clippy", allow(cyclomatic_complexity))] fn parse_opts_into_struct(matches: &ArgMatches) -> Result<Options, String> { let mut opts = if let Some(x) = matches.value_of("optimization") { if let Ok(opt) = x.parse::<u8>() { Options::from_preset(opt) } else { unreachable!() } } else { Options::default() }; if let Some(x) = matches.value_of("interlace") { opts.interlace = x.parse::<u8>().ok(); } if let Some(x) = matches.value_of("filters") { opts.filter = parse_numeric_range_opts(x, 0, 5).unwrap(); } if let Some(x) = matches.value_of("compression") { opts.compression = parse_numeric_range_opts(x, 1, 9).unwrap(); } if let Some(x) = matches.value_of("strategies") { opts.strategies = parse_numeric_range_opts(x, 0, 3).unwrap(); } match matches.value_of("window") { Some("256") => opts.window = 8, Some("512") => opts.window = 9, Some("1k") => opts.window = 10, Some("2k") => opts.window = 11, Some("4k") => opts.window = 12, Some("8k") => opts.window = 13, Some("16k") => opts.window = 14, _ => (), } if let Some(x) = matches.value_of("output_dir") { let path = PathBuf::from(x); if !path.exists() { match DirBuilder::new().recursive(true).create(&path) { Ok(_) => (), Err(x) => return Err(format!("Could not create output directory {}", x)), }; } else if !path.is_dir() { return Err(format!( "{} is an existing file (not a directory), cannot create directory", x )); } opts.out_dir = Some(path); } if let Some(x) = matches.value_of("output_file") { opts.out_file = Some(PathBuf::from(x)); } if matches.is_present("stdout") { opts.stdout = true; } if matches.is_present("alpha") { opts.alphas.insert(AlphaOptim::White); opts.alphas.insert(AlphaOptim::Up); opts.alphas.insert(AlphaOptim::Down); opts.alphas.insert(AlphaOptim::Left); opts.alphas.insert(AlphaOptim::Right); } if matches.is_present("backup") { opts.backup = true; } if matches.is_present("force") { opts.force = true; } if matches.is_present("recursive") { opts.recursive = true; } if matches.is_present("fix") { opts.fix_errors = true; } if matches.is_present("clobber") { opts.clobber = false; } if matches.is_present("pretend") { opts.pretend = true; } if matches.is_present("preserve") { opts.preserve_attrs = true; } if matches.is_present("quiet") { opts.verbosity = None; } if matches.is_present("verbose") { opts.verbosity = Some(1); } if matches.is_present("no-bit-reduction") { opts.bit_depth_reduction = false; } if matches.is_present("no-color-reduction") { opts.color_type_reduction = false; } if matches.is_present("no-palette-reduction") { opts.palette_reduction = false; } if matches.is_present("no-reductions") { opts.bit_depth_reduction = false; opts.color_type_reduction = false; opts.palette_reduction = false; } if matches.is_present("no-recoding") { opts.idat_recoding = false; } if let Some(hdrs) = matches.value_of("strip") { let hdrs = hdrs.split(',') .map(|x| x.trim().to_owned()) .collect::<Vec<String>>(); if hdrs.contains(&"safe".to_owned()) || hdrs.contains(&"all".to_owned()) { if hdrs.len() > 1 { return Err( "'safe' or 'all' presets for --strip should be used by themselves".to_owned(), ); } if hdrs[0] == "safe" { opts.strip = Headers::Safe; } else { opts.strip = Headers::All; } } else { const FORBIDDEN_CHUNKS: [&str; 5] = ["IHDR", "IDAT", "tRNS", "PLTE", "IEND"]; for i in &hdrs { if FORBIDDEN_CHUNKS.contains(&i.as_ref()) { return Err(format!("{} chunk is not allowed to be stripped", i)); } } opts.strip = Headers::Some(hdrs); } } if matches.is_present("strip-safe") { opts.strip = Headers::Safe; } if matches.is_present("zopfli") { opts.deflate = Deflaters::Zopfli; } if let Some(x) = matches.value_of("threads") { opts.threads = x.parse::<usize>().unwrap(); } Ok(opts) } fn parse_numeric_range_opts( input: &str, min_value: u8, max_value: u8, ) -> Result<HashSet<u8>, String> { let one_item = Regex::new(format!(r"^[{}-{}]$", min_value, max_value).as_ref()).unwrap(); let multiple_items = Regex::new( format!( r"^([{}-{}])(,|-)([{}-{}])$", min_value, max_value, min_value, max_value ).as_ref(), ).unwrap(); let mut items = HashSet::new(); if one_item.is_match(input) { items.insert(input.parse::<u8>().unwrap()); return Ok(items); } if let Some(captures) = multiple_items.captures(input) { let first = captures[1].parse::<u8>().unwrap(); let second = captures[3].parse::<u8>().unwrap(); if first >= second { return Err("Not a valid input".to_owned()); } match &captures[2] { "," => { items.insert(first); items.insert(second); } "-" => for i in first..second + 1 { items.insert(i); }, _ => unreachable!(), }; return Ok(items); } Err("Not a valid input".to_owned()) }
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", warn(enum_glob_use))] #![cfg_attr(feature = "clippy", warn(if_not_else))] #![cfg_attr(feature = "clippy", warn(string_add))] #![cfg_attr(feature = "clippy", warn(string_add_assign))] #![warn(trivial_casts, trivial_numeric_casts, unused_import_braces)] #![deny(missing_debug_implementations, missing_copy_implementations)] extern crate clap; extern crate glob; extern crate oxipng; extern crate regex; use clap::{App, Arg, ArgMatches}; use glob::glob; use oxipng::AlphaOptim; use oxipng::Deflaters; use oxipng::Headers; use oxipng::{Options, PngError}; use regex::Regex; use std::collections::HashSet; use std::fs::DirBuilder; use std::path::PathBuf; use std::process::exit; fn main() { let matches = App::new("oxipng") .version(env!("CARGO_PKG_VERSION")) .author("Joshua Holmer <jholmer.in@gmail.com>") .about("Losslessly improves compression of PNG files") .arg(Arg::with_name("files") .help("File(s) to compress") .index(1) .multiple(true) .use_delimiter(false) .required(true)) .arg(Arg::with_name("optimization") .help("Optimization level - Default: 2") .short("o") .long("opt") .takes_value(true) .possible_value("0") .possible_value("1") .possible_value("2") .possible_value("3") .possible_value("4") .possible_value("5") .possible_value("6")) .arg(Arg::with_name("backup") .help("Back up modified files") .short("b") .long("backup")) .arg(Arg::with_name("force") .help("Write output even if larger than the original") .short("F") .long("force")) .arg(Arg::with_name("recursive") .help("Recurse into subdirectories") .short("r") .long("recursive")) .arg(Arg::with_name("output_dir") .help("Write output file(s) to <directory>") .long("dir") .takes_value(true) .conflicts_with("output_file") .conflicts_with("stdout")) .arg(Arg::with_name("output_file") .help("Write output file to <file>") .long("out") .takes_value(true) .conflicts_with("output_dir") .conflicts_with("stdout")) .arg(Arg::with_name("stdout") .help("Write output to stdout") .long("stdout") .conflicts_with("output_dir") .conflicts_with("output_file")) .arg(Arg::with_name("fix") .help("Enable error recovery") .long("fix")) .arg(Arg::with_name("no-clobber") .help("Do not overwrite existing files") .long("no-clobber")) .arg(Arg::with_name("pretend") .help("Do not write any files, only calculate compression gains") .short("P") .long("pretend")) .arg(Arg::with_name("preserve") .help("Preserve file attributes if possible") .short("p") .long("preserve")) .arg(Arg::with_name("quiet") .help("Run in quiet mode") .short("q") .long("quiet") .conflicts_with("verbose")) .arg(Arg::with_name("verbose") .help("Run in verbose mode") .short("v") .long("verbose") .conflicts_with("quiet")) .arg(Arg::with_name("filters") .help("PNG delta filters (0-5) - Default: 0,5") .short("f") .long("filters") .takes_value(true) .validator(|x| { match parse_numeric_range_opts(&x, 0, 5) { Ok(_) => Ok(()), Err(_) => Err("Invalid option for filters".to_owned()), } })) .arg(Arg::with_name("interlace") .help("PNG interlace type") .short("i") .long("interlace") .takes_value(true) .possible_value("0") .possible_value("1")) .arg(Arg::with_name("compression") .help("zlib compression levels (1-9) - Default: 9") .long("zc") .takes_value(true) .validator(|x| { match parse_numeric_range_opts(&x, 1, 9) { Ok(_) => Ok(()), Err(_) => Err("Invalid option for compression".to_owned()), } })) .arg(Arg::with_name("strategies") .help("zlib compression strategies (0-3) - Default: 0-3") .long("zs") .takes_value(true) .validator(|x| { match parse_numeric_range_opts(&x, 0, 3) { Ok(_) => Ok(()), Err(_) => Err("Invalid option for strategies".to_owned()), } })) .arg(Arg::with_name("window") .help("zlib window size - Default: 32k") .long("zw") .takes_value(true) .possible_value("256") .possible_value("512") .possible_value("1k") .possible_value("2k") .possible_value("4k") .possible_value("8k") .possible_value("16k") .possible_value("32k")) .arg(Arg::with_name("alpha") .help("Perform additional alpha optimizations") .short("a") .long("alpha")) .arg(Arg::with_name("no-bit-reduction") .help("No bit depth reduction") .long("nb")) .arg(Arg::with_name("no-color-reduction") .help("No color type reduction") .long("nc")) .arg(Arg::with_name("no-palette-reduction") .help("No palette reduction") .long("np")) .arg(Arg::with_name("no-reductions") .help("No reductions") .long("nx")) .arg(Arg::with_name("no-recoding") .help("No IDAT recoding unless necessary") .long("nz")) .arg(Arg::with_name("strip") .help("Strip metadata objects ['safe', 'all', or comma-separated list]") .long("strip") .takes_value(true) .conflicts_with("strip-safe")) .arg(Arg::with_name("strip-safe") .help("Strip safely-removable metadata objects") .short("s") .conflicts_with("strip")) .arg(Arg::with_name("zopfli") .help("Use the slower but better compressing Zopfli algorithm, overrides zlib-specific options") .short("Z") .long("zopfli")) .arg(Arg::with_name("threads") .help("Set number of threads to use - default 1.5x CPU cores") .long("threads") .short("t") .takes_value(true) .validator(|x| { match x.parse::<usize>() { Ok(val) => { if val > 0 { Ok(()) } else { Err("Thread count must be >= 1".to_owned()) } } Err(_) => Err("Thread count must be >= 1".to_owned()), } })) .after_help("Optimization levels: -o 0 => --zc 3 --nz (0 or 1 trials) -o 1 => --zc 9 (1 trial, determined heuristically) -o 2 => --zc 9 --zs 0-3 -f 0,5 (8 trials) -o 3 => --zc 9 --zs 0-3 -f 0-5 (24 trials) -o 4 => --zc 9 --zs 0-3 -f 0-5 -a (24 trials + 6 alpha trials) -o 5 => --zc 3-9 --zs 0-3 -f 0-5 -a (96 trials + 6 alpha trials) -o 6 => --zc 1-9 --zs 0-3 -f 0-5 -a (180 trials + 6 alpha trials) Manually specifying a compression option (zc, zs, etc.) will override the optimization preset, regardless of the order you write the arguments.") .get_matches(); let opts = match parse_opts_into_struct(&matches) { Ok(x) => x, Err(x) => { eprintln!("{}", x); exit(1) } }; if let Err(e) = handle_optimization( matches .values_of("files") .unwrap() .map(|pattern| glob(pattern).expect("Failed to parse input file path")) .flat_map(|paths| { paths .into_iter() .map(|path| path.expect("Failed to parse input file path")) }) .collect(), &opts, ) { eprintln!("{}", e); exit(1); } } fn handle_optimization(inputs: Vec<PathBuf>, opts: &Options) -> Result<(), PngError> { inputs.into_iter().fold(Ok(()), |res, input| { let mut current_opts = opts.clone(); if input.is_dir() { if current_opts.recursive { let cur_result = handle_optimization( input .read_dir() .unwrap() .map(|x| x.unwrap().path()) .collect(), &current_opts, ); return res.and(cur_result); } else { eprintln!("{} is a directory, skipping", input.display()); } return res; } if let Some(ref out_dir) = current_opts.out_dir { current_opts.out_file = Some(out_dir.join(input.file_name().unwrap())); } let cur_result = oxipng::optimize(&input, &current_opts); res.and(cur_result) }) } #[cfg_attr(feature = "clippy", allow(cyclomatic_complexity))] fn parse_opts_into_struct(matches: &ArgMatches) -> Result<Options, String> { let mut opts = if let Some(x) = matches.value_of("optimization") { if let Ok(opt) = x.parse::<u8>() { Options::from_preset(opt) } else { unreachable!() } } else { Options::default() }; if let Some(x) = matches.value_of("interlace") { opts.interlace = x.parse::<u8>().ok(); } if let Some(x) = matches.value_of("filters") { opts.filter = parse_numeric_range_opts(x, 0, 5).unwrap(); } if let Some(x) = matches.value_of("compression") { opts.compression = parse_numeric_range_opts(x, 1, 9).unwrap(); } if let Some(x) = matches.value_of("strategies") { opts.strategies = parse_numeric_range_opts(x, 0, 3).unwrap(); } match matches.value_of("window") { Some("256") => opts.window = 8, Some("512") => opts.window = 9, Some("1k") => opts.window = 10, Some("2k") => opts.window = 11, Some("4k") => opts.window = 12, Some("8k") => opts.window = 13, Some("16k") => opts.window = 14, _ => (), } if let Some(x) = matches.value_of("output_dir") { let path = PathBuf::from(x); if !path.exists() { match DirBuilder::new().recursive(true).create(&path) { Ok(_) => (), Err(x) => return Err(format!("Could not create output directory {}", x)), }; } else if !path.is_dir() { return Err(format!( "{} is an existing file (not a directory), cannot create directory", x )); } opts.out_dir = Some(path); } if let Some(x) = matches.value_of("output_file") { opts.out_file = Some(PathBuf::from(x)); } if matches.is_present("stdout") { opts.stdout = true; } if matches.is_present("alpha") { opts.alphas.insert(AlphaOptim::White); opts.alphas.insert(AlphaOptim::Up); opts.alphas.insert(AlphaOptim::Down); opts.alphas.insert(AlphaOptim::Left); opts.alphas.insert(AlphaOptim::Right); } if matches.is_present("backup") { opts.backup = true; } if matches.is_present("force") { opts.force = true; } if matches.is_present("recursive") { opts.recursive = true; } if matches.is_present("fix") { opts.fix_errors = true; } if matches.is_present("clobber") { opts.clobber = false; } if matches.is_present("pretend") { opts.pretend = true; } if matches.is_present("preserve") { opts.preserve_attrs = true; } if matches.is_present("quiet") { opts.verbosity = None; } if matches.is_present("verbose") { opts.verbosity = Some(1); } if matches.is_present("no-bit-reduction") { opts.bit_depth_reduction = false; } if matches.is_present("no-color-reduction") { opts.color_type_reduction = false; } if matches.is_present("no-palette-reduction") { opts.palette_reduction = false; } if matches.is_present("no-reductions") { opts.bit_depth_reduction = false; opts.color_type_reduction = false; opts.palette_reduction = false; } if matches.is_present("no-recoding") { opts.idat_recoding = false; } if let Some(hdrs) = matches.value_of("strip") { let hdrs = hdrs.split(',') .map(|x| x.trim().to_owned()) .collect::<Vec<String>>(); if hdrs.contains(&"safe".to_owned()) || hdrs.contains(&"all".to_owned()) { if hdrs.len() > 1 { return
; } if hdrs[0] == "safe" { opts.strip = Headers::Safe; } else { opts.strip = Headers::All; } } else { const FORBIDDEN_CHUNKS: [&str; 5] = ["IHDR", "IDAT", "tRNS", "PLTE", "IEND"]; for i in &hdrs { if FORBIDDEN_CHUNKS.contains(&i.as_ref()) { return Err(format!("{} chunk is not allowed to be stripped", i)); } } opts.strip = Headers::Some(hdrs); } } if matches.is_present("strip-safe") { opts.strip = Headers::Safe; } if matches.is_present("zopfli") { opts.deflate = Deflaters::Zopfli; } if let Some(x) = matches.value_of("threads") { opts.threads = x.parse::<usize>().unwrap(); } Ok(opts) } fn parse_numeric_range_opts( input: &str, min_value: u8, max_value: u8, ) -> Result<HashSet<u8>, String> { let one_item = Regex::new(format!(r"^[{}-{}]$", min_value, max_value).as_ref()).unwrap(); let multiple_items = Regex::new( format!( r"^([{}-{}])(,|-)([{}-{}])$", min_value, max_value, min_value, max_value ).as_ref(), ).unwrap(); let mut items = HashSet::new(); if one_item.is_match(input) { items.insert(input.parse::<u8>().unwrap()); return Ok(items); } if let Some(captures) = multiple_items.captures(input) { let first = captures[1].parse::<u8>().unwrap(); let second = captures[3].parse::<u8>().unwrap(); if first >= second { return Err("Not a valid input".to_owned()); } match &captures[2] { "," => { items.insert(first); items.insert(second); } "-" => for i in first..second + 1 { items.insert(i); }, _ => unreachable!(), }; return Ok(items); } Err("Not a valid input".to_owned()) }
Err( "'safe' or 'all' presets for --strip should be used by themselves".to_owned(), )
call_expression
[ { "content": "/// Perform optimization on the input file using the options provided\n\npub fn optimize(input_path: &Path, opts: &Options) -> Result<(), PngError> {\n\n // Initialize the thread pool with correct number of threads\n\n let thread_count = opts.threads;\n\n let _ = rayon::ThreadPoolBuilder:...
Rust
quicksilver-utils-async/src/std_web/websocket.rs
johnpmayer/quicksilver-utils
0ddd30d02d4dcf152a142ec79b29495069999d4c
use futures_util::future::poll_fn; use std::cell::RefCell; use std::collections::VecDeque; use std::sync::Arc; use std::task::{Poll, Waker}; use url::Url; use std_web::web::{ event::{ IMessageEvent, SocketCloseEvent, SocketErrorEvent, SocketMessageData, SocketMessageEvent, SocketOpenEvent, }, IEventTarget, SocketBinaryType, TypedArray, WebSocket, }; use crate::websocket::{WebSocketError, WebSocketMessage}; use log::{debug, trace}; enum SocketState { Init, Open, Error(String), Closed, } struct AsyncWebSocketInner { ws: WebSocket, state: SocketState, waker: Option<Waker>, buffer: VecDeque<SocketMessageEvent>, } pub struct AsyncWebSocket { inner: Arc<RefCell<AsyncWebSocketInner>>, } impl Clone for AsyncWebSocket { fn clone(&self) -> Self { AsyncWebSocket { inner: self.inner.clone(), } } } impl AsyncWebSocket { pub async fn connect(url: &Url) -> Result<Self, WebSocketError> { let ws = WebSocket::new(url.as_str()) .map_err(|_| WebSocketError::NativeError("Creation".to_string()))?; ws.set_binary_type(SocketBinaryType::ArrayBuffer); let async_ws: AsyncWebSocket = { let ws = ws.clone(); let state = SocketState::Init; let waker = None; let buffer = VecDeque::new(); let inner = Arc::new(RefCell::new(AsyncWebSocketInner { ws, state, waker, buffer, })); AsyncWebSocket { inner } }; ws.add_event_listener({ let async_ws = async_ws.clone(); move |_: SocketOpenEvent| { trace!("Websocket onopen callback!"); let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); inner.state = SocketState::Open; if let Some(waker) = inner.waker.take() { waker.wake() } } }); ws.add_event_listener({ let async_ws = async_ws.clone(); move |_: SocketCloseEvent| { trace!("Websocket onclose callback!"); let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); inner.state = SocketState::Closed; if let Some(waker) = inner.waker.take() { waker.wake() } } }); ws.add_event_listener({ let async_ws = async_ws.clone(); move |error_event: SocketErrorEvent| { trace!("Websocket onerror callback!"); let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); let error_message = format!("{:?}", error_event); inner.state = SocketState::Error(error_message); if let Some(waker) = inner.waker.take() { waker.wake() } } }); ws.add_event_listener({ let async_ws = async_ws.clone(); move |message_event: SocketMessageEvent| { let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); inner.buffer.push_back(message_event); if let Some(waker) = inner.waker.take() { waker.wake() } } }); poll_fn({ let async_ws = async_ws.clone(); move |cx| { trace!("Polling"); let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); match &inner.state { SocketState::Init => { inner.waker.replace(cx.waker().clone()); Poll::Pending } SocketState::Open => Poll::Ready(Ok(())), SocketState::Error(val) => { Poll::Ready(Err(WebSocketError::StateError(val.clone()))) } SocketState::Closed => Poll::Ready(Err(WebSocketError::StateClosed)), } } }) .await?; Ok(async_ws) } pub async fn send(&self, msg: &str) -> Result<(), WebSocketError> { trace!("Send"); let inner: &AsyncWebSocketInner = &self.inner.borrow(); inner .ws .send_text(msg) .map_err(|_| WebSocketError::NativeError("Send".to_string()))?; Ok(()) } pub async fn receive(&self) -> Result<WebSocketMessage, WebSocketError> { let message_event = poll_fn({ move |cx| { trace!("Polling"); let inner: &mut AsyncWebSocketInner = &mut *self.inner.borrow_mut(); match &inner.state { SocketState::Init => Poll::Ready(Err(WebSocketError::StateInit)), SocketState::Open => { if let Some(ev) = inner.buffer.pop_front() { Poll::Ready(Ok(ev)) } else { inner.waker.replace(cx.waker().clone()); Poll::Pending } } SocketState::Error(val) => { Poll::Ready(Err(WebSocketError::StateError(val.clone()))) } SocketState::Closed => Poll::Ready(Err(WebSocketError::StateClosed)), } } }) .await?; let data = message_event.data(); debug!("{:?}", &data); let message = match data { SocketMessageData::Text(s) => WebSocketMessage::String(s), SocketMessageData::ArrayBuffer(buf) => { let t_buffer: TypedArray<u8> = TypedArray::from(buf); WebSocketMessage::Binary(t_buffer.to_vec()) } SocketMessageData::Blob(_) => { panic!("binary should have been set to array buffer above...") } }; Ok(message) } }
use futures_util::future::poll_fn; use std::cell::RefCell; use std::collections::VecDeque; use std::sync::Arc; use std::task::{Poll, Waker}; use url::Url; use std_web::web::{ event::{ IMessageEvent, SocketCloseEvent, SocketErrorEvent, SocketMessageData, SocketMessageEvent, SocketOpenEvent, }, IEventTarget, SocketBinaryType, TypedArray, WebSocket, }; use crate::websocket::{WebSocketError, WebSocketMessage}; use log::{debug, trace}; enum SocketState { Init, Open, Error(String), Closed, } struct AsyncWebSocketInner { ws: WebSocket, state: SocketState, waker: Option<Waker>, buffer: VecDeque<SocketMessageEvent>, } pub struct AsyncWebSocket { inner: Arc<RefCell<AsyncWebSocketInner>>, } impl Clone for AsyncWebSocket { fn clone(&self) -> Self { AsyncWebSocket { inner: self.inner.clone(), } } } impl AsyncWebSocket { pub async fn connect(url: &Url) -> Result<Self, WebSocketError> { let ws = WebSocket::new(url.as_str()) .map_err(|_| WebSocketError::NativeError("Creation".to_string()))?; ws.set_binary_type(SocketBinaryType::ArrayBuffer); let async_ws: AsyncWebSocket = { let ws = ws.clone(); let state = SocketState::Init; let waker = None; let buffer = VecDeque::new(); let inner = Arc::new(RefCell::new(AsyncWebSocketInner { ws, state, waker, buffer, })); AsyncWebSocket { inner } }; ws.add_event_listener({ let async_ws = async_ws.clone(); move |_: SocketOpenEvent| { trace!("Websocket onopen callback!"); let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); inner.state = SocketState::Open; if let Some(waker) = inner.waker.take() { waker.wake() } } }); ws.add_event_listener({ let async_ws = async_ws.clone(); move |_: SocketCloseEvent| { trace!("Websocket onclose callback!"); let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); inner.state = SocketState::Closed; if let Some(waker) = inner.waker.take() { waker.wake() } } }); ws.add_event_listener({ let async_ws = async_ws.clone(); move |error_event: SocketErrorEvent| { trace!("Websocket onerror callback!"); let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); let error_message = format!("{:?}", error_event); inner.state = SocketState::Error(error_message); if let Some(waker) = inner.waker.take() { waker.wake() } } }); ws.add_event_listener({ let async_ws = async_ws.clone(); move |message_event: SocketMessageEvent| { let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); inner.buffer.push_back(message_event); if let Some(waker) = inner.waker.take() { waker.wake() } } });
.await?; Ok(async_ws) } pub async fn send(&self, msg: &str) -> Result<(), WebSocketError> { trace!("Send"); let inner: &AsyncWebSocketInner = &self.inner.borrow(); inner .ws .send_text(msg) .map_err(|_| WebSocketError::NativeError("Send".to_string()))?; Ok(()) } pub async fn receive(&self) -> Result<WebSocketMessage, WebSocketError> { let message_event = poll_fn({ move |cx| { trace!("Polling"); let inner: &mut AsyncWebSocketInner = &mut *self.inner.borrow_mut(); match &inner.state { SocketState::Init => Poll::Ready(Err(WebSocketError::StateInit)), SocketState::Open => { if let Some(ev) = inner.buffer.pop_front() { Poll::Ready(Ok(ev)) } else { inner.waker.replace(cx.waker().clone()); Poll::Pending } } SocketState::Error(val) => { Poll::Ready(Err(WebSocketError::StateError(val.clone()))) } SocketState::Closed => Poll::Ready(Err(WebSocketError::StateClosed)), } } }) .await?; let data = message_event.data(); debug!("{:?}", &data); let message = match data { SocketMessageData::Text(s) => WebSocketMessage::String(s), SocketMessageData::ArrayBuffer(buf) => { let t_buffer: TypedArray<u8> = TypedArray::from(buf); WebSocketMessage::Binary(t_buffer.to_vec()) } SocketMessageData::Blob(_) => { panic!("binary should have been set to array buffer above...") } }; Ok(message) } }
poll_fn({ let async_ws = async_ws.clone(); move |cx| { trace!("Polling"); let inner: &mut AsyncWebSocketInner = &mut *async_ws.inner.borrow_mut(); match &inner.state { SocketState::Init => { inner.waker.replace(cx.waker().clone()); Poll::Pending } SocketState::Open => Poll::Ready(Ok(())), SocketState::Error(val) => { Poll::Ready(Err(WebSocketError::StateError(val.clone()))) } SocketState::Closed => Poll::Ready(Err(WebSocketError::StateClosed)), } } })
call_expression
[ { "content": "struct AsyncWebSocketInner {\n\n ws: WebSocket,\n\n state: SocketState,\n\n waker: Option<Waker>,\n\n buffer: VecDeque<MessageEvent>,\n\n}\n\n\n\npub struct AsyncWebSocket {\n\n inner: Arc<RefCell<AsyncWebSocketInner>>,\n\n}\n\n\n\nimpl Clone for AsyncWebSocket {\n\n fn clone(&se...
Rust
widgetry/src/widgets/compare_times.rs
tnederlof/abstreet
4f00c8d2bbbe2ccb4b65c11b2a071d5d1f87290d
use geom::{Angle, Circle, Distance, Duration, Pt2D}; use crate::{ Color, Drawable, EventCtx, GeomBatch, GfxCtx, Line, ScreenDims, ScreenPt, ScreenRectangle, Text, TextExt, Widget, WidgetImpl, WidgetOutput, }; pub struct CompareTimes { draw: Drawable, max: Duration, top_left: ScreenPt, dims: ScreenDims, } impl CompareTimes { pub fn new_widget<I: AsRef<str>>( ctx: &mut EventCtx, x_name: I, y_name: I, points: Vec<(Duration, Duration)>, ) -> Widget { if points.is_empty() { return Widget::nothing(); } let actual_max = *points.iter().map(|(b, a)| a.max(b)).max().unwrap(); let num_labels = 5; let (max, labels) = actual_max.make_intervals_for_max(num_labels); let width = 500.0; let height = width; let mut batch = GeomBatch::new(); batch.autocrop_dims = false; let thickness = Distance::meters(2.0); for i in 1..num_labels { let x = (i as f64) / (num_labels as f64) * width; let y = (i as f64) / (num_labels as f64) * height; batch.push( Color::grey(0.5), geom::Line::new(Pt2D::new(0.0, y), Pt2D::new(width, y)) .unwrap() .make_polygons(thickness), ); batch.push( Color::grey(0.5), geom::Line::new(Pt2D::new(x, 0.0), Pt2D::new(x, height)) .unwrap() .make_polygons(thickness), ); } batch.push( Color::grey(0.5), geom::Line::new(Pt2D::new(0.0, height), Pt2D::new(width, 0.0)) .unwrap() .make_polygons(thickness), ); let circle = Circle::new(Pt2D::new(0.0, 0.0), Distance::meters(4.0)).to_polygon(); for (b, a) in points { let pt = Pt2D::new((b / max) * width, (1.0 - (a / max)) * height); let color = match a.cmp(&b) { std::cmp::Ordering::Equal => Color::YELLOW.alpha(0.5), std::cmp::Ordering::Less => Color::GREEN.alpha(0.9), std::cmp::Ordering::Greater => Color::RED.alpha(0.9), }; batch.push(color, circle.translate(pt.x(), pt.y())); } let plot = Widget::new(Box::new(CompareTimes { dims: batch.get_dims(), draw: ctx.upload(batch), max, top_left: ScreenPt::new(0.0, 0.0), })); let y_axis = Widget::custom_col( labels .iter() .rev() .map(|x| Line(x.to_string()).small().into_widget(ctx)) .collect(), ) .evenly_spaced(); let mut y_label = Text::from(format!("{} (minutes)", y_name.as_ref())) .render(ctx) .rotate(Angle::degrees(90.0)); y_label.autocrop_dims = true; let y_label = y_label .autocrop() .into_widget(ctx) .centered_vert() .margin_right(5); let x_axis = Widget::custom_row( labels .iter() .map(|x| Line(x.to_string()).small().into_widget(ctx)) .collect(), ) .evenly_spaced(); let x_label = format!("{} (minutes)", x_name.as_ref()) .text_widget(ctx) .centered_horiz(); let plot_width = plot.get_width_for_forcing(); Widget::custom_col(vec![ Widget::custom_row(vec![y_label, y_axis, plot]), Widget::custom_col(vec![x_axis, x_label]) .force_width(plot_width) .align_right(), ]) .container() } } impl WidgetImpl for CompareTimes { fn get_dims(&self) -> ScreenDims { self.dims } fn set_pos(&mut self, top_left: ScreenPt) { self.top_left = top_left; } fn event(&mut self, _: &mut EventCtx, _: &mut WidgetOutput) {} fn draw(&self, g: &mut GfxCtx) { g.redraw_at(self.top_left, &self.draw); if let Some(cursor) = g.canvas.get_cursor_in_screen_space() { let rect = ScreenRectangle::top_left(self.top_left, self.dims); if let Some((pct_x, pct_y)) = rect.pt_to_percent(cursor) { let thickness = Distance::meters(2.0); let mut batch = GeomBatch::new(); if let Some(l) = geom::Line::new(Pt2D::new(rect.x1, cursor.y), cursor.to_pt()) { batch.push(Color::WHITE, l.make_polygons(thickness)); } if let Some(l) = geom::Line::new(Pt2D::new(cursor.x, rect.y2), cursor.to_pt()) { batch.push(Color::WHITE, l.make_polygons(thickness)); } g.fork_screenspace(); let draw = g.upload(batch); g.redraw(&draw); let before = pct_x * self.max; let after = (1.0 - pct_y) * self.max; if after <= before { g.draw_mouse_tooltip(Text::from_multiline(vec![ Line(format!("Before: {}", before)), Line(format!("After: {}", after)), Line(format!( "{} faster (-{:.1}%)", before - after, 100.0 * (1.0 - after / before) )) .fg(Color::hex("#72CE36")), ])); } else { g.draw_mouse_tooltip(Text::from_multiline(vec![ Line(format!("Before: {}", before)), Line(format!("After: {}", after)), Line(format!( "{} slower (+{:.1}%)", after - before, 100.0 * (after / before - 1.0) )) .fg(Color::hex("#EB3223")), ])); } g.unfork(); } } } }
use geom::{Angle, Circle, Distance, Duration, Pt2D}; use crate::{ Color, Drawable, EventCtx, GeomBatch, GfxCtx, Line, ScreenDims, ScreenPt, ScreenRectangle, Text, TextExt, Widget, WidgetImpl, WidgetOutput, }; pub struct CompareTimes { draw: Drawable, max: Duration, top_left: ScreenPt, dims: ScreenDims, } impl CompareTimes {
} impl WidgetImpl for CompareTimes { fn get_dims(&self) -> ScreenDims { self.dims } fn set_pos(&mut self, top_left: ScreenPt) { self.top_left = top_left; } fn event(&mut self, _: &mut EventCtx, _: &mut WidgetOutput) {} fn draw(&self, g: &mut GfxCtx) { g.redraw_at(self.top_left, &self.draw); if let Some(cursor) = g.canvas.get_cursor_in_screen_space() { let rect = ScreenRectangle::top_left(self.top_left, self.dims); if let Some((pct_x, pct_y)) = rect.pt_to_percent(cursor) { let thickness = Distance::meters(2.0); let mut batch = GeomBatch::new(); if let Some(l) = geom::Line::new(Pt2D::new(rect.x1, cursor.y), cursor.to_pt()) { batch.push(Color::WHITE, l.make_polygons(thickness)); } if let Some(l) = geom::Line::new(Pt2D::new(cursor.x, rect.y2), cursor.to_pt()) { batch.push(Color::WHITE, l.make_polygons(thickness)); } g.fork_screenspace(); let draw = g.upload(batch); g.redraw(&draw); let before = pct_x * self.max; let after = (1.0 - pct_y) * self.max; if after <= before { g.draw_mouse_tooltip(Text::from_multiline(vec![ Line(format!("Before: {}", before)), Line(format!("After: {}", after)), Line(format!( "{} faster (-{:.1}%)", before - after, 100.0 * (1.0 - after / before) )) .fg(Color::hex("#72CE36")), ])); } else { g.draw_mouse_tooltip(Text::from_multiline(vec![ Line(format!("Before: {}", before)), Line(format!("After: {}", after)), Line(format!( "{} slower (+{:.1}%)", after - before, 100.0 * (after / before - 1.0) )) .fg(Color::hex("#EB3223")), ])); } g.unfork(); } } } }
pub fn new_widget<I: AsRef<str>>( ctx: &mut EventCtx, x_name: I, y_name: I, points: Vec<(Duration, Duration)>, ) -> Widget { if points.is_empty() { return Widget::nothing(); } let actual_max = *points.iter().map(|(b, a)| a.max(b)).max().unwrap(); let num_labels = 5; let (max, labels) = actual_max.make_intervals_for_max(num_labels); let width = 500.0; let height = width; let mut batch = GeomBatch::new(); batch.autocrop_dims = false; let thickness = Distance::meters(2.0); for i in 1..num_labels { let x = (i as f64) / (num_labels as f64) * width; let y = (i as f64) / (num_labels as f64) * height; batch.push( Color::grey(0.5), geom::Line::new(Pt2D::new(0.0, y), Pt2D::new(width, y)) .unwrap() .make_polygons(thickness), ); batch.push( Color::grey(0.5), geom::Line::new(Pt2D::new(x, 0.0), Pt2D::new(x, height)) .unwrap() .make_polygons(thickness), ); } batch.push( Color::grey(0.5), geom::Line::new(Pt2D::new(0.0, height), Pt2D::new(width, 0.0)) .unwrap() .make_polygons(thickness), ); let circle = Circle::new(Pt2D::new(0.0, 0.0), Distance::meters(4.0)).to_polygon(); for (b, a) in points { let pt = Pt2D::new((b / max) * width, (1.0 - (a / max)) * height); let color = match a.cmp(&b) { std::cmp::Ordering::Equal => Color::YELLOW.alpha(0.5), std::cmp::Ordering::Less => Color::GREEN.alpha(0.9), std::cmp::Ordering::Greater => Color::RED.alpha(0.9), }; batch.push(color, circle.translate(pt.x(), pt.y())); } let plot = Widget::new(Box::new(CompareTimes { dims: batch.get_dims(), draw: ctx.upload(batch), max, top_left: ScreenPt::new(0.0, 0.0), })); let y_axis = Widget::custom_col( labels .iter() .rev() .map(|x| Line(x.to_string()).small().into_widget(ctx)) .collect(), ) .evenly_spaced(); let mut y_label = Text::from(format!("{} (minutes)", y_name.as_ref())) .render(ctx) .rotate(Angle::degrees(90.0)); y_label.autocrop_dims = true; let y_label = y_label .autocrop() .into_widget(ctx) .centered_vert() .margin_right(5); let x_axis = Widget::custom_row( labels .iter() .map(|x| Line(x.to_string()).small().into_widget(ctx)) .collect(), ) .evenly_spaced(); let x_label = format!("{} (minutes)", x_name.as_ref()) .text_widget(ctx) .centered_horiz(); let plot_width = plot.get_width_for_forcing(); Widget::custom_col(vec![ Widget::custom_row(vec![y_label, y_axis, plot]), Widget::custom_col(vec![x_axis, x_label]) .force_width(plot_width) .align_right(), ]) .container() }
function_block-full_function
[ { "content": "pub fn make_bar(ctx: &mut EventCtx, filled_color: Color, value: usize, max: usize) -> Widget {\n\n let pct_full = if max == 0 {\n\n 0.0\n\n } else {\n\n (value as f64) / (max as f64)\n\n };\n\n let txt = Text::from(format!(\n\n \"{} / {}\",\n\n prettyprint_u...
Rust
src/transforms/geoip.rs
XOSplicer/vector
f04d9452471147c082d8262e103cdb33fb846e26
use super::Transform; use crate::{ event::{Event, Value}, topology::config::{DataType, TransformConfig, TransformContext}, }; use serde::{Deserialize, Serialize}; use string_cache::DefaultAtom as Atom; use std::str::FromStr; use tracing::field; #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fields)] pub struct GeoipConfig { pub source: Atom, pub database: String, #[serde(default = "default_geoip_target_field")] pub target: String, } pub struct Geoip { pub dbreader: maxminddb::Reader<Vec<u8>>, pub source: Atom, pub target: String, } fn default_geoip_target_field() -> String { "geoip".to_string() } #[typetag::serde(name = "geoip")] impl TransformConfig for GeoipConfig { fn build(&self, _cx: TransformContext) -> Result<Box<dyn Transform>, crate::Error> { let reader = maxminddb::Reader::open_readfile(self.database.clone())?; Ok(Box::new(Geoip::new( reader, self.source.clone(), self.target.clone(), ))) } fn input_type(&self) -> DataType { DataType::Log } fn output_type(&self) -> DataType { DataType::Log } fn transform_type(&self) -> &'static str { "geoip" } } impl Geoip { pub fn new(dbreader: maxminddb::Reader<Vec<u8>>, source: Atom, target: String) -> Self { Geoip { dbreader, source, target, } } } impl Transform for Geoip { fn transform(&mut self, mut event: Event) -> Option<Event> { let target_field = self.target.clone(); let ipaddress = event .as_log() .get(&self.source) .map(|s| s.to_string_lossy()); if let Some(ipaddress) = &ipaddress { if let Ok(ip) = FromStr::from_str(ipaddress) { if let Ok(data) = self.dbreader.lookup::<maxminddb::geoip2::City>(ip) { if let Some(city_names) = data.city.and_then(|c| c.names) { if let Some(city_name_en) = city_names.get("en") { event.as_mut_log().insert( Atom::from(format!("{}.city_name", target_field)), Value::from(city_name_en.to_string()), ); } } let continent_code = data.continent.and_then(|c| c.code); if let Some(continent_code) = continent_code { event.as_mut_log().insert( Atom::from(format!("{}.continent_code", target_field)), Value::from(continent_code), ); } let iso_code = data.country.and_then(|cy| cy.iso_code); if let Some(iso_code) = iso_code { event.as_mut_log().insert( Atom::from(format!("{}.country_code", target_field)), Value::from(iso_code), ); } let time_zone = data.location.clone().and_then(|loc| loc.time_zone); if let Some(time_zone) = time_zone { event.as_mut_log().insert( Atom::from(format!("{}.timezone", target_field)), Value::from(time_zone), ); } let latitude = data.location.clone().and_then(|loc| loc.latitude); if let Some(latitude) = latitude { event.as_mut_log().insert( Atom::from(format!("{}.latitude", target_field)), Value::from(latitude.to_string()), ); } let longitude = data.location.clone().and_then(|loc| loc.longitude); if let Some(longitude) = longitude { event.as_mut_log().insert( Atom::from(format!("{}.longitude", target_field)), Value::from(longitude.to_string()), ); } let postal_code = data.postal.clone().and_then(|p| p.code); if let Some(postal_code) = postal_code { event.as_mut_log().insert( Atom::from(format!("{}.postal_code", target_field)), Value::from(postal_code), ); } } } else { debug!( message = "IP Address not parsed correctly.", ipaddr = &field::display(&ipaddress), ); } } else { debug!( message = "Field does not exist.", field = self.source.as_ref(), ); }; let geoip_fields = [ format!("{}.city_name", target_field), format!("{}.country_code", target_field), format!("{}.continent_code", target_field), format!("{}.timezone", target_field), format!("{}.latitude", target_field), format!("{}.longitude", target_field), format!("{}.postal_code", target_field), ]; for field in geoip_fields.iter() { let e = event.as_mut_log(); let d = e.get(&Atom::from(field.to_string())); match d { None => { e.insert(Atom::from(field.to_string()), Value::from("")); } _ => (), } } Some(event) } } #[cfg(feature = "transforms-json_parser")] #[cfg(test)] mod tests { use super::Geoip; use crate::{ event::Event, transforms::json_parser::{JsonParser, JsonParserConfig}, transforms::Transform, }; use std::collections::HashMap; use string_cache::DefaultAtom as Atom; #[test] fn geoip_lookup_success() { let mut parser = JsonParser::from(JsonParserConfig::default()); let event = Event::from(r#"{"remote_addr": "2.125.160.216", "request_path": "foo/bar"}"#); let event = parser.transform(event).unwrap(); let reader = maxminddb::Reader::open_readfile("test-data/GeoIP2-City-Test.mmdb").unwrap(); let mut augment = Geoip::new(reader, Atom::from("remote_addr"), "geo".to_string()); let new_event = augment.transform(event).unwrap(); let mut exp_geoip_attr = HashMap::new(); exp_geoip_attr.insert("city_name", "Boxford"); exp_geoip_attr.insert("country_code", "GB"); exp_geoip_attr.insert("continent_code", "EU"); exp_geoip_attr.insert("timezone", "Europe/London"); exp_geoip_attr.insert("latitude", "51.75"); exp_geoip_attr.insert("longitude", "-1.25"); exp_geoip_attr.insert("postal_code", "OX1"); for field in exp_geoip_attr.keys() { let k = Atom::from(format!("geo.{}", field).to_string()); let geodata = new_event.as_log().get(&k).unwrap().to_string_lossy(); match exp_geoip_attr.get(field) { Some(&v) => assert_eq!(geodata, v), _ => assert!(false), } } } #[test] fn geoip_lookup_partial_results() { let mut parser = JsonParser::from(JsonParserConfig::default()); let event = Event::from(r#"{"remote_addr": "67.43.156.9", "request_path": "foo/bar"}"#); let event = parser.transform(event).unwrap(); let reader = maxminddb::Reader::open_readfile("test-data/GeoIP2-City-Test.mmdb").unwrap(); let mut augment = Geoip::new(reader, Atom::from("remote_addr"), "geo".to_string()); let new_event = augment.transform(event).unwrap(); let mut exp_geoip_attr = HashMap::new(); exp_geoip_attr.insert("city_name", ""); exp_geoip_attr.insert("country_code", "BT"); exp_geoip_attr.insert("continent_code", "AS"); exp_geoip_attr.insert("timezone", "Asia/Thimphu"); exp_geoip_attr.insert("latitude", "27.5"); exp_geoip_attr.insert("longitude", "90.5"); exp_geoip_attr.insert("postal_code", ""); for field in exp_geoip_attr.keys() { let k = Atom::from(format!("geo.{}", field).to_string()); let geodata = new_event.as_log().get(&k).unwrap().to_string_lossy(); match exp_geoip_attr.get(field) { Some(&v) => assert_eq!(geodata, v), _ => assert!(false), } } } #[test] fn geoip_lookup_no_results() { let mut parser = JsonParser::from(JsonParserConfig::default()); let event = Event::from(r#"{"remote_addr": "10.1.12.1", "request_path": "foo/bar"}"#); let event = parser.transform(event).unwrap(); let reader = maxminddb::Reader::open_readfile("test-data/GeoIP2-City-Test.mmdb").unwrap(); let mut augment = Geoip::new(reader, Atom::from("remote_addr"), "geo".to_string()); let new_event = augment.transform(event).unwrap(); let mut exp_geoip_attr = HashMap::new(); exp_geoip_attr.insert("city_name", ""); exp_geoip_attr.insert("country_code", ""); exp_geoip_attr.insert("continent_code", ""); exp_geoip_attr.insert("timezone", ""); exp_geoip_attr.insert("latitude", ""); exp_geoip_attr.insert("longitude", ""); exp_geoip_attr.insert("postal_code", ""); for field in exp_geoip_attr.keys() { let k = Atom::from(format!("geo.{}", field).to_string()); println!("Looking for {:?}", k); let geodata = new_event.as_log().get(&k).unwrap().to_string_lossy(); match exp_geoip_attr.get(field) { Some(&v) => assert_eq!(geodata, v), _ => assert!(false), } } } }
use super::Transform; use crate::{ event::{Event, Value}, topology::config::{DataType, TransformConfig, TransformContext}, }; use serde::{Deserialize, Serialize}; use string_cache::DefaultAtom as Atom; use std::str::FromStr; use tracing::field; #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fields)] pub struct GeoipConfig { pub source: Atom, pub database: String, #[serde(default = "default_geoip_target_field")] pub target: String, } pub struct Geoip { pub dbreader: maxminddb::Reader<Vec<u8>>, pub source: Atom, pub target: String, } fn default_geoip_target_field() -> String { "geoip".to_string() } #[typetag::serde(name = "geoip")] impl TransformConfig for GeoipConfig { fn build(&self, _cx: TransformContext) -> Result<Box<dyn Transform>, crate::Error> { let reader = maxminddb::Reader::open_readfile(self.database.clone())?; Ok(Box::new(Geoip::new( reader, self.source.clone(), self.target.clone(), ))) } fn input_type(&self) -> DataType { DataType::Log } fn output_type(&self) -> DataType { DataType::Log } fn transform_type(&self) -> &'static str { "geoip" } } impl Geoip { pub fn new(dbreader: maxminddb::Reader<Vec<u8>>, source: Atom, target: String) -> Self { Geoip { dbreader, source, target, } } } impl Transform for Geoip { fn transform(&mut self, mut event: Event) -> Option<Event> { let target_field = self.target.clone(); let ipaddress = event .as_log() .get(&self.source) .map(|s| s.to_string_lossy()); if let Some(ipaddress) = &ipaddress { if let Ok(ip) = FromStr::from_str(ipaddress) { if let Ok(data) = self.dbreader.lookup::<maxminddb::geoip2::City>(ip) { if let Some(city_names) = data.city.and_then(|c| c.names) { if let Some(city_name_en) = city_names.get("en") { event.as_mut_log().insert( Atom::from(format!("{}.city_name", target_field)), Value::from(city_name_en.to_string()), ); } } let continent_code = data.continent.and_then(|c| c.code); if let Some(continent_code) = continent_code { event.as_mut_log().insert( Atom::from(format!("{}.continent_code", target_field)), Value::from(continent_code), ); } let iso_code = data.country.and_then(|cy| cy.iso_code); if let Some(iso_code) = iso_code { event.as_mut_log().insert( Atom::from(format!("{}.country_code", target_field)), Value::from(iso_code), ); } let time_zone = data.location.clone().and_then(|loc| loc.time_zone); if let Some(time_zone) = time_zone { event.as_mut_log().insert( Atom::from(format!("{}.timezone", target_field)), Value::from(time_zone), ); } let latitude = data.location.clone().and_then(|loc| loc.latitude); if let Some(latitude) = latitude { event.as_mut_log().insert( Atom::from(format!("{}.latitude", target_field)), Value::from(latitude.to_string()), ); } let longitude = data.location.clone().and_then(|loc| loc.longitude); if let Some(longitude) = longitude { event.as_mut_log().insert( Atom::from(format!("{}.longitude", target_field)), Value::from(longitude.to_string()), ); } let postal_code = data.postal.clone().and_then(|p| p.code); if let Some(postal_code) = postal_code { event.as_mut_log().insert( Atom::from(format!("{}.postal_code", target_field)), Value::from(postal_code), ); } } } else { debug!( message = "IP Address not parsed correctly.", ipaddr = &field::display(&ipaddress), ); } } else { debug!( message = "Field does not exist.", field = self.source.as_ref(), ); }; let geoip_fields = [ format!("{}.city_name", target_field), format!("{}.country_code", target_field), format!("{}.continent_code", target_field), format!("{}.timezone", target_field), format!("{}.latitude", target_field), format!("{}.longitude", target_field), format!("{}.postal_code", target_field), ]; for field in geoip_fields.iter() { let e = event.as_mut_log(); let d = e.get(&Atom::from(field.to_string())); match d { None => { e.insert(Atom::from(field.to_string()), Value::from("")); } _ => (), } } Some(event) } } #[cfg(feature = "transforms-json_parser")] #[cfg(test)] mod tests { use super::Geoip; use crate::{ event::Event, transforms::json_parser::{JsonParser, JsonParserConfig}, transforms::Transform, }; use std::collections::HashMap; use string_cache::DefaultAtom as Atom; #[test] fn geoip_lookup_success() { let mut parser = JsonParser::from(JsonParserConfig::default()); let event = Event::from(r#"{"remote_addr": "2.125.160.216", "request_path": "foo/bar"}"#); let event = parser.transform(event).unwrap(); let reader = maxminddb::Reader::open_readfile("test-data/GeoIP2-City-Test.mmdb").unwrap(); let mut augment = Geoip::new(reader, Atom::from("remote_addr"), "geo".to_string()); let new_event = augment.transform(event).unwrap(); let mut exp_geoip_attr = HashMap::new(); exp_geoip_attr.insert("city_name", "Boxford"); exp_geoip_attr.insert("country_code", "GB"); exp_geoip_attr.insert("continent_code", "EU"); exp_geoip_attr.insert("timezone", "Europe/London"); exp_geoip_attr.insert("latitude", "51.75"); exp_geoip_attr.insert("longitude", "-1.25"); exp_geoip_attr.insert("postal_code", "OX1"); for field in exp_geoip_attr.keys() { let k = Atom::from(format!("geo.{}", field).to_string()); let geodata = new_event.as_log().get(&k).unwrap().to_string_lossy(); match exp_geoip_attr.get(field) { Some(&v) => assert_eq!(geodata, v), _ => assert!(false), } } } #[test] fn geoip_lookup_partial_results() { let mut parser = JsonParser::from(JsonParserConfig::default()); let event = Event::from(r#"{"remote_addr": "67.43.156.9", "request_path": "foo/bar"}"#); let event = parser.transform(event).unwrap(); let reader = maxminddb::Reader::open_readfile("test-data/GeoIP2-City-Test.mmdb").unwrap(); let mut augment = Geoip::new(reader, Atom::from("re
exp_geoip_attr.insert("timezone", ""); exp_geoip_attr.insert("latitude", ""); exp_geoip_attr.insert("longitude", ""); exp_geoip_attr.insert("postal_code", ""); for field in exp_geoip_attr.keys() { let k = Atom::from(format!("geo.{}", field).to_string()); println!("Looking for {:?}", k); let geodata = new_event.as_log().get(&k).unwrap().to_string_lossy(); match exp_geoip_attr.get(field) { Some(&v) => assert_eq!(geodata, v), _ => assert!(false), } } } }
mote_addr"), "geo".to_string()); let new_event = augment.transform(event).unwrap(); let mut exp_geoip_attr = HashMap::new(); exp_geoip_attr.insert("city_name", ""); exp_geoip_attr.insert("country_code", "BT"); exp_geoip_attr.insert("continent_code", "AS"); exp_geoip_attr.insert("timezone", "Asia/Thimphu"); exp_geoip_attr.insert("latitude", "27.5"); exp_geoip_attr.insert("longitude", "90.5"); exp_geoip_attr.insert("postal_code", ""); for field in exp_geoip_attr.keys() { let k = Atom::from(format!("geo.{}", field).to_string()); let geodata = new_event.as_log().get(&k).unwrap().to_string_lossy(); match exp_geoip_attr.get(field) { Some(&v) => assert_eq!(geodata, v), _ => assert!(false), } } } #[test] fn geoip_lookup_no_results() { let mut parser = JsonParser::from(JsonParserConfig::default()); let event = Event::from(r#"{"remote_addr": "10.1.12.1", "request_path": "foo/bar"}"#); let event = parser.transform(event).unwrap(); let reader = maxminddb::Reader::open_readfile("test-data/GeoIP2-City-Test.mmdb").unwrap(); let mut augment = Geoip::new(reader, Atom::from("remote_addr"), "geo".to_string()); let new_event = augment.transform(event).unwrap(); let mut exp_geoip_attr = HashMap::new(); exp_geoip_attr.insert("city_name", ""); exp_geoip_attr.insert("country_code", ""); exp_geoip_attr.insert("continent_code", "");
random
[ { "content": "/// Returns a mutable reference to field value specified by the given path.\n\npub fn get_mut<'a>(fields: &'a mut BTreeMap<Atom, Value>, path: &str) -> Option<&'a mut Value> {\n\n let mut path_iter = PathIter::new(path);\n\n\n\n match path_iter.next() {\n\n Some(PathComponent::Key(key...
Rust
server/prisma-rs/libs/database-inspector/tests/tests.rs
otrebu/prisma
298be5c919119847bb8d102d6b16672edd06b2c5
#![allow(non_snake_case)] #![allow(unused)] use barrel::{backend::Sqlite as Squirrel, types, Migration}; use database_inspector::*; use rusqlite::{Connection, Result, NO_PARAMS}; use std::{thread, time}; const SCHEMA: &str = "database_inspector_test"; #[test] fn all_columns_types_must_work() { let inspector = setup(|mut migration| { migration.create_table("User", |t| { t.add_column("int", types::integer()); t.add_column("float", types::float()); t.add_column("boolean", types::boolean()); t.add_column("string1", types::text()); t.add_column("string2", types::varchar(1)); t.add_column("date_time", types::date()); }); }); let result = inspector.introspect(&SCHEMA.to_string()); let table = result.table("User").unwrap(); let expected_columns = vec![ Column { name: "int".to_string(), tpe: ColumnType::Int, is_required: true, foreign_key: None, sequence: None, }, Column { name: "float".to_string(), tpe: ColumnType::Float, is_required: true, foreign_key: None, sequence: None, }, Column { name: "boolean".to_string(), tpe: ColumnType::Boolean, is_required: true, foreign_key: None, sequence: None, }, Column { name: "string1".to_string(), tpe: ColumnType::String, is_required: true, foreign_key: None, sequence: None, }, Column { name: "string2".to_string(), tpe: ColumnType::String, is_required: true, foreign_key: None, sequence: None, }, Column { name: "date_time".to_string(), tpe: ColumnType::DateTime, is_required: true, foreign_key: None, sequence: None, }, ]; assert_eq!(table.columns, expected_columns); } #[test] fn is_required_must_work() { let inspector = setup(|mut migration| { migration.create_table("User", |t| { t.add_column("column1", types::integer().nullable(false)); t.add_column("column2", types::integer().nullable(true)); }); }); let result = inspector.introspect(&SCHEMA.to_string()); let user_table = result.table("User").unwrap(); let expected_columns = vec![ Column { name: "column1".to_string(), tpe: ColumnType::Int, is_required: true, foreign_key: None, sequence: None, }, Column { name: "column2".to_string(), tpe: ColumnType::Int, is_required: false, foreign_key: None, sequence: None, }, ]; assert_eq!(user_table.columns, expected_columns); } #[test] fn foreign_keys_must_work() { let inspector = setup(|mut migration| { migration.create_table("City", |t| { t.add_column("id", types::primary()); }); migration.create_table("User", |t| { t.add_column("city", types::foreign("City(id)")); }); }); let result = inspector.introspect(&SCHEMA.to_string()); let user_table = result.table("User").unwrap(); let expected_columns = vec![Column { name: "city".to_string(), tpe: ColumnType::Int, is_required: true, foreign_key: Some(ForeignKey { table: "City".to_string(), column: "id".to_string(), }), sequence: None, }]; assert_eq!(user_table.columns, expected_columns); } fn setup<F>(mut migrationFn: F) -> Box<DatabaseInspector> where F: FnMut(&mut Migration) -> (), { let connection = Connection::open_in_memory() .and_then(|c| { let server_root = std::env::var("SERVER_ROOT").expect("Env var SERVER_ROOT required but not found."); let path = format!("{}/db", server_root); let database_file_path = dbg!(format!("{}/{}.db", path, SCHEMA)); std::fs::remove_file(database_file_path.clone()); thread::sleep(time::Duration::from_millis(100)); c.execute("ATTACH DATABASE ? AS ?", &[database_file_path.as_ref(), SCHEMA]) .map(|_| c) }) .and_then(|c| { let mut migration = Migration::new().schema(SCHEMA); migrationFn(&mut migration); let full_sql = migration.make::<Squirrel>(); for sql in full_sql.split(";") { dbg!(sql); if (sql != "") { c.execute(&sql, NO_PARAMS).unwrap(); } } Ok(c) }) .unwrap(); Box::new(DatabaseInspectorImpl::new(connection)) }
#![allow(non_snake_case)] #![allow(unused)] use barrel::{backend::Sqlite as Squirrel, types, Migration}; use database_inspector::*; use rusqlite::{Connection, Result, NO_PARAMS}; use std::{thread, time}; const SCHEMA: &str = "database_inspector_test"; #[test] fn all_columns_types_must_work() { let inspector = setup(|mut migration| { migration.create_table("User", |t| { t.add_column("int", types::integer()); t.add_column("float", types::float()); t.add_column("boolean", types::boolean()); t.add_column("string1", types::tex
at, is_required: true, foreign_key: None, sequence: None, }, Column { name: "boolean".to_string(), tpe: ColumnType::Boolean, is_required: true, foreign_key: None, sequence: None, }, Column { name: "string1".to_string(), tpe: ColumnType::String, is_required: true, foreign_key: None, sequence: None, }, Column { name: "string2".to_string(), tpe: ColumnType::String, is_required: true, foreign_key: None, sequence: None, }, Column { name: "date_time".to_string(), tpe: ColumnType::DateTime, is_required: true, foreign_key: None, sequence: None, }, ]; assert_eq!(table.columns, expected_columns); } #[test] fn is_required_must_work() { let inspector = setup(|mut migration| { migration.create_table("User", |t| { t.add_column("column1", types::integer().nullable(false)); t.add_column("column2", types::integer().nullable(true)); }); }); let result = inspector.introspect(&SCHEMA.to_string()); let user_table = result.table("User").unwrap(); let expected_columns = vec![ Column { name: "column1".to_string(), tpe: ColumnType::Int, is_required: true, foreign_key: None, sequence: None, }, Column { name: "column2".to_string(), tpe: ColumnType::Int, is_required: false, foreign_key: None, sequence: None, }, ]; assert_eq!(user_table.columns, expected_columns); } #[test] fn foreign_keys_must_work() { let inspector = setup(|mut migration| { migration.create_table("City", |t| { t.add_column("id", types::primary()); }); migration.create_table("User", |t| { t.add_column("city", types::foreign("City(id)")); }); }); let result = inspector.introspect(&SCHEMA.to_string()); let user_table = result.table("User").unwrap(); let expected_columns = vec![Column { name: "city".to_string(), tpe: ColumnType::Int, is_required: true, foreign_key: Some(ForeignKey { table: "City".to_string(), column: "id".to_string(), }), sequence: None, }]; assert_eq!(user_table.columns, expected_columns); } fn setup<F>(mut migrationFn: F) -> Box<DatabaseInspector> where F: FnMut(&mut Migration) -> (), { let connection = Connection::open_in_memory() .and_then(|c| { let server_root = std::env::var("SERVER_ROOT").expect("Env var SERVER_ROOT required but not found."); let path = format!("{}/db", server_root); let database_file_path = dbg!(format!("{}/{}.db", path, SCHEMA)); std::fs::remove_file(database_file_path.clone()); thread::sleep(time::Duration::from_millis(100)); c.execute("ATTACH DATABASE ? AS ?", &[database_file_path.as_ref(), SCHEMA]) .map(|_| c) }) .and_then(|c| { let mut migration = Migration::new().schema(SCHEMA); migrationFn(&mut migration); let full_sql = migration.make::<Squirrel>(); for sql in full_sql.split(";") { dbg!(sql); if (sql != "") { c.execute(&sql, NO_PARAMS).unwrap(); } } Ok(c) }) .unwrap(); Box::new(DatabaseInspectorImpl::new(connection)) }
t()); t.add_column("string2", types::varchar(1)); t.add_column("date_time", types::date()); }); }); let result = inspector.introspect(&SCHEMA.to_string()); let table = result.table("User").unwrap(); let expected_columns = vec![ Column { name: "int".to_string(), tpe: ColumnType::Int, is_required: true, foreign_key: None, sequence: None, }, Column { name: "float".to_string(), tpe: ColumnType::Flo
function_block-random_span
[]
Rust
askama_escape/src/lib.rs
tizgafa/askama
d2c38b22ac54cc145bb2ede2925f7f149c8fd57e
#[macro_use] extern crate cfg_if; use std::fmt::{self, Display, Formatter}; use std::str; #[derive(Debug, PartialEq)] pub enum MarkupDisplay<T> where T: Display, { Safe(T), Unsafe(T), } impl<T> MarkupDisplay<T> where T: Display, { pub fn mark_safe(self) -> MarkupDisplay<T> { match self { MarkupDisplay::Unsafe(t) => MarkupDisplay::Safe(t), _ => self, } } } impl<T> From<T> for MarkupDisplay<T> where T: Display, { fn from(t: T) -> MarkupDisplay<T> { MarkupDisplay::Unsafe(t) } } impl<T> Display for MarkupDisplay<T> where T: Display, { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { MarkupDisplay::Unsafe(ref t) => escape(&t.to_string()).fmt(f), MarkupDisplay::Safe(ref t) => t.fmt(f), } } } pub fn escape(s: &str) -> Escaped { Escaped { bytes: s.as_bytes(), } } pub struct Escaped<'a> { bytes: &'a [u8], } impl<'a> Display for Escaped<'a> { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { _imp(self.bytes, fmt) } } cfg_if! { if #[cfg(all(target_arch = "x86_64", askama_runtime_simd))] { use std::arch::x86_64::*; use std::mem::{self, size_of}; use std::sync::atomic::{AtomicUsize, Ordering}; #[inline(always)] fn _imp(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { static mut FN: fn(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result = detect; fn detect(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { let fun = if cfg!(askama_runtime_avx) && is_x86_feature_detected!("avx2") { _avx_escape as usize } else if cfg!(askama_runtime_sse) { _sse_escape as usize } else { _escape as usize }; let slot = unsafe { &*(&FN as *const _ as *const AtomicUsize) }; slot.store(fun as usize, Ordering::Relaxed); unsafe { mem::transmute::<usize, fn(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result>(fun)(bytes, fmt) } } unsafe { let slot = &*(&FN as *const _ as * const AtomicUsize); let fun = slot.load(Ordering::Relaxed); mem::transmute::<usize, fn(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result>(fun)(bytes, fmt) } } #[inline(always)] fn sub(a: *const u8, b: *const u8) -> usize { debug_assert!(b <= a); (a as usize) - (b as usize) } } else { #[inline(always)] fn _imp(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { _escape(bytes, fmt) } } } macro_rules! escaping_body { ($i:expr, $start:ident, $fmt:ident, $bytes:ident, $quote:expr) => {{ if $start < $i { #[allow(unused_unsafe)] $fmt.write_str(unsafe { str::from_utf8_unchecked(&$bytes[$start..$i]) })?; } $fmt.write_str($quote)?; $start = $i + 1; }}; } macro_rules! bodies { ($i:expr, $b: ident, $start:ident, $fmt:ident, $bytes:ident, $callback:ident) => { match $b { b'<' => $callback!($i, $start, $fmt, $bytes, "&lt;"), b'>' => $callback!($i, $start, $fmt, $bytes, "&gt;"), b'&' => $callback!($i, $start, $fmt, $bytes, "&amp;"), b'"' => $callback!($i, $start, $fmt, $bytes, "&quot;"), b'\'' => $callback!($i, $start, $fmt, $bytes, "&#x27;"), b'/' => $callback!($i, $start, $fmt, $bytes, "&#x2f;"), _ => (), } }; } macro_rules! write_char { ($i:ident, $ptr: ident, $start: ident, $fmt: ident, $bytes:ident) => {{ let b = *$ptr; if b.wrapping_sub(FLAG_BELOW) <= LEN { bodies!($i, b, $start, $fmt, $bytes, escaping_body); } }}; } #[allow(unused_macros)] macro_rules! mask_body { ($i:expr, $start:ident, $fmt:ident, $bytes:ident, $quote:expr) => {{ let i = $i; escaping_body!(i, $start, $fmt, $bytes, $quote); }}; } #[allow(unused_macros)] macro_rules! mask_bodies { ($mask: ident, $at:ident, $cur: ident, $ptr: ident, $start: ident, $fmt: ident, $bytes:ident) => { let b = *$ptr.add($cur); bodies!($at + $cur, b, $start, $fmt, $bytes, mask_body); $mask ^= 1 << $cur; if $mask == 0 { break; } $cur = $mask.trailing_zeros() as usize; }; } #[allow(unused_macros)] macro_rules! write_mask { ($mask: ident, $ptr: ident, $start_ptr: ident, $start: ident, $fmt: ident, $bytes:ident) => {{ let at = sub($ptr, $start_ptr); let mut cur = $mask.trailing_zeros() as usize; loop { mask_bodies!($mask, at, cur, $ptr, $start, $fmt, $bytes); } debug_assert_eq!(at, sub($ptr, $start_ptr)) }}; } #[allow(unused_macros)] macro_rules! write_forward { ($mask: ident, $align: ident, $ptr: ident, $start_ptr: ident, $start: ident, $fmt: ident, $bytes:ident) => {{ if $mask != 0 { let at = sub($ptr, $start_ptr); let mut cur = $mask.trailing_zeros() as usize; while cur < $align { mask_bodies!($mask, at, cur, $ptr, $start, $fmt, $bytes); } debug_assert_eq!(at, sub($ptr, $start_ptr)) } }}; } fn _escape(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { let mut start = 0; for (i, b) in bytes.iter().enumerate() { write_char!(i, b, start, fmt, bytes); } fmt.write_str(unsafe { str::from_utf8_unchecked(&bytes[start..]) })?; Ok(()) } #[cfg(all(target_arch = "x86_64", askama_runtime_avx))] unsafe fn _avx_escape(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { const VECTOR_SIZE: usize = size_of::<__m256i>(); const VECTOR_ALIGN: usize = VECTOR_SIZE - 1; const LOOP_SIZE: usize = 4 * VECTOR_SIZE; let len = bytes.len(); let mut start = 0; if len < VECTOR_SIZE { for (i, b) in bytes.iter().enumerate() { write_char!(i, b, start, fmt, bytes); } if start < len { fmt.write_str(str::from_utf8_unchecked(&bytes[start..len]))?; } return Ok(()); } let v_flag = _mm256_set1_epi8((LEN + 1) as i8); let v_flag_below = _mm256_set1_epi8(FLAG_BELOW as i8); let start_ptr = bytes.as_ptr(); let end_ptr = bytes[len..].as_ptr(); let mut ptr = start_ptr; debug_assert!(start_ptr <= ptr && start_ptr <= end_ptr.sub(VECTOR_SIZE)); if LOOP_SIZE <= len { { let align = start_ptr as usize & VECTOR_ALIGN; if 0 < align { let a = _mm256_loadu_si256(ptr as *const __m256i); let cmp = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(a, v_flag_below)); let mut mask = _mm256_movemask_epi8(cmp); write_forward!(mask, align, ptr, start_ptr, start, fmt, bytes); ptr = ptr.add(align); debug_assert!(start <= sub(ptr, start_ptr)); } } while ptr <= end_ptr.sub(LOOP_SIZE) { debug_assert_eq!(0, (ptr as usize) % VECTOR_SIZE); let a = _mm256_load_si256(ptr as *const __m256i); let b = _mm256_load_si256(ptr.add(VECTOR_SIZE) as *const __m256i); let c = _mm256_load_si256(ptr.add(VECTOR_SIZE * 2) as *const __m256i); let d = _mm256_load_si256(ptr.add(VECTOR_SIZE * 3) as *const __m256i); let cmp_a = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(a, v_flag_below)); let cmp_b = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(b, v_flag_below)); let cmp_c = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(c, v_flag_below)); let cmp_d = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(d, v_flag_below)); let or1 = _mm256_or_si256(cmp_a, cmp_b); let or2 = _mm256_or_si256(cmp_c, cmp_d); if _mm256_movemask_epi8(_mm256_or_si256(or1, or2)) != 0 { let mut mask = _mm256_movemask_epi8(cmp_a) as i128 | (_mm256_movemask_epi8(cmp_b) as i128) << VECTOR_SIZE | (_mm256_movemask_epi8(cmp_c) as i128) << VECTOR_SIZE * 2 | (_mm256_movemask_epi8(cmp_d) as i128) << VECTOR_SIZE * 3; write_mask!(mask, ptr, start_ptr, start, fmt, bytes); } ptr = ptr.add(LOOP_SIZE); debug_assert!(start <= sub(ptr, start_ptr)); } } while ptr <= end_ptr.sub(VECTOR_SIZE) { let a = _mm256_loadu_si256(ptr as *const __m256i); let cmp = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(a, v_flag_below)); let mut mask = _mm256_movemask_epi8(cmp); if mask != 0 { write_mask!(mask, ptr, start_ptr, start, fmt, bytes); } ptr = ptr.add(VECTOR_SIZE); debug_assert!(start <= sub(ptr, start_ptr)); } debug_assert!(end_ptr.sub(VECTOR_SIZE) < ptr); if ptr < end_ptr { let a = _mm256_loadu_si256(ptr as *const __m256i); let cmp = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(a, v_flag_below)); let end = sub(end_ptr, ptr); let mut mask = _mm256_movemask_epi8(cmp); write_forward!(mask, end, ptr, start_ptr, start, fmt, bytes); } debug_assert!(start <= len); if start < len { fmt.write_str(str::from_utf8_unchecked(&bytes[start..len]))?; } Ok(()) } #[cfg(all(target_arch = "x86_64", askama_runtime_sse))] unsafe fn _sse_escape(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { const VECTOR_SIZE: usize = size_of::<__m128i>(); let len = bytes.len(); let mut start = 0; if len < VECTOR_SIZE { for (i, b) in bytes.iter().enumerate() { write_char!(i, b, start, fmt, bytes); } if start < len { fmt.write_str(str::from_utf8_unchecked(&bytes[start..len]))?; } return Ok(()); } const NEEDLE_LEN: i32 = 6; let needle = _mm_setr_epi8( b'<' as i8, b'>' as i8, b'&' as i8, b'"' as i8, b'\'' as i8, b'/' as i8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ); let start_ptr = bytes.as_ptr(); let end_ptr = bytes[len..].as_ptr(); let mut ptr = start_ptr; while ptr <= end_ptr.sub(VECTOR_SIZE) { let a = _mm_loadu_si128(ptr as *const __m128i); let cmp = _mm_cmpestrm(needle, NEEDLE_LEN, a, VECTOR_SIZE as i32, 0); let mut mask = _mm_extract_epi16(cmp, 0) as i16; if mask != 0 { write_mask!(mask, ptr, start_ptr, start, fmt, bytes); } ptr = ptr.add(VECTOR_SIZE); debug_assert!(start <= sub(ptr, start_ptr)); } debug_assert!(end_ptr.sub(VECTOR_SIZE) < ptr); if ptr < end_ptr { let end = sub(end_ptr, ptr); let a = _mm_loadu_si128(ptr as *const __m128i); let cmp = _mm_cmpestrm(needle, NEEDLE_LEN, a, VECTOR_SIZE as i32, 0); let mut mask = _mm_extract_epi16(cmp, 0) as i16; write_forward!(mask, end, ptr, start_ptr, start, fmt, bytes); } debug_assert!(start <= len); if start < len { fmt.write_str(str::from_utf8_unchecked(&bytes[start..len]))?; } Ok(()) } const LEN: u8 = b'>' - b'"'; const FLAG_BELOW: u8 = b'"'; #[cfg(test)] mod tests { use super::*; #[test] fn test_escape() { let escapes = "<>&\"'/"; let escaped = "&lt;&gt;&amp;&quot;&#x27;&#x2f;"; let string_long: &str = &"foobar".repeat(1024); assert_eq!(escape("").to_string(), ""); assert_eq!(escape("<&>").to_string(), "&lt;&amp;&gt;"); assert_eq!(escape("bar&").to_string(), "bar&amp;"); assert_eq!(escape("<foo").to_string(), "&lt;foo"); assert_eq!(escape("bar&h").to_string(), "bar&amp;h"); assert_eq!( escape("// my <html> is \"unsafe\" & should be 'escaped'").to_string(), "&#x2f;&#x2f; my &lt;html&gt; is &quot;unsafe&quot; &amp; \ should be &#x27;escaped&#x27;" ); assert_eq!(escape(&"<".repeat(16)).to_string(), "&lt;".repeat(16)); assert_eq!(escape(&"<".repeat(32)).to_string(), "&lt;".repeat(32)); assert_eq!(escape(&"<".repeat(64)).to_string(), "&lt;".repeat(64)); assert_eq!(escape(&"<".repeat(128)).to_string(), "&lt;".repeat(128)); assert_eq!(escape(&"<".repeat(1024)).to_string(), "&lt;".repeat(1024)); assert_eq!(escape(&"<".repeat(129)).to_string(), "&lt;".repeat(129)); assert_eq!( escape(&"<".repeat(128 * 2 - 1)).to_string(), "&lt;".repeat(128 * 2 - 1) ); assert_eq!( escape(&"<".repeat(128 * 8 - 1)).to_string(), "&lt;".repeat(128 * 8 - 1) ); assert_eq!(escape(string_long).to_string(), string_long); assert_eq!( escape(&[string_long, "<"].join("")).to_string(), [string_long, "&lt;"].join("") ); assert_eq!( escape(&["<", string_long].join("")).to_string(), ["&lt;", string_long].join("") ); assert_eq!( escape(&escapes.repeat(1024)).to_string(), escaped.repeat(1024) ); assert_eq!( escape(&[string_long, "<", string_long].join("")).to_string(), [string_long, "&lt;", string_long].join("") ); assert_eq!( escape(&[string_long, "<", string_long, escapes, string_long,].join("")).to_string(), [string_long, "&lt;", string_long, escaped, string_long,].join("") ); } }
#[macro_use] extern crate cfg_if; use std::fmt::{self, Display, Formatter}; use std::str; #[derive(Debug, PartialEq)] pub enum MarkupDisplay<T> where T: Display, { Safe(T), Unsafe(T), } impl<T> MarkupDisplay<T> where T: Display, { pub fn mark_safe(self) -> MarkupDisplay<T> { match self { MarkupDisplay::Unsafe(t) => MarkupDisplay::Safe(t), _ => self, } } } impl<T> From<T> for MarkupDisplay<T> where T: Display, { fn from(t: T) -> MarkupDisplay<T> { MarkupDisplay::Unsafe(t) } } impl<T> Display for MarkupDisplay<T> where T: Display, { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { MarkupDisplay::Unsafe(ref t) => escape(&t.to_string()).fmt(f), MarkupDisplay::Safe(ref t) => t.fmt(f), } } } pub fn escape(s: &str) -> Escaped { Escaped { bytes: s.as_bytes(), } } pub struct Escaped<'a> { bytes: &'a [u8], } impl<'a> Display for Escaped<'a> { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { _imp(self.bytes, fmt) } } cfg_if! { if #[cfg(all(target_arch = "x86_64", askama_runtime_simd))] { use std::arch::x86_64::*; use std::mem::{self, size_of}; use std::sync::atomic::{AtomicUsize, Ordering}; #[inline(always)] fn _imp(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { static mut FN: fn(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result = detect; fn detect(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { let fun = if cfg!(askama_runtime_avx) && is_x86_feature_detected!("avx2") { _avx_escape as usize } else if cfg!(askama_runtime_sse) { _sse_escape as usize } else { _escape as usize }; let slot = unsafe { &*(&FN as *const _ as *const AtomicUsize) }; slot.store(fun as usize, Ordering::Relaxed); unsafe { mem::transmute::<usize, fn(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result>(fun)(bytes, fmt) } } unsafe { let slot = &*(&FN as *const _ as * const AtomicUsize); let fun = slot.load(Ordering::Relaxed); mem::transmute::<usize, fn(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result>(fun)(bytes, fmt) } } #[inline(always)] fn sub(a: *const u8, b: *const u8) -> usize { debug_assert!(b <= a); (a as usize) - (b as usize) } } else { #[inline(always)] fn _imp(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { _escape(bytes, fmt) } } } macro_rules! escaping_body { ($i:expr, $start:ident, $fmt:ident, $bytes:ident, $quote:expr) => {{ if $start < $i { #[allow(unused_unsafe)] $fmt.write_str(unsafe { str::from_utf8_unchecked(&$bytes[$start..$i]) })?; } $fmt.write_str($quote)?; $start = $i + 1; }}; } macro_rules! bodies { ($i:expr, $b: ident, $start:ident, $fmt:ident, $bytes:ident, $callback:ident) => { match $b { b'<' => $callback!($i, $start, $fmt, $bytes, "&lt;"), b'>' => $callback!($i, $start, $fmt, $bytes, "&gt;"), b'&' => $callback!($i, $start, $fmt, $bytes, "&amp;"), b'"' => $callback!($i, $start, $fmt, $bytes, "&quot;"), b'\'' => $callback!($i, $start, $fmt, $bytes, "&#x27;"), b'/' => $callback!($i, $start, $fmt, $bytes, "&#x2f;"), _ => (), } }; } macro_rules! write_char { ($i:ident, $ptr: ident, $start: ident, $fmt: ident, $bytes:ident) => {{ let b = *$ptr; if b.wrapping_sub(FLAG_BELOW) <= LEN { bodies!($i, b, $start, $fmt, $bytes, escaping_body); } }}; } #[allow(unused_macros)] macro_rules! mask_body { ($i:expr, $start:ident, $fmt:ident, $bytes:ident, $quote:expr) => {{ let i = $i; escaping_body!(i, $start, $fmt, $bytes, $quote); }}; } #[allow(unused_macros)] macro_rules! mask_bodies { ($mask: ident, $at:ident, $cur: ident, $ptr: ident, $start: ident, $fmt: ident, $bytes:ident) => { let b = *$ptr.add($cur); bodies!($at + $cur, b, $start, $fmt, $bytes, mask_body); $mask ^= 1 << $cur; if $mask == 0 { break; } $cur = $mask.trailing_zeros() as usize; }; } #[allow(unused_macros)] macro_rules! write_mask { ($mask: ident, $ptr: ident, $start_ptr: ident, $start: ident, $fmt: ident, $bytes:ident) => {{ let at = sub($ptr, $start_ptr); let mut cur = $mask.trailing_zeros() as usize; loop { mask_bodies!($mask, at, cur, $ptr, $start, $fmt, $bytes); } debug_assert_eq!(at, sub($ptr, $start_ptr)) }}; } #[allow(unused_macros)] macro_rules! write_forward { ($mask: ident, $align: ident, $ptr: ident, $start_ptr: ident, $start: ident, $fmt: ident, $bytes:ident) => {{ if $mask != 0 { let at = sub($ptr, $start_ptr); let mut cur = $mask.trailing_zeros() as usize; while cur < $align { mask_bodies!($mask, at, cur, $ptr, $start, $fmt, $bytes); } debug_assert_eq!(at, sub($ptr, $start_ptr)) } }}; } fn _escape(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { let mut start = 0; for (i, b) in bytes.iter().enumerate() { write_char!(i, b, start, fmt, bytes); } fmt.write_str(unsafe { str::from_utf8_unchecked(&bytes[start..]) })?; Ok(()) } #[cfg(all(target_arch = "x86_64", askama_runtime_avx))] unsafe fn _avx_escape(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { const VECTOR_SIZE: usize = size_of::<__m256i>(); const VECTOR_ALIGN: usize = VECTOR_SIZE - 1; const LOOP_SIZE: usize = 4 * VECTOR_SIZE; let len = bytes.len(); let mut start = 0; if len < VECTOR_SIZE { for (i, b) in bytes.iter().enumerate() { write_char!(i, b, start, fmt, bytes); } if start < len { fmt.write_str(str::from_utf8_unchecked(&bytes[start..len]))?; } return Ok(()); } let v_flag = _mm25
#[cfg(all(target_arch = "x86_64", askama_runtime_sse))] unsafe fn _sse_escape(bytes: &[u8], fmt: &mut Formatter) -> fmt::Result { const VECTOR_SIZE: usize = size_of::<__m128i>(); let len = bytes.len(); let mut start = 0; if len < VECTOR_SIZE { for (i, b) in bytes.iter().enumerate() { write_char!(i, b, start, fmt, bytes); } if start < len { fmt.write_str(str::from_utf8_unchecked(&bytes[start..len]))?; } return Ok(()); } const NEEDLE_LEN: i32 = 6; let needle = _mm_setr_epi8( b'<' as i8, b'>' as i8, b'&' as i8, b'"' as i8, b'\'' as i8, b'/' as i8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ); let start_ptr = bytes.as_ptr(); let end_ptr = bytes[len..].as_ptr(); let mut ptr = start_ptr; while ptr <= end_ptr.sub(VECTOR_SIZE) { let a = _mm_loadu_si128(ptr as *const __m128i); let cmp = _mm_cmpestrm(needle, NEEDLE_LEN, a, VECTOR_SIZE as i32, 0); let mut mask = _mm_extract_epi16(cmp, 0) as i16; if mask != 0 { write_mask!(mask, ptr, start_ptr, start, fmt, bytes); } ptr = ptr.add(VECTOR_SIZE); debug_assert!(start <= sub(ptr, start_ptr)); } debug_assert!(end_ptr.sub(VECTOR_SIZE) < ptr); if ptr < end_ptr { let end = sub(end_ptr, ptr); let a = _mm_loadu_si128(ptr as *const __m128i); let cmp = _mm_cmpestrm(needle, NEEDLE_LEN, a, VECTOR_SIZE as i32, 0); let mut mask = _mm_extract_epi16(cmp, 0) as i16; write_forward!(mask, end, ptr, start_ptr, start, fmt, bytes); } debug_assert!(start <= len); if start < len { fmt.write_str(str::from_utf8_unchecked(&bytes[start..len]))?; } Ok(()) } const LEN: u8 = b'>' - b'"'; const FLAG_BELOW: u8 = b'"'; #[cfg(test)] mod tests { use super::*; #[test] fn test_escape() { let escapes = "<>&\"'/"; let escaped = "&lt;&gt;&amp;&quot;&#x27;&#x2f;"; let string_long: &str = &"foobar".repeat(1024); assert_eq!(escape("").to_string(), ""); assert_eq!(escape("<&>").to_string(), "&lt;&amp;&gt;"); assert_eq!(escape("bar&").to_string(), "bar&amp;"); assert_eq!(escape("<foo").to_string(), "&lt;foo"); assert_eq!(escape("bar&h").to_string(), "bar&amp;h"); assert_eq!( escape("// my <html> is \"unsafe\" & should be 'escaped'").to_string(), "&#x2f;&#x2f; my &lt;html&gt; is &quot;unsafe&quot; &amp; \ should be &#x27;escaped&#x27;" ); assert_eq!(escape(&"<".repeat(16)).to_string(), "&lt;".repeat(16)); assert_eq!(escape(&"<".repeat(32)).to_string(), "&lt;".repeat(32)); assert_eq!(escape(&"<".repeat(64)).to_string(), "&lt;".repeat(64)); assert_eq!(escape(&"<".repeat(128)).to_string(), "&lt;".repeat(128)); assert_eq!(escape(&"<".repeat(1024)).to_string(), "&lt;".repeat(1024)); assert_eq!(escape(&"<".repeat(129)).to_string(), "&lt;".repeat(129)); assert_eq!( escape(&"<".repeat(128 * 2 - 1)).to_string(), "&lt;".repeat(128 * 2 - 1) ); assert_eq!( escape(&"<".repeat(128 * 8 - 1)).to_string(), "&lt;".repeat(128 * 8 - 1) ); assert_eq!(escape(string_long).to_string(), string_long); assert_eq!( escape(&[string_long, "<"].join("")).to_string(), [string_long, "&lt;"].join("") ); assert_eq!( escape(&["<", string_long].join("")).to_string(), ["&lt;", string_long].join("") ); assert_eq!( escape(&escapes.repeat(1024)).to_string(), escaped.repeat(1024) ); assert_eq!( escape(&[string_long, "<", string_long].join("")).to_string(), [string_long, "&lt;", string_long].join("") ); assert_eq!( escape(&[string_long, "<", string_long, escapes, string_long,].join("")).to_string(), [string_long, "&lt;", string_long, escaped, string_long,].join("") ); } }
6_set1_epi8((LEN + 1) as i8); let v_flag_below = _mm256_set1_epi8(FLAG_BELOW as i8); let start_ptr = bytes.as_ptr(); let end_ptr = bytes[len..].as_ptr(); let mut ptr = start_ptr; debug_assert!(start_ptr <= ptr && start_ptr <= end_ptr.sub(VECTOR_SIZE)); if LOOP_SIZE <= len { { let align = start_ptr as usize & VECTOR_ALIGN; if 0 < align { let a = _mm256_loadu_si256(ptr as *const __m256i); let cmp = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(a, v_flag_below)); let mut mask = _mm256_movemask_epi8(cmp); write_forward!(mask, align, ptr, start_ptr, start, fmt, bytes); ptr = ptr.add(align); debug_assert!(start <= sub(ptr, start_ptr)); } } while ptr <= end_ptr.sub(LOOP_SIZE) { debug_assert_eq!(0, (ptr as usize) % VECTOR_SIZE); let a = _mm256_load_si256(ptr as *const __m256i); let b = _mm256_load_si256(ptr.add(VECTOR_SIZE) as *const __m256i); let c = _mm256_load_si256(ptr.add(VECTOR_SIZE * 2) as *const __m256i); let d = _mm256_load_si256(ptr.add(VECTOR_SIZE * 3) as *const __m256i); let cmp_a = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(a, v_flag_below)); let cmp_b = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(b, v_flag_below)); let cmp_c = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(c, v_flag_below)); let cmp_d = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(d, v_flag_below)); let or1 = _mm256_or_si256(cmp_a, cmp_b); let or2 = _mm256_or_si256(cmp_c, cmp_d); if _mm256_movemask_epi8(_mm256_or_si256(or1, or2)) != 0 { let mut mask = _mm256_movemask_epi8(cmp_a) as i128 | (_mm256_movemask_epi8(cmp_b) as i128) << VECTOR_SIZE | (_mm256_movemask_epi8(cmp_c) as i128) << VECTOR_SIZE * 2 | (_mm256_movemask_epi8(cmp_d) as i128) << VECTOR_SIZE * 3; write_mask!(mask, ptr, start_ptr, start, fmt, bytes); } ptr = ptr.add(LOOP_SIZE); debug_assert!(start <= sub(ptr, start_ptr)); } } while ptr <= end_ptr.sub(VECTOR_SIZE) { let a = _mm256_loadu_si256(ptr as *const __m256i); let cmp = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(a, v_flag_below)); let mut mask = _mm256_movemask_epi8(cmp); if mask != 0 { write_mask!(mask, ptr, start_ptr, start, fmt, bytes); } ptr = ptr.add(VECTOR_SIZE); debug_assert!(start <= sub(ptr, start_ptr)); } debug_assert!(end_ptr.sub(VECTOR_SIZE) < ptr); if ptr < end_ptr { let a = _mm256_loadu_si256(ptr as *const __m256i); let cmp = _mm256_cmpgt_epi8(v_flag, _mm256_sub_epi8(a, v_flag_below)); let end = sub(end_ptr, ptr); let mut mask = _mm256_movemask_epi8(cmp); write_forward!(mask, end, ptr, start_ptr, start, fmt, bytes); } debug_assert!(start <= len); if start < len { fmt.write_str(str::from_utf8_unchecked(&bytes[start..len]))?; } Ok(()) }
function_block-function_prefixed
[ { "content": "/// Limit string length, appends '...' if truncated\n\npub fn truncate(s: &fmt::Display, len: &usize) -> Result<String> {\n\n let mut s = s.to_string();\n\n if s.len() < *len {\n\n Ok(s)\n\n } else {\n\n s.truncate(*len);\n\n s.push_str(\"...\");\n\n Ok(s)\n\n ...
Rust
bee-bundle/src/constants.rs
zesterer/bee-p
375357bdfe8f670e4d26b62a7683d97f339f056f
use common::constants::*; pub struct Offset { pub start: usize, pub length: usize, } pub struct Field { pub trit_offset: Offset, pub tryte_offset: Offset, } impl Field { pub fn byte_start(&self) -> usize { self.trit_offset.start / 5 } pub fn byte_length(&self) -> usize { if self.trit_offset.length % 5 == 0 { self.trit_offset.length / 5 } else { self.trit_offset.length / 5 + 1 } } } macro_rules! offsets_from_trits { ($start:expr, $length:expr) => { Field { trit_offset: Offset { start: $start, length: $length, }, tryte_offset: Offset { start: $start / 3, length: $length / 3, }, } }; } macro_rules! offsets_from_previous_field { ($prev:expr, $length:expr) => { Field { trit_offset: Offset { start: ($prev).trit_offset.start + ($prev).trit_offset.length, length: $length, }, tryte_offset: Offset { start: (($prev).trit_offset.start + ($prev).trit_offset.length) / 3, length: $length / 3, }, } }; } pub const PAYLOAD: Field = offsets_from_trits!(0, PAYLOAD_TRIT_LEN); pub const ADDRESS: Field = offsets_from_previous_field!(PAYLOAD, ADDRESS_TRIT_LEN); pub const VALUE: Field = offsets_from_previous_field!(ADDRESS, VALUE_TRIT_LEN); pub const OBSOLETE_TAG: Field = offsets_from_previous_field!(VALUE, TAG_TRIT_LEN); pub const TIMESTAMP: Field = offsets_from_previous_field!(OBSOLETE_TAG, TIMESTAMP_TRIT_LEN); pub const INDEX: Field = offsets_from_previous_field!(TIMESTAMP, INDEX_TRIT_LEN); pub const LAST_INDEX: Field = offsets_from_previous_field!(INDEX, INDEX_TRIT_LEN); pub const BUNDLE_HASH: Field = offsets_from_previous_field!(LAST_INDEX, HASH_TRIT_LEN); pub const TRUNK_HASH: Field = offsets_from_previous_field!(BUNDLE_HASH, HASH_TRIT_LEN); pub const BRANCH_HASH: Field = offsets_from_previous_field!(TRUNK_HASH, HASH_TRIT_LEN); pub const TAG: Field = offsets_from_previous_field!(BRANCH_HASH, TAG_TRIT_LEN); pub const ATTACHMENT_TS: Field = offsets_from_previous_field!(TAG, TIMESTAMP_TRIT_LEN); pub const ATTACHMENT_LBTS: Field = offsets_from_previous_field!(ATTACHMENT_TS, TIMESTAMP_TRIT_LEN); pub const ATTACHMENT_UBTS: Field = offsets_from_previous_field!(ATTACHMENT_LBTS, TIMESTAMP_TRIT_LEN); pub const NONCE: Field = offsets_from_previous_field!(ATTACHMENT_UBTS, NONCE_TRIT_LEN); #[cfg(test)] mod should { use super::*; use common::constants::*; #[test] fn add_up_to_transaction_trit_length() { let total_trit_length = PAYLOAD.trit_offset.length + ADDRESS.trit_offset.length + VALUE.trit_offset.length + OBSOLETE_TAG.trit_offset.length + TIMESTAMP.trit_offset.length + INDEX.trit_offset.length + LAST_INDEX.trit_offset.length + BUNDLE_HASH.trit_offset.length + TRUNK_HASH.trit_offset.length + BRANCH_HASH.trit_offset.length + TAG.trit_offset.length + ATTACHMENT_TS.trit_offset.length + ATTACHMENT_LBTS.trit_offset.length + ATTACHMENT_UBTS.trit_offset.length + NONCE.trit_offset.length; assert_eq!(total_trit_length, TRANSACTION_TRIT_LEN); } #[test] fn add_up_to_transaction_tryte_length() { let total_tryte_length = PAYLOAD.tryte_offset.length + ADDRESS.tryte_offset.length + VALUE.tryte_offset.length + OBSOLETE_TAG.tryte_offset.length + TIMESTAMP.tryte_offset.length + INDEX.tryte_offset.length + LAST_INDEX.tryte_offset.length + BUNDLE_HASH.tryte_offset.length + TRUNK_HASH.tryte_offset.length + BRANCH_HASH.tryte_offset.length + TAG.tryte_offset.length + ATTACHMENT_TS.tryte_offset.length + ATTACHMENT_LBTS.tryte_offset.length + ATTACHMENT_UBTS.tryte_offset.length + NONCE.tryte_offset.length; assert_eq!(total_tryte_length, TRANSACTION_TRYT_LEN); } }
use common::constants::*; pub struct Offset { pub start: usize, pub length: usize, } pub struct Field { pub trit_offset: Offset, pub tryte_offset: Offset, } impl Field { pub fn byte_start(&self) -> usize { self.trit_offset.start / 5 } pub fn byte_length(&self) -> usize { if self.trit_offset.length % 5 == 0 { self.trit_offset.length / 5 } else { self.trit_offset.length / 5 + 1 } } } macro_rules! offsets_from_trits { ($start:expr, $length:expr) => { Field { trit_offset: Offset { start: $start, length: $length, }, tryte_offset: Offset { start: $start / 3, length: $length / 3, }, } }; } macro_rules! offsets_from_previous_field { ($prev:expr, $length:exp
h + LAST_INDEX.trit_offset.length + BUNDLE_HASH.trit_offset.length + TRUNK_HASH.trit_offset.length + BRANCH_HASH.trit_offset.length + TAG.trit_offset.length + ATTACHMENT_TS.trit_offset.length + ATTACHMENT_LBTS.trit_offset.length + ATTACHMENT_UBTS.trit_offset.length + NONCE.trit_offset.length; assert_eq!(total_trit_length, TRANSACTION_TRIT_LEN); } #[test] fn add_up_to_transaction_tryte_length() { let total_tryte_length = PAYLOAD.tryte_offset.length + ADDRESS.tryte_offset.length + VALUE.tryte_offset.length + OBSOLETE_TAG.tryte_offset.length + TIMESTAMP.tryte_offset.length + INDEX.tryte_offset.length + LAST_INDEX.tryte_offset.length + BUNDLE_HASH.tryte_offset.length + TRUNK_HASH.tryte_offset.length + BRANCH_HASH.tryte_offset.length + TAG.tryte_offset.length + ATTACHMENT_TS.tryte_offset.length + ATTACHMENT_LBTS.tryte_offset.length + ATTACHMENT_UBTS.tryte_offset.length + NONCE.tryte_offset.length; assert_eq!(total_tryte_length, TRANSACTION_TRYT_LEN); } }
r) => { Field { trit_offset: Offset { start: ($prev).trit_offset.start + ($prev).trit_offset.length, length: $length, }, tryte_offset: Offset { start: (($prev).trit_offset.start + ($prev).trit_offset.length) / 3, length: $length / 3, }, } }; } pub const PAYLOAD: Field = offsets_from_trits!(0, PAYLOAD_TRIT_LEN); pub const ADDRESS: Field = offsets_from_previous_field!(PAYLOAD, ADDRESS_TRIT_LEN); pub const VALUE: Field = offsets_from_previous_field!(ADDRESS, VALUE_TRIT_LEN); pub const OBSOLETE_TAG: Field = offsets_from_previous_field!(VALUE, TAG_TRIT_LEN); pub const TIMESTAMP: Field = offsets_from_previous_field!(OBSOLETE_TAG, TIMESTAMP_TRIT_LEN); pub const INDEX: Field = offsets_from_previous_field!(TIMESTAMP, INDEX_TRIT_LEN); pub const LAST_INDEX: Field = offsets_from_previous_field!(INDEX, INDEX_TRIT_LEN); pub const BUNDLE_HASH: Field = offsets_from_previous_field!(LAST_INDEX, HASH_TRIT_LEN); pub const TRUNK_HASH: Field = offsets_from_previous_field!(BUNDLE_HASH, HASH_TRIT_LEN); pub const BRANCH_HASH: Field = offsets_from_previous_field!(TRUNK_HASH, HASH_TRIT_LEN); pub const TAG: Field = offsets_from_previous_field!(BRANCH_HASH, TAG_TRIT_LEN); pub const ATTACHMENT_TS: Field = offsets_from_previous_field!(TAG, TIMESTAMP_TRIT_LEN); pub const ATTACHMENT_LBTS: Field = offsets_from_previous_field!(ATTACHMENT_TS, TIMESTAMP_TRIT_LEN); pub const ATTACHMENT_UBTS: Field = offsets_from_previous_field!(ATTACHMENT_LBTS, TIMESTAMP_TRIT_LEN); pub const NONCE: Field = offsets_from_previous_field!(ATTACHMENT_UBTS, NONCE_TRIT_LEN); #[cfg(test)] mod should { use super::*; use common::constants::*; #[test] fn add_up_to_transaction_trit_length() { let total_trit_length = PAYLOAD.trit_offset.length + ADDRESS.trit_offset.length + VALUE.trit_offset.length + OBSOLETE_TAG.trit_offset.length + TIMESTAMP.trit_offset.length + INDEX.trit_offset.lengt
random
[ { "content": "fn trits_with_length(trits: &[Trit], length: usize) -> Vec<Trit> {\n\n if trits.len() < length {\n\n let mut result = vec![0; length];\n\n result[..trits.len()].copy_from_slice(&trits);\n\n result\n\n } else {\n\n trits[..length].to_vec()\n\n }\n\n}\n", "fi...
Rust
src/client/market.rs
zeta1999/huobi_future_async
e5202c50b15cd1fd22ccb696534bb4c513af1b49
use super::HuobiFuture; use crate::{ models::*, }; use failure::Fallible; use futures::prelude::*; use std::{collections::BTreeMap}; impl HuobiFuture { pub fn get_contract_info<S1, S2, S3>( &self, symbol: S1, contract_type: S2, contract_code: S3 ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<Symbol>>>>> where S1: Into<Option<String>>, S2: Into<Option<String>>, S3: Into<Option<String>>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); if let Some(sy) = symbol.into() { parameters.insert("symbol".into(), format!{"{}", sy});} if let Some(cc) = contract_code.into() { parameters.insert("contract_code".into(), format!("{}", cc));} if let Some(ct) = contract_type.into() { parameters.insert("contract_type".into(), format!("{}", ct));} Ok(self .transport .get("/api/v1/contract_contract_info", Some(parameters))?) } pub fn get_all_book_tickers<S1, S2>( &self, contract_code: S1, orderbook_type: S2, ) -> Fallible<impl Future<Output = Fallible<APIResponse<OrderBook>>>> where S1: Into<String>, S2: Into<String>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), contract_code.into()); parameters.insert("type".into(), orderbook_type.into()); Ok(self .transport .get("/market/depth", Some(parameters))?) } pub fn get_klines<S1, S2, S3, S4, S5>( &self, contract_code: S1, period: S2, size: S3, from: S4, to: S5, ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<Kline>>>>> where S1: Into<String>, S2: Into<String>, S3: Into<Option<u32>>, S4: Into<Option<u32>>, S5: Into<Option<u32>>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), contract_code.into()); parameters.insert("period".into(), period.into()); if let Some(lt) = size.into() { parameters.insert("size".into(), format!{"{}", lt});} if let Some(st) = from.into() { parameters.insert("from".into(), format!("{}", st));} if let Some(et) = to.into() { parameters.insert("to".into(), format!("{}", et));} Ok(self .transport .get("/market/history/kline", Some(parameters))?) } pub fn get_index_klines<S1, S2>( &self, contract_code: S1, period: S2, size: u32, ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<Kline>>>>> where S1: Into<String>, S2: Into<String>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), contract_code.into()); parameters.insert("period".into(), period.into()); parameters.insert("size".into(), format!{"{}", size}); Ok(self .transport .get("/index/market/history/index", Some(parameters))?) } pub fn get_basis<S1, S2, S3>( &self, contract_code: S1, period: S2, basis_price_type: S3, size: u32, ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<Basis>>>>> where S1: Into<String>, S2: Into<String>, S3: Into<Option<String>>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), contract_code.into()); parameters.insert("period".into(), period.into()); parameters.insert("size".into(), format!{"{}", size}); if let Some(bs) = basis_price_type.into() { parameters.insert("basis_price_type".into(), bs);} Ok(self .transport .get("/index/market/history/basis", Some(parameters))?) } pub fn get_merged_data<S1>( &self, symbol: S1, ) -> Fallible<impl Future<Output = Fallible<APIResponse<Merged>>>> where S1: Into<String> { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), symbol.into()); Ok(self .transport .get("/market/detail/merged", Some(parameters))? ) } pub fn get_price_limit<S1, S2, S3>( &self, symbol: S1, contract_type: S2, contract_code: S3 ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<PriceLimit>>>>> where S1: Into<Option<String>>, S2: Into<Option<String>>, S3: Into<Option<String>> { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); if let Some(sym) = symbol.into() { parameters.insert("symbol".into(), sym); } if let Some(ctype) = contract_type.into() { parameters.insert("contract_type".into(), ctype); } if let Some(code) = contract_code.into() { parameters.insert("contract_code".into(), code); } Ok(self .transport .get("/api/v1/contract_price_limit", Some(parameters))? ) } }
use super::HuobiFuture; use crate::{ models::*, }; use failure::Fallible; use futures::prelude::*; use std::{collections::BTreeMap}; impl HuobiFuture { pub fn get_contract_info<S1, S2, S3>( &self, symbol: S1, contract_type: S2, contract_code: S3 ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<Symbol>>>>> where S1: Into<Option<String>>, S2: Into<Option<String>>, S3: Into<Option<String>>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); if let Some(sy) = symbol.into() { parameters.insert("symbol".into(), format!{"{}", sy});} if let Some(cc) = contract_code.into() { parameters.insert("contract_code".into(), format!("{}", cc));} if let Some(ct) = contract_type.into() { parameters.insert("contract_type".into(), format!("{}", ct));} Ok(self .transport .get("/api/v1/contract_contract_info", Some(parameters))?) } pub fn get_all_book_tickers<S1, S2>( &self, contract_code: S1, orderbook_type: S2, ) -> Fallible<impl Future<Output = Fallible<APIResponse<OrderBook>>>> where S1: Into<String>, S2: Into<String>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), contract_code.into()); parameters.insert("type".into(), orderbook_type.into()); Ok(self .transport .get("/market/depth", Some(parameters))?) } pub fn get_klines<S1, S2, S3, S4, S5>( &self, contract_code: S1, period: S2, size: S3, from: S4, to: S5, ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<Kline>>>>> where S1: Into<String>, S2: Into<String>, S3: Into<Option<u32>>, S4: Into<Option<u32>>, S5: Into<Option<u32>>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), contract_code.into()); parameters.insert("period".into(), period.into()); if let Some(lt) = size.into() { parameters.insert("size".into(), format!{"{}", lt});} if let Some(st) = from.into() { parameters.insert("from".into(), format!("{}", st));} if let Some(et) = to.into() { parameters.insert("to".into(), format!("{}", et));} Ok(self .transport .get("/market/history/kline", Some(parameters))?) } pub fn get_index_klines<S1, S2>( &self, contract_code: S1, period: S2, size: u32, ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<Kline>>>>> where S1: Into<String>, S2: Into<String>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), contract_code.into()); parameters.insert("period".into(), period.into()); parameters.insert("size".into(), format!{"{}", size}); Ok(self .transport .get("/index/market/history/index", Some(parameters))?) } pub fn get_basis<S1, S2, S3>( &self, contract_code: S1, period: S2, basis_price_type: S3, size: u32, ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<Basis>>>>> where S1: Into<String>, S2: Into<String>, S3: Into<Option<String>>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), contract_code.into()); parameters.insert("period".into(), period.into()); parameters.insert("size".into(), format!{"{}", size}); if let Some(bs) = basis_price_type.into() { parameters.insert("basis_price_type".into(), bs);} Ok(self .transport .get("/index/market/history/basis", Some(parameters))?) } pub fn get_merged_data<S1>( &self, symbol: S1, ) -> Fallible<impl Future<Output = Fallible<APIResponse<Merged>>>> where S1: Into<String> { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), symbol.into()); Ok(self .transport .get("/market/detail/merged", Some(parameters))? ) }
}
pub fn get_price_limit<S1, S2, S3>( &self, symbol: S1, contract_type: S2, contract_code: S3 ) -> Fallible<impl Future<Output = Fallible<APIResponse<Vec<PriceLimit>>>>> where S1: Into<Option<String>>, S2: Into<Option<String>>, S3: Into<Option<String>> { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); if let Some(sym) = symbol.into() { parameters.insert("symbol".into(), sym); } if let Some(ctype) = contract_type.into() { parameters.insert("contract_type".into(), ctype); } if let Some(code) = contract_code.into() { parameters.insert("contract_code".into(), code); } Ok(self .transport .get("/api/v1/contract_price_limit", Some(parameters))? ) }
function_block-full_function
[ { "content": "pub fn build_query_string(parameters: &[(String,String)]) -> String \n\n{\n\n parameters\n\n .iter()\n\n .map(|(key, value)| format!(\"{}={}\", key, percent_encode(&value.clone())))\n\n .collect::<Vec<String>>()\n\n .join(\"&\")\n\n}\n\n\n", "file_path": "src/tra...
Rust
src/cigar.rs
Daniel-Liu-c0deb0t/block-aligner
b54c09e0210605bd56c85e950aa9cd1cbf1c1f31
use std::fmt; #[derive(Debug, PartialEq, Copy, Clone)] #[repr(u8)] pub enum Operation { Sentinel = 0u8, M = 1u8, I = 2u8, D = 3u8 } #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct OpLen { pub op: Operation, pub len: usize } pub struct Cigar { s: Vec<OpLen>, idx: usize } impl Cigar { pub fn new(query_len: usize, reference_len: usize) -> Self { let s = vec![OpLen { op: Operation::Sentinel, len: 0 }; query_len + reference_len + 5]; let idx = 1; Cigar { s, idx } } #[allow(dead_code)] pub(crate) fn clear(&mut self, query_len: usize, reference_len: usize) { self.s[..query_len + reference_len + 5].fill(OpLen { op: Operation::Sentinel, len: 0 }); self.idx = 1; } #[allow(dead_code)] pub(crate) unsafe fn add(&mut self, op: Operation) { debug_assert!(self.idx < self.s.len()); let add = (op != (*self.s.as_ptr().add(self.idx - 1)).op) as usize; self.idx += add; (*self.s.as_mut_ptr().add(self.idx - 1)).op = op; (*self.s.as_mut_ptr().add(self.idx - 1)).len += 1; } pub fn len(&self) -> usize { self.idx - 1 } pub fn get(&self, i: usize) -> OpLen { self.s[self.idx - 1 - i] } pub fn format(&self, q: &[u8], r: &[u8]) -> (String, String) { let mut a = String::with_capacity(self.idx); let mut b = String::with_capacity(self.idx); let mut i = 0; let mut j = 0; for &op_len in self.s[1..self.idx].iter().rev() { match op_len.op { Operation::M => { for _k in 0..op_len.len { a.push(q[i] as char); b.push(r[j] as char); i += 1; j += 1; } }, Operation::I => { for _k in 0..op_len.len { a.push(q[i] as char); b.push('-'); i += 1; } }, Operation::D => { for _k in 0..op_len.len { a.push('-'); b.push(r[j] as char); j += 1; } }, _ => continue } } (a, b) } pub fn to_vec(&self) -> Vec<OpLen> { self.s[1..self.idx] .iter() .rev() .map(|&op_len| op_len) .collect::<Vec<OpLen>>() } } impl fmt::Display for Cigar { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for &op_len in self.s[1..self.idx].iter().rev() { let c = match op_len.op { Operation::M => 'M', Operation::I => 'I', Operation::D => 'D', _ => continue }; write!(f, "{}{}", op_len.len, c)?; } Ok(()) } }
use std::fmt; #[derive(Debug, PartialEq, Copy, Clone)] #[repr(u8)] pub enum Operation { Sentinel = 0u8, M = 1u8, I = 2u8, D = 3u8 } #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct OpLen { pub op: Operation, pub len: usize } pub struct Cigar { s: Vec<OpLen>, idx: usize } impl Cigar { pub fn new(query_len: usize, reference_len: usize) -> Self { let s = vec![OpLen { op: Operation::Sentinel, len: 0 }; query_len + reference_len + 5]; let idx = 1; Cigar { s, idx } } #[allow(dead_code)] pub(crate) fn clear(&mut self, query_len: usize, reference_len: usize) { self.s[..query_len + reference_len + 5].fill(OpLen { op: Operation::Sentinel, len: 0 }); self.idx = 1; } #[allow(dead_code)] pub(crate) unsafe fn add(&mut self, op: Operation) { debug_assert!(self.idx < self.s.len()); let add = (op != (*self.s.as_ptr().add(self.idx - 1)).op) as usize; self.idx += add; (*self.s.as_mut_ptr().add(self.idx - 1)).op = op; (*self.s.as_mut_ptr().add(self.idx - 1)).len += 1; } pub fn len(&self) -> usize { self.idx - 1 } pub fn get(&self, i: usize) -> OpLen { self.s[self.idx - 1 - i] } pub fn format(&self, q: &[u8], r: &[u8]) -> (String, String) { let mut a = String::with_capacity(self.idx); let mut b = String::with_capacity(self.idx); let mut i = 0; let mut j = 0; for &op_len in self.s[1..self.idx].iter().rev() { match op_len.op { Operation::M => { for _k in 0..op_len.len { a.push(q[i] as char); b.push(r[j] as char); i += 1; j += 1; } }, Operation::I => { for _k in 0..op_len.len { a.push(q[i] as char); b.push('-'); i += 1; } }, Operation::D => { for _k in 0..op_len.len { a.push('-'); b.push(r[j] as char); j += 1; } }, _ => continue } } (a, b) } pub fn to_vec(&self) -> Vec<OpLen> { self.s[1..self.idx] .iter() .rev() .map(|&op_len| op_len) .collect::<Vec<OpLen>>() } } impl fmt::Display for Cigar { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for &op_len in self.s[1..self.idx].iter().rev() { let c =
; write!(f, "{}{}", op_len.len, c)?; } Ok(()) } }
match op_len.op { Operation::M => 'M', Operation::I => 'I', Operation::D => 'D', _ => continue }
if_condition
[ { "content": "/// Given an input byte string, create a randomly mutated copy and\n\n/// add random suffixes to both strings.\n\npub fn rand_mutate_suffix<R: Rng>(a: &mut Vec<u8>, k: usize, alpha: &[u8], suffix_len: usize, rng: &mut R) -> Vec<u8> {\n\n let mut b = rand_mutate(a, k, alpha, rng);\n\n let a_s...
Rust
pallets/account-linker/src/lib.rs
FueledAmp/litentry-node
bb703fbd06f45824c79c32a3e938799f07e9442d
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use sp_std::prelude::*; use sp_io::crypto::secp256k1_ecdsa_recover_compressed; use frame_support::{decl_module, decl_storage, decl_event, decl_error, dispatch, ensure}; use frame_system::{ensure_signed}; use btc::base58::ToBase58; use btc::witness::WitnessProgram; #[cfg(test)] mod mock; #[cfg(test)] mod tests; mod btc; mod util_eth; mod benchmarking; const EXPIRING_BLOCK_NUMBER_MAX: u32 = 10 * 60 * 24 * 30; pub const MAX_ETH_LINKS: usize = 3; pub const MAX_BTC_LINKS: usize = 3; pub trait Config: frame_system::Config { type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>; } enum BTCAddrType { Legacy, Segwit, } decl_storage! { trait Store for Module<T: Config> as AccountLinkerModule { pub EthereumLink get(fn eth_addresses): map hasher(blake2_128_concat) T::AccountId => Vec<[u8; 20]>; pub BitcoinLink get(fn btc_addresses): map hasher(blake2_128_concat) T::AccountId => Vec<Vec<u8>>; } } decl_event!( pub enum Event<T> where AccountId = <T as frame_system::Config>::AccountId, { EthAddressLinked(AccountId, Vec<u8>), BtcAddressLinked(AccountId, Vec<u8>), } ); decl_error! { pub enum Error for Module<T: Config> { EcdsaRecoverFailure, LinkRequestExpired, UnexpectedAddress, UnexpectedEthMsgLength, InvalidBTCAddress, InvalidBTCAddressLength, InvalidExpiringBlockNumber, } } decl_module! { pub struct Module<T: Config> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; #[weight = 1] pub fn link_eth( origin, account: T::AccountId, index: u32, addr_expected: [u8; 20], expiring_block_number: T::BlockNumber, r: [u8; 32], s: [u8; 32], v: u8, ) -> dispatch::DispatchResult { let _ = ensure_signed(origin)?; let current_block_number = <frame_system::Module<T>>::block_number(); ensure!(expiring_block_number > current_block_number, Error::<T>::LinkRequestExpired); ensure!((expiring_block_number - current_block_number) < T::BlockNumber::from(EXPIRING_BLOCK_NUMBER_MAX), Error::<T>::InvalidExpiringBlockNumber); let mut bytes = b"Link Litentry: ".encode(); let mut account_vec = account.encode(); let mut expiring_block_number_vec = expiring_block_number.encode(); bytes.append(&mut account_vec); bytes.append(&mut expiring_block_number_vec); let hash = util_eth::eth_data_hash(bytes).map_err(|_| Error::<T>::UnexpectedEthMsgLength)?; let mut msg = [0u8; 32]; let mut sig = [0u8; 65]; msg[..32].copy_from_slice(&hash[..32]); sig[..32].copy_from_slice(&r[..32]); sig[32..64].copy_from_slice(&s[..32]); sig[64] = v; let addr = util_eth::addr_from_sig(msg, sig) .map_err(|_| Error::<T>::EcdsaRecoverFailure)?; ensure!(addr == addr_expected, Error::<T>::UnexpectedAddress); let index = index as usize; let mut addrs = Self::eth_addresses(&account); if (index >= addrs.len()) && (addrs.len() != MAX_ETH_LINKS) { addrs.push(addr.clone()); } else if (index >= addrs.len()) && (addrs.len() == MAX_ETH_LINKS) { addrs[MAX_ETH_LINKS - 1] = addr.clone(); } else { addrs[index] = addr.clone(); } <EthereumLink<T>>::insert(account.clone(), addrs); Self::deposit_event(RawEvent::EthAddressLinked(account, addr.to_vec())); Ok(()) } #[weight = 1] pub fn link_btc( origin, account: T::AccountId, index: u32, addr_expected: Vec<u8>, expiring_block_number: T::BlockNumber, r: [u8; 32], s: [u8; 32], v: u8, ) -> dispatch::DispatchResult { let _ = ensure_signed(origin)?; let current_block_number = <frame_system::Module<T>>::block_number(); ensure!(expiring_block_number > current_block_number, Error::<T>::LinkRequestExpired); ensure!((expiring_block_number - current_block_number) < T::BlockNumber::from(EXPIRING_BLOCK_NUMBER_MAX), Error::<T>::InvalidExpiringBlockNumber); if addr_expected.len() < 2 { Err(Error::<T>::InvalidBTCAddressLength)? } let addr_type = if addr_expected[0] == b'1' { BTCAddrType::Legacy } else if addr_expected[0] == b'b' && addr_expected[1] == b'c' { BTCAddrType::Segwit } else { Err(Error::<T>::InvalidBTCAddress)? }; let mut bytes = b"Link Litentry: ".encode(); let mut account_vec = account.encode(); let mut expiring_block_number_vec = expiring_block_number.encode(); bytes.append(&mut account_vec); bytes.append(&mut expiring_block_number_vec); let hash = sp_io::hashing::keccak_256(&bytes); let mut msg = [0u8; 32]; let mut sig = [0u8; 65]; msg[..32].copy_from_slice(&hash[..32]); sig[..32].copy_from_slice(&r[..32]); sig[32..64].copy_from_slice(&s[..32]); sig[64] = v; let pk = secp256k1_ecdsa_recover_compressed(&sig, &msg) .map_err(|_| Error::<T>::EcdsaRecoverFailure)?; let addr = match addr_type { BTCAddrType::Legacy => { btc::legacy::btc_addr_from_pk(&pk).to_base58() }, BTCAddrType::Segwit => { let pk_hash = btc::legacy::hash160(&pk); let mut pk = [0u8; 22]; pk[0] = 0; pk[1] = 20; pk[2..].copy_from_slice(&pk_hash); let wp = WitnessProgram::from_scriptpubkey(&pk.to_vec()).map_err(|_| Error::<T>::InvalidBTCAddress)?; wp.to_address(b"bc".to_vec()).map_err(|_| Error::<T>::InvalidBTCAddress)? } }; ensure!(addr == addr_expected, Error::<T>::UnexpectedAddress); let index = index as usize; let mut addrs = Self::btc_addresses(&account); if (index >= addrs.len()) && (addrs.len() != MAX_BTC_LINKS) { addrs.push(addr.clone()); } else if (index >= addrs.len()) && (addrs.len() == MAX_BTC_LINKS) { addrs[MAX_BTC_LINKS - 1] = addr.clone(); } else { addrs[index] = addr.clone(); } <BitcoinLink<T>>::insert(account.clone(), addrs); Self::deposit_event(RawEvent::BtcAddressLinked(account, addr)); Ok(()) } } }
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use sp_std::prelude::*; use sp_io::crypto::secp256k1_ecdsa_recover_compressed; use frame_support::{decl_module, decl_storage, decl_event, decl_error, dispatch, ensure}; use frame_system::{ensure_signed}; use btc::base58::ToBase58; use btc::witness::WitnessProgram; #[cfg(test)] mod mock; #[cfg(test)] mod tests; mod btc; mod util_eth; mod benchmarking; const EXPIRING_BLOCK_NUMBER_MAX: u32 = 10 * 60 * 24 * 30; pub const MAX_ETH_LINKS: usize = 3; pub const MAX_BTC_LINKS: usize = 3; pub trait Config: frame_system::Config { type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>; } enum BTCAddrType { Legacy, Segwit, } decl_storage! { trait Store for Module<T: Config> as AccountLinkerModule { pub EthereumLink get(fn eth_addresses): map hasher(blake2_128_concat) T::AccountId => Vec<[u8; 20]>; pub BitcoinLink get(fn btc_addresses): map hasher(blake2_128_concat) T::AccountId => Vec<Vec<u8>>; } } decl_event!( pub enum Event<T> where AccountId = <T as frame_system::Config>::AccountId, { EthAddressLinked(AccountId, Vec<u8>), BtcAddressLinked(AccountId, Vec<u8>), } ); decl_error! { pub enum Error for Module<T: Config> { EcdsaRecoverFailure, LinkRequestExpired, UnexpectedAddress, UnexpectedEthMsgLength, InvalidBTCAddress, InvalidBTCAddressLength, InvalidExpiringBlockNumber, } } decl_module! { pub struct Module<T: Config> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; #[weight = 1] pub fn link_eth( origin, account: T::AccountId, index: u32, addr_expected: [u8; 20], expiring_block_number: T::BlockNumber, r: [u8; 32], s: [u8; 32], v: u8, ) -> dispatch::DispatchResult { let _ = ensure_signed(origin)?; let current_block_number = <frame_system::Module<T>>::block_number(); ensure!(expiring_block_num
nt); if (index >= addrs.len()) && (addrs.len() != MAX_ETH_LINKS) { addrs.push(addr.clone()); } else if (index >= addrs.len()) && (addrs.len() == MAX_ETH_LINKS) { addrs[MAX_ETH_LINKS - 1] = addr.clone(); } else { addrs[index] = addr.clone(); } <EthereumLink<T>>::insert(account.clone(), addrs); Self::deposit_event(RawEvent::EthAddressLinked(account, addr.to_vec())); Ok(()) } #[weight = 1] pub fn link_btc( origin, account: T::AccountId, index: u32, addr_expected: Vec<u8>, expiring_block_number: T::BlockNumber, r: [u8; 32], s: [u8; 32], v: u8, ) -> dispatch::DispatchResult { let _ = ensure_signed(origin)?; let current_block_number = <frame_system::Module<T>>::block_number(); ensure!(expiring_block_number > current_block_number, Error::<T>::LinkRequestExpired); ensure!((expiring_block_number - current_block_number) < T::BlockNumber::from(EXPIRING_BLOCK_NUMBER_MAX), Error::<T>::InvalidExpiringBlockNumber); if addr_expected.len() < 2 { Err(Error::<T>::InvalidBTCAddressLength)? } let addr_type = if addr_expected[0] == b'1' { BTCAddrType::Legacy } else if addr_expected[0] == b'b' && addr_expected[1] == b'c' { BTCAddrType::Segwit } else { Err(Error::<T>::InvalidBTCAddress)? }; let mut bytes = b"Link Litentry: ".encode(); let mut account_vec = account.encode(); let mut expiring_block_number_vec = expiring_block_number.encode(); bytes.append(&mut account_vec); bytes.append(&mut expiring_block_number_vec); let hash = sp_io::hashing::keccak_256(&bytes); let mut msg = [0u8; 32]; let mut sig = [0u8; 65]; msg[..32].copy_from_slice(&hash[..32]); sig[..32].copy_from_slice(&r[..32]); sig[32..64].copy_from_slice(&s[..32]); sig[64] = v; let pk = secp256k1_ecdsa_recover_compressed(&sig, &msg) .map_err(|_| Error::<T>::EcdsaRecoverFailure)?; let addr = match addr_type { BTCAddrType::Legacy => { btc::legacy::btc_addr_from_pk(&pk).to_base58() }, BTCAddrType::Segwit => { let pk_hash = btc::legacy::hash160(&pk); let mut pk = [0u8; 22]; pk[0] = 0; pk[1] = 20; pk[2..].copy_from_slice(&pk_hash); let wp = WitnessProgram::from_scriptpubkey(&pk.to_vec()).map_err(|_| Error::<T>::InvalidBTCAddress)?; wp.to_address(b"bc".to_vec()).map_err(|_| Error::<T>::InvalidBTCAddress)? } }; ensure!(addr == addr_expected, Error::<T>::UnexpectedAddress); let index = index as usize; let mut addrs = Self::btc_addresses(&account); if (index >= addrs.len()) && (addrs.len() != MAX_BTC_LINKS) { addrs.push(addr.clone()); } else if (index >= addrs.len()) && (addrs.len() == MAX_BTC_LINKS) { addrs[MAX_BTC_LINKS - 1] = addr.clone(); } else { addrs[index] = addr.clone(); } <BitcoinLink<T>>::insert(account.clone(), addrs); Self::deposit_event(RawEvent::BtcAddressLinked(account, addr)); Ok(()) } } }
ber > current_block_number, Error::<T>::LinkRequestExpired); ensure!((expiring_block_number - current_block_number) < T::BlockNumber::from(EXPIRING_BLOCK_NUMBER_MAX), Error::<T>::InvalidExpiringBlockNumber); let mut bytes = b"Link Litentry: ".encode(); let mut account_vec = account.encode(); let mut expiring_block_number_vec = expiring_block_number.encode(); bytes.append(&mut account_vec); bytes.append(&mut expiring_block_number_vec); let hash = util_eth::eth_data_hash(bytes).map_err(|_| Error::<T>::UnexpectedEthMsgLength)?; let mut msg = [0u8; 32]; let mut sig = [0u8; 65]; msg[..32].copy_from_slice(&hash[..32]); sig[..32].copy_from_slice(&r[..32]); sig[32..64].copy_from_slice(&s[..32]); sig[64] = v; let addr = util_eth::addr_from_sig(msg, sig) .map_err(|_| Error::<T>::EcdsaRecoverFailure)?; ensure!(addr == addr_expected, Error::<T>::UnexpectedAddress); let index = index as usize; let mut addrs = Self::eth_addresses(&accou
random
[ { "content": "pub fn hash160(bytes: &[u8]) -> [u8; 20] {\n\n let mut hasher_sha256 = Sha256::new();\n\n hasher_sha256.update(bytes);\n\n let digest = hasher_sha256.finalize();\n\n\n\n let mut hasher_ripemd = Ripemd160::new();\n\n hasher_ripemd.update(digest);\n\n\n\n let mut ret = [0; 20];\n\n...
Rust
ezgui/src/screen_geom.rs
accelsao/abstreet
eca71d27c95abd74a96863ed20bbd92c7850cd33
use crate::Canvas; use geom::{trim_f64, Polygon, Pt2D}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq)] pub struct ScreenPt { pub x: f64, pub y: f64, } impl ScreenPt { pub fn new(x: f64, y: f64) -> ScreenPt { ScreenPt { x, y } } pub fn to_pt(self) -> Pt2D { Pt2D::new(self.x, self.y) } } impl From<winit::dpi::LogicalPosition<f64>> for ScreenPt { fn from(lp: winit::dpi::LogicalPosition<f64>) -> ScreenPt { ScreenPt { x: lp.x, y: lp.y } } } #[derive(Clone, Debug)] pub struct ScreenRectangle { pub x1: f64, pub y1: f64, pub x2: f64, pub y2: f64, } impl ScreenRectangle { pub fn top_left(top_left: ScreenPt, dims: ScreenDims) -> ScreenRectangle { ScreenRectangle { x1: top_left.x, y1: top_left.y, x2: top_left.x + dims.width, y2: top_left.y + dims.height, } } pub fn placeholder() -> ScreenRectangle { ScreenRectangle { x1: 0.0, y1: 0.0, x2: 0.0, y2: 0.0, } } pub fn contains(&self, pt: ScreenPt) -> bool { pt.x >= self.x1 && pt.x <= self.x2 && pt.y >= self.y1 && pt.y <= self.y2 } pub fn pt_to_percent(&self, pt: ScreenPt) -> Option<(f64, f64)> { if self.contains(pt) { Some(( (pt.x - self.x1) / self.width(), (pt.y - self.y1) / self.height(), )) } else { None } } pub fn percent_to_pt(&self, x: f64, y: f64) -> ScreenPt { ScreenPt::new(self.x1 + x * self.width(), self.y1 + y * self.height()) } pub fn width(&self) -> f64 { self.x2 - self.x1 } pub fn height(&self) -> f64 { self.y2 - self.y1 } pub fn dims(&self) -> ScreenDims { ScreenDims::new(self.x2 - self.x1, self.y2 - self.y1) } pub fn center(&self) -> ScreenPt { ScreenPt::new((self.x1 + self.x2) / 2.0, (self.y1 + self.y2) / 2.0) } pub fn to_polygon(&self) -> Polygon { Polygon::rectangle(self.width(), self.height()).translate(self.x1, self.y1) } } #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub struct ScreenDims { pub width: f64, pub height: f64, } impl ScreenDims { pub fn new(width: f64, height: f64) -> ScreenDims { ScreenDims { width: trim_f64(width), height: trim_f64(height), } } pub fn top_left_for_corner(&self, corner: ScreenPt, canvas: &Canvas) -> ScreenPt { if corner.x + self.width < canvas.window_width { if corner.y + self.height < canvas.window_height { corner } else { ScreenPt::new(corner.x, corner.y - self.height) } } else { if corner.y + self.height < canvas.window_height { ScreenPt::new(corner.x - self.width, corner.y) } else { ScreenPt::new(corner.x - self.width, corner.y - self.height) } } } pub fn scaled(&self, factor: f64) -> ScreenDims { ScreenDims::new(self.width * factor, self.height * factor) } } impl From<winit::dpi::LogicalSize<f64>> for ScreenDims { fn from(size: winit::dpi::LogicalSize<f64>) -> ScreenDims { ScreenDims { width: size.width, height: size.height, } } } impl From<ScreenDims> for winit::dpi::LogicalSize<f64> { fn from(dims: ScreenDims) -> winit::dpi::LogicalSize<f64> { winit::dpi::LogicalSize::new(dims.width, dims.height) } }
use crate::Canvas; use geom::{trim_f64, Polygon, Pt2D}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq)] pub struct ScreenPt { pub x: f64, pub y: f64, } impl ScreenPt { pub fn new(x: f64, y: f64) -> ScreenPt { ScreenPt { x, y } } pub fn to_pt(self) -> Pt2D { Pt2D::new(self.x, self.y) } } impl From<winit::dpi::LogicalPosition<f64>> for ScreenPt { fn from(lp: winit::dpi::LogicalPosition<f64>) -> ScreenPt { ScreenPt { x: lp.x, y: lp.y } } } #[derive(Clone, Debug)] pub struct ScreenRectangle { pub x1: f64, pub y1: f64, pub x2: f64, pub y2: f64, } impl ScreenRectangle { pub fn top_left(top_left: ScreenPt, dims: ScreenDims) -> ScreenRectangle { ScreenRectangle { x1: top_left.x, y1: top_left.y, x2: top_left.x + dims.width, y2: top_left.y + dims.height, } } pub fn placeholder() -> ScreenRectangle { ScreenRectangle { x1: 0.0, y1: 0.0, x2: 0.0, y2: 0.0, } } pub fn contains(&self, pt: ScreenPt) -> bool { pt.x >= self.x1 && pt.x <= self.x2 && pt.y >= self.y1 && pt.y <= self.y2 } pub fn pt_to_percent(&self, pt: ScreenPt) -> Option<(f64, f64)> { if self.contains(pt) { Some(( (pt.x - self.x1) / self.width(), (pt.y - self.y1) / self.height(), )) } else { None } } pub fn percent_to_pt(&self, x: f64, y: f64) -> ScreenPt { ScreenPt::new(self.x1 + x * self.width(), self.y1 + y * self.height()) } pub fn width(&self) -> f64 { self.x2 - self.x1 } pub fn height(&self) -> f64 { self.y2 - self.y1 } pub fn dims(&self) -> ScreenDims { ScreenDims::new(self.x2 - self.x1, self.y2 - self.y1) } pub fn center(&self) -> ScreenPt { ScreenPt::new((self.x1 + self.x2) / 2.0, (self.y1 + self.y2) / 2.0) } pub fn to_polygon(&self) -> Polygon { Polygon::rectangle(self.width(), self.height()).translate(self.x1, self.y1) } } #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub struct ScreenDims { pub width: f64, pub height: f64, } impl ScreenDims { pub fn new(width: f64, height: f64) -> ScreenDims { ScreenDims { width: trim_f64(width), height: trim_f64(height), } } pub fn top_left_for_corner(&self, corner: ScreenPt, canvas: &Canvas) -> ScreenPt {
} pub fn scaled(&self, factor: f64) -> ScreenDims { ScreenDims::new(self.width * factor, self.height * factor) } } impl From<winit::dpi::LogicalSize<f64>> for ScreenDims { fn from(size: winit::dpi::LogicalSize<f64>) -> ScreenDims { ScreenDims { width: size.width, height: size.height, } } } impl From<ScreenDims> for winit::dpi::LogicalSize<f64> { fn from(dims: ScreenDims) -> winit::dpi::LogicalSize<f64> { winit::dpi::LogicalSize::new(dims.width, dims.height) } }
if corner.x + self.width < canvas.window_width { if corner.y + self.height < canvas.window_height { corner } else { ScreenPt::new(corner.x, corner.y - self.height) } } else { if corner.y + self.height < canvas.window_height { ScreenPt::new(corner.x - self.width, corner.y) } else { ScreenPt::new(corner.x - self.width, corner.y - self.height) } }
if_condition
[ { "content": "fn area_under_curve(raw: Vec<(Time, usize)>, width: f64, height: f64) -> Polygon {\n\n assert!(!raw.is_empty());\n\n let min_x = Time::START_OF_DAY;\n\n let min_y = 0;\n\n let max_x = raw.last().unwrap().0;\n\n let max_y = raw.iter().max_by_key(|(_, cnt)| *cnt).unwrap().1;\n\n\n\n ...
Rust
crates/witx2/src/interface.rs
yowl/witx-bindgen
9c10658073776e0ea4e3e30cef295cb1e306ecb0
use crate::{ abi::Abi, ast::interface::{Ast, Item}, rewrite_error, }; use anyhow::{bail, Context, Result}; use id_arena::{Arena, Id}; use std::collections::{HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; #[derive(Debug, Clone)] pub struct Interface { pub name: String, pub types: Arena<TypeDef>, pub type_lookup: HashMap<String, TypeId>, pub resources: Arena<Resource>, pub resource_lookup: HashMap<String, ResourceId>, pub interfaces: Arena<Interface>, pub interface_lookup: HashMap<String, InterfaceId>, pub functions: Vec<Function>, pub globals: Vec<Global>, } pub type TypeId = Id<TypeDef>; pub type ResourceId = Id<Resource>; pub type InterfaceId = Id<Interface>; #[derive(Debug, Clone)] pub struct TypeDef { pub docs: Docs, pub kind: TypeDefKind, pub name: Option<String>, pub foreign_module: Option<String>, } #[derive(Debug, Clone)] pub enum TypeDefKind { Record(Record), Variant(Variant), List(Type), Pointer(Type), ConstPointer(Type), PushBuffer(Type), PullBuffer(Type), Type(Type), } #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum Type { U8, U16, U32, U64, S8, S16, S32, S64, F32, F64, Char, CChar, Usize, Handle(ResourceId), Id(TypeId), } #[derive(PartialEq, Debug, Copy, Clone)] pub enum Int { U8, U16, U32, U64, } #[derive(Debug, Clone)] pub struct Record { pub fields: Vec<Field>, pub kind: RecordKind, } #[derive(Copy, Clone, Debug)] pub enum RecordKind { Other, Flags(Option<Int>), Tuple, } #[derive(Debug, Clone)] pub struct Field { pub docs: Docs, pub name: String, pub ty: Type, } impl Record { pub fn is_tuple(&self) -> bool { matches!(self.kind, RecordKind::Tuple) } pub fn is_flags(&self) -> bool { matches!(self.kind, RecordKind::Flags(_)) } pub fn num_i32s(&self) -> usize { (self.fields.len() + 31) / 32 } } impl RecordKind { pub fn infer(types: &Arena<TypeDef>, fields: &[Field]) -> RecordKind { if fields.is_empty() { return RecordKind::Other; } if fields.iter().all(|t| is_bool(&t.ty, types)) { return RecordKind::Flags(None); } if fields .iter() .enumerate() .all(|(i, m)| m.name.as_str().parse().ok() == Some(i)) { return RecordKind::Tuple; } return RecordKind::Other; fn is_bool(t: &Type, types: &Arena<TypeDef>) -> bool { match t { Type::Id(v) => match &types[*v].kind { TypeDefKind::Variant(v) => v.is_bool(), TypeDefKind::Type(t) => is_bool(t, types), _ => false, }, _ => false, } } } } #[derive(Debug, Clone)] pub struct Variant { pub cases: Vec<Case>, pub tag: Int, } #[derive(Debug, Clone)] pub struct Case { pub docs: Docs, pub name: String, pub ty: Option<Type>, } impl Variant { pub fn infer_tag(cases: usize) -> Int { match cases { n if n <= u8::max_value() as usize => Int::U8, n if n <= u16::max_value() as usize => Int::U16, n if n <= u32::max_value() as usize => Int::U32, n if n <= u64::max_value() as usize => Int::U64, _ => panic!("too many cases to fit in a repr"), } } pub fn is_bool(&self) -> bool { self.cases.len() == 2 && self.cases[0].name == "false" && self.cases[1].name == "true" && self.cases[0].ty.is_none() && self.cases[1].ty.is_none() } pub fn is_enum(&self) -> bool { self.cases.iter().all(|c| c.ty.is_none()) } pub fn as_option(&self) -> Option<&Type> { if self.cases.len() != 2 { return None; } if self.cases[0].name != "none" || self.cases[0].ty.is_some() { return None; } if self.cases[1].name != "some" { return None; } self.cases[1].ty.as_ref() } pub fn as_expected(&self) -> Option<(Option<&Type>, Option<&Type>)> { if self.cases.len() != 2 { return None; } if self.cases[0].name != "ok" { return None; } if self.cases[1].name != "err" { return None; } Some((self.cases[0].ty.as_ref(), self.cases[1].ty.as_ref())) } } #[derive(Clone, Default, Debug)] pub struct Docs { pub contents: Option<String>, } impl<'a, T, U> From<T> for Docs where T: ExactSizeIterator<Item = U>, U: AsRef<str>, { fn from(iter: T) -> Self { if iter.len() == 0 { return Self { contents: None }; } let mut docs = String::new(); for doc in iter { let doc = doc.as_ref(); if let Some(doc) = doc.strip_prefix("//") { docs.push_str(doc.trim_start_matches('/').trim()); } else { assert!(doc.starts_with("/*")); assert!(doc.ends_with("*/")); for line in doc[2..doc.len() - 2].lines() { docs.push_str(line); docs.push('\n'); } } } Self { contents: Some(docs), } } } #[derive(Debug, Clone)] pub struct Resource { pub docs: Docs, pub name: String, pub foreign_module: Option<String>, } #[derive(Debug, Clone)] pub struct Global { pub docs: Docs, pub name: String, pub ty: Type, } #[derive(Debug, Clone)] pub struct Function { pub abi: Abi, pub is_async: bool, pub docs: Docs, pub name: String, pub kind: FunctionKind, pub params: Vec<(String, Type)>, pub results: Vec<(String, Type)>, } #[derive(Debug, Clone)] pub enum FunctionKind { Freestanding, Static { resource: ResourceId, name: String }, Method { resource: ResourceId, name: String }, } impl Function { pub fn item_name(&self) -> &str { match &self.kind { FunctionKind::Freestanding => &self.name, FunctionKind::Static { name, .. } => name, FunctionKind::Method { name, .. } => name, } } } impl Interface { pub fn parse(name: &str, input: &str) -> Result<Interface> { Interface::parse_with(name, input, |name| { bail!("cannot load interface `{}`", name) }) } pub fn parse_file(path: impl AsRef<Path>) -> Result<Interface> { let path = path.as_ref(); let parent = path.parent().unwrap(); let contents = std::fs::read_to_string(&path) .with_context(|| format!("failed to read interface `{}`", path.display()))?; Interface::parse_with(path, &contents, |name| load_fs(parent, name)) } pub fn parse_with( path: impl AsRef<Path>, contents: &str, mut load: impl FnMut(&str) -> Result<(PathBuf, String)>, ) -> Result<Interface> { Interface::_parse_with( path.as_ref(), contents, &mut load, &mut HashSet::new(), &mut HashMap::new(), ) } fn _parse_with( path: &Path, contents: &str, load: &mut dyn FnMut(&str) -> Result<(PathBuf, String)>, visiting: &mut HashSet<PathBuf>, map: &mut HashMap<String, Interface>, ) -> Result<Interface> { let ast = match Ast::parse(contents) { Ok(ast) => ast, Err(mut e) => { let file = path.display().to_string(); rewrite_error(&mut e, &file, contents); return Err(e); } }; if !visiting.insert(path.to_path_buf()) { bail!("file `{}` recursively imports itself", path.display()) } for item in ast.items.iter() { let u = match item { Item::Use(u) => u, _ => continue, }; if map.contains_key(&*u.from[0].name) { continue; } let (path, contents) = load(&u.from[0].name) ?; let instance = Self::_parse_with(&path, &contents, load, visiting, map)?; map.insert(u.from[0].name.to_string(), instance); } visiting.remove(path); let name = path.file_stem().unwrap().to_str().unwrap(); match ast.resolve(name, map) { Ok(i) => Ok(i), Err(mut e) => { let file = path.display().to_string(); rewrite_error(&mut e, &file, contents); Err(e) } } } pub fn topological_types(&self) -> Vec<TypeId> { let mut ret = Vec::new(); let mut visited = HashSet::new(); for (id, _) in self.types.iter() { self.topo_visit(id, &mut ret, &mut visited); } ret } fn topo_visit(&self, id: TypeId, list: &mut Vec<TypeId>, visited: &mut HashSet<TypeId>) { if !visited.insert(id) { return; } match &self.types[id].kind { TypeDefKind::Type(t) | TypeDefKind::List(t) | TypeDefKind::PushBuffer(t) | TypeDefKind::PullBuffer(t) | TypeDefKind::Pointer(t) | TypeDefKind::ConstPointer(t) => self.topo_visit_ty(t, list, visited), TypeDefKind::Record(r) => { for f in r.fields.iter() { self.topo_visit_ty(&f.ty, list, visited); } } TypeDefKind::Variant(v) => { for v in v.cases.iter() { if let Some(ty) = &v.ty { self.topo_visit_ty(ty, list, visited); } } } } list.push(id); } fn topo_visit_ty(&self, ty: &Type, list: &mut Vec<TypeId>, visited: &mut HashSet<TypeId>) { if let Type::Id(id) = ty { self.topo_visit(*id, list, visited); } } pub fn all_bits_valid(&self, ty: &Type) -> bool { match ty { Type::U8 | Type::S8 | Type::U16 | Type::S16 | Type::U32 | Type::S32 | Type::U64 | Type::S64 | Type::F32 | Type::F64 | Type::CChar | Type::Usize => true, Type::Char | Type::Handle(_) => false, Type::Id(id) => match &self.types[*id].kind { TypeDefKind::List(_) | TypeDefKind::Variant(_) | TypeDefKind::PushBuffer(_) | TypeDefKind::PullBuffer(_) => false, TypeDefKind::Type(t) => self.all_bits_valid(t), TypeDefKind::Record(r) => r.fields.iter().all(|f| self.all_bits_valid(&f.ty)), TypeDefKind::Pointer(_) | TypeDefKind::ConstPointer(_) => true, }, } } pub fn has_preview1_pointer(&self, ty: &Type) -> bool { match ty { Type::Id(id) => match &self.types[*id].kind { TypeDefKind::List(t) | TypeDefKind::PushBuffer(t) | TypeDefKind::PullBuffer(t) => { self.has_preview1_pointer(t) } TypeDefKind::Type(t) => self.has_preview1_pointer(t), TypeDefKind::Pointer(_) | TypeDefKind::ConstPointer(_) => true, TypeDefKind::Record(r) => r.fields.iter().any(|f| self.has_preview1_pointer(&f.ty)), TypeDefKind::Variant(v) => v.cases.iter().any(|c| match &c.ty { Some(ty) => self.has_preview1_pointer(ty), None => false, }), }, _ => false, } } } fn load_fs(root: &Path, name: &str) -> Result<(PathBuf, String)> { let path = root.join(name).with_extension("witx"); let contents = fs::read_to_string(&path).context(format!("failed to read `{}`", path.display()))?; Ok((path, contents)) }
use crate::{ abi::Abi, ast::interface::{Ast, Item}, rewrite_error, }; use anyhow::{bail, Context, Result}; use id_arena::{Arena, Id}; use std::collections::{HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; #[derive(Debug, Clone)] pub struct Interface { pub name: String, pub types: Arena<TypeDef>, pub type_lookup: HashMap<String, TypeId>, pub resources: Arena<Resource>, pub resource_lookup: HashMap<String, ResourceId>, pub interfaces: Arena<Interface>, pub interface_lookup: HashMap<String, InterfaceId>, pub functions: Vec<Function>, pub globals: Vec<Global>, } pub type TypeId = Id<TypeDef>; pub type ResourceId = Id<Resource>; pub type InterfaceId = Id<Interface>; #[derive(Debug, Clone)] pub struct TypeDef { pub docs: Docs, pub kind: TypeDefKind, pub name: Option<String>, pub foreign_module: Option<String>, } #[derive(Debug, Clone)] pub enum TypeDefKind { Record(Record), Variant(Variant), List(Type), Pointer(Type), ConstPointer(Type), PushBuffer(Type), PullBuffer(Type), Type(Type), } #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum Type { U8, U16, U32, U64, S8, S16, S32, S64, F32, F64, Char, CChar, Usize, Handle(ResourceId), Id(TypeId), } #[derive(PartialEq, Debug, Copy, Clone)] pub enum Int { U8, U16, U32, U64, } #[derive(Debug, Clone)] pub struct Record { pub fields: Vec<Field>, pub kind: RecordKind, } #[derive(Copy, Clone, Debug)] pub enum RecordKind { Other, Flags(Option<Int>), Tuple, } #[derive(Debug, Clone)] pub struct Field { pub docs: Docs, pub name: String, pub ty: Type, } impl Record { pub fn is_tuple(&self) -> bool { matches!(self.kind, RecordKind::Tuple) } pub fn is_flags(&self) -> bool { matches!(self.kind, RecordKind::Flags(_)) } pub fn num_i32s(&self) -> usize { (self.fields.len() + 31) / 32 } } impl RecordKind { pub fn infer(types: &Arena<TypeDef>, fields: &[Field]) -> RecordKind { if fields.is_empty() { return RecordKind::Other; } if fields.iter().all(|t| is_bool(&t.ty, types)) { return RecordKind::Flags(None); } if fields .iter() .enumerate() .all(|(i, m)| m.name.as_str().parse().ok() == Some(i)) { return RecordKind::Tuple; } return RecordKind::Other; fn is_bool(t: &Type, types: &Arena<TypeDef>) -> bool { match t { Type::Id(v) => match &types[*v].kind { TypeDefKind::Variant(v) => v.is_bool(), TypeDefKind::Type(t) => is_bool(t, types), _ => false, }, _ => false, } } } } #[derive(Debug, Clone)] pub struct Variant { pub cases: Vec<Case>, pub tag: Int, } #[derive(Debug, Clone)] pub struct Case { pub docs: Docs, pub name: String, pub ty: Option<Type>, } impl Variant { pub fn infer_tag(cases: usize) -> Int { match cases { n if n <= u8::max_value() as usize => Int::U8, n if n <= u16::max_value() as usize => Int::U16, n if n <= u32::max_value() as usize => Int::U32, n if n <= u64::max_value() as usize => Int::U64, _ => panic!("too many cases to fit in a repr"), } } pub fn is_bool(&self) -> bool { self.cases.len() == 2 && self.cases[0].name == "false" && self.cases[1].name == "true" && self.cases[0].ty.is_none() && self.cases[1].ty.is_none() } pub fn is_enum(&self) -> bool { self.cases.iter().all(|c| c.ty.is_none()) } pub fn as_option(&self) -> Option<&Type> { if self.cases.len() != 2 { return None; } if self.cases[0].name != "none" || self.cases[0].ty.is_some() { return None; } if self.cases[1].name != "some" { return None; } self.cases[1].ty.as_ref() } pub fn as_expected(&self) -> Option<(Option<&Type>, Option<&Type>)> { if self.cases.len() != 2 { return None; } if self.cases[0].name != "ok" { return None; } if self.cases[1].name != "err" { return None; } Some((self.cases[0].ty.as_ref(), self.cases[1].ty.as_ref())) } } #[derive(Clone, Default, Debug)] pub struct Docs { pub contents: Option<String>, } impl<'a, T, U> From<T> for Docs where T: ExactSizeIterator<Item = U>, U: AsRef<str>, { fn from(iter: T) -> Self { if iter.len() == 0 { return Self { contents: None }; } let mut docs = String::new(); for doc in iter { let doc = doc.as_ref(); if let Some(doc) = doc.strip_prefix("//") { docs.push_str(doc.trim_start_matches('/').trim()); } else { assert!(doc.starts_with("/*")); assert!(doc.ends_with("*/")); for line in doc[2..doc.len() - 2].lines() { docs.push_str(line); docs.push('\n'); } } } Self { contents: Some(docs), } } } #[derive(Debug, Clone)] pub struct Resource { pub docs: Docs, pub name: String, pub foreign_module: Option<String>, } #[derive(Debug, Clone)] pub struct Global { pub docs: Docs, pub name: String, pub ty: Type, } #[derive(Debug, Clone)] pub struct Function { pub abi: Abi, pub is_async: bool, pub docs: Docs, pub name: String, pub kind: FunctionKind, pub params: Vec<(String, Type)>, pub results: Vec<(String, Type)>, } #[derive(Debug, Clone)] pub enum FunctionKind { Freestanding, Static { resource: ResourceId, name: String }, Method { resource: ResourceId, name: String }, } impl Function { pub fn item_name(&self) -> &str { match &self.kind { FunctionKind::Freestanding => &self.name, FunctionKind::Static { name, .. } => name, FunctionKind::Method { name, .. } => name, } } } impl Interface { pub fn parse(name: &str, input: &str) -> Result<Interface> { Interface::parse_with(name, input, |name| { bail!("cannot load interface `{}`", name) }) } pub fn parse_file(path: impl AsRef<Path>) -> Result<Interface> {
pub fn parse_with( path: impl AsRef<Path>, contents: &str, mut load: impl FnMut(&str) -> Result<(PathBuf, String)>, ) -> Result<Interface> { Interface::_parse_with( path.as_ref(), contents, &mut load, &mut HashSet::new(), &mut HashMap::new(), ) } fn _parse_with( path: &Path, contents: &str, load: &mut dyn FnMut(&str) -> Result<(PathBuf, String)>, visiting: &mut HashSet<PathBuf>, map: &mut HashMap<String, Interface>, ) -> Result<Interface> { let ast = match Ast::parse(contents) { Ok(ast) => ast, Err(mut e) => { let file = path.display().to_string(); rewrite_error(&mut e, &file, contents); return Err(e); } }; if !visiting.insert(path.to_path_buf()) { bail!("file `{}` recursively imports itself", path.display()) } for item in ast.items.iter() { let u = match item { Item::Use(u) => u, _ => continue, }; if map.contains_key(&*u.from[0].name) { continue; } let (path, contents) = load(&u.from[0].name) ?; let instance = Self::_parse_with(&path, &contents, load, visiting, map)?; map.insert(u.from[0].name.to_string(), instance); } visiting.remove(path); let name = path.file_stem().unwrap().to_str().unwrap(); match ast.resolve(name, map) { Ok(i) => Ok(i), Err(mut e) => { let file = path.display().to_string(); rewrite_error(&mut e, &file, contents); Err(e) } } } pub fn topological_types(&self) -> Vec<TypeId> { let mut ret = Vec::new(); let mut visited = HashSet::new(); for (id, _) in self.types.iter() { self.topo_visit(id, &mut ret, &mut visited); } ret } fn topo_visit(&self, id: TypeId, list: &mut Vec<TypeId>, visited: &mut HashSet<TypeId>) { if !visited.insert(id) { return; } match &self.types[id].kind { TypeDefKind::Type(t) | TypeDefKind::List(t) | TypeDefKind::PushBuffer(t) | TypeDefKind::PullBuffer(t) | TypeDefKind::Pointer(t) | TypeDefKind::ConstPointer(t) => self.topo_visit_ty(t, list, visited), TypeDefKind::Record(r) => { for f in r.fields.iter() { self.topo_visit_ty(&f.ty, list, visited); } } TypeDefKind::Variant(v) => { for v in v.cases.iter() { if let Some(ty) = &v.ty { self.topo_visit_ty(ty, list, visited); } } } } list.push(id); } fn topo_visit_ty(&self, ty: &Type, list: &mut Vec<TypeId>, visited: &mut HashSet<TypeId>) { if let Type::Id(id) = ty { self.topo_visit(*id, list, visited); } } pub fn all_bits_valid(&self, ty: &Type) -> bool { match ty { Type::U8 | Type::S8 | Type::U16 | Type::S16 | Type::U32 | Type::S32 | Type::U64 | Type::S64 | Type::F32 | Type::F64 | Type::CChar | Type::Usize => true, Type::Char | Type::Handle(_) => false, Type::Id(id) => match &self.types[*id].kind { TypeDefKind::List(_) | TypeDefKind::Variant(_) | TypeDefKind::PushBuffer(_) | TypeDefKind::PullBuffer(_) => false, TypeDefKind::Type(t) => self.all_bits_valid(t), TypeDefKind::Record(r) => r.fields.iter().all(|f| self.all_bits_valid(&f.ty)), TypeDefKind::Pointer(_) | TypeDefKind::ConstPointer(_) => true, }, } } pub fn has_preview1_pointer(&self, ty: &Type) -> bool { match ty { Type::Id(id) => match &self.types[*id].kind { TypeDefKind::List(t) | TypeDefKind::PushBuffer(t) | TypeDefKind::PullBuffer(t) => { self.has_preview1_pointer(t) } TypeDefKind::Type(t) => self.has_preview1_pointer(t), TypeDefKind::Pointer(_) | TypeDefKind::ConstPointer(_) => true, TypeDefKind::Record(r) => r.fields.iter().any(|f| self.has_preview1_pointer(&f.ty)), TypeDefKind::Variant(v) => v.cases.iter().any(|c| match &c.ty { Some(ty) => self.has_preview1_pointer(ty), None => false, }), }, _ => false, } } } fn load_fs(root: &Path, name: &str) -> Result<(PathBuf, String)> { let path = root.join(name).with_extension("witx"); let contents = fs::read_to_string(&path).context(format!("failed to read `{}`", path.display()))?; Ok((path, contents)) }
let path = path.as_ref(); let parent = path.parent().unwrap(); let contents = std::fs::read_to_string(&path) .with_context(|| format!("failed to read interface `{}`", path.display()))?; Interface::parse_with(path, &contents, |name| load_fs(parent, name)) }
function_block-function_prefix_line
[ { "content": "pub fn case_name(id: &str) -> String {\n\n if id.chars().next().unwrap().is_alphabetic() {\n\n id.to_camel_case()\n\n } else {\n\n format!(\"V{}\", id)\n\n }\n\n}\n\n\n", "file_path": "crates/gen-rust/src/lib.rs", "rank": 0, "score": 443626.0483821046 }, { ...
Rust
kernel/src/drivers/keyboard/codes.rs
andrewimm/imm-dos-nx
2716a4954eae779cdf0596e061d16484d06c3563
#[derive(Copy, Clone)] #[repr(u8)] pub enum KeyCode { None = 0x00, Delete = 0x07, Backspace = 0x08, Tab = 0x09, Enter = 0x0d, Caps = 0x10, Shift = 0x11, Control = 0x12, Menu = 0x13, Alt = 0x14, Escape = 0x1b, Space = 0x20, ArrowLeft = 0x21, ArrowUp = 0x22, ArrowRight = 0x23, ArrowDown = 0x24, Comma = 0x2c, Minus = 0x2d, Period = 0x2e, Slash = 0x2f, Num0 = 0x30, Num1 = 0x31, Num2 = 0x32, Num3 = 0x33, Num4 = 0x34, Num5 = 0x35, Num6 = 0x36, Num7 = 0x37, Num8 = 0x38, Num9 = 0x39, Semicolon = 0x3a, Quote = 0x3b, LessThan = 0x3c, Equals = 0x3d, GreaterThan = 0x3e, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4a, K = 0x4b, L = 0x4c, M = 0x4d, N = 0x4e, O = 0x4f, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5a, BracketLeft = 0x5b, Backslash = 0x5c, BracketRight = 0x5d, Backtick = 0x5f, } pub const US_LAYOUT: [(u8, u8); 0x60] = [ (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0x7f, 0x7f), (0x08, 0x08), (0x09, 0x09), (0, 0), (0, 0), (0, 0), (0x0a, 0x0a), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0x1b, 0x1b), (0, 0), (0, 0), (0, 0), (0, 0), (0x20, 0x20), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0x2c, 0x3c), (0x2d, 0x5f), (0x2e, 0x3e), (0x2f, 0x3f), (0x30, 0x29), (0x31, 0x21), (0x32, 0x40), (0x33, 0x23), (0x34, 0x24), (0x35, 0x25), (0x36, 0x5e), (0x37, 0x26), (0x38, 0x2a), (0x39, 0x28), (0x3b, 0x3a), (0x27, 0x22), (0, 0), (0x3d, 0x2b), (0, 0), (0, 0), (0, 0), (0x61, 0x41), (0x62, 0x42), (0x63, 0x43), (0x64, 0x44), (0x65, 0x45), (0x66, 0x46), (0x67, 0x47), (0x68, 0x48), (0x69, 0x49), (0x6a, 0x4a), (0x6b, 0x4b), (0x6c, 0x4c), (0x6d, 0x4d), (0x6e, 0x4e), (0x6f, 0x4f), (0x70, 0x50), (0x71, 0x51), (0x72, 0x52), (0x73, 0x53), (0x74, 0x54), (0x75, 0x55), (0x76, 0x56), (0x77, 0x57), (0x78, 0x58), (0x79, 0x59), (0x7a, 0x5a), (0x5b, 0x7b), (0x5c, 0x7c), (0x5d, 0x7d), (0, 0), (0x60, 0x7e), ]; pub const SCANCODES_TO_KEYCODES: [KeyCode; 60] = [ KeyCode::None, KeyCode::Escape, KeyCode::Num1, KeyCode::Num2, KeyCode::Num3, KeyCode::Num4, KeyCode::Num5, KeyCode::Num6, KeyCode::Num7, KeyCode::Num8, KeyCode::Num9, KeyCode::Num0, KeyCode::Minus, KeyCode::Equals, KeyCode::Backspace, KeyCode::Tab, KeyCode::Q, KeyCode::W, KeyCode::E, KeyCode::R, KeyCode::T, KeyCode::Y, KeyCode::U, KeyCode::I, KeyCode::O, KeyCode::P, KeyCode::BracketLeft, KeyCode::BracketRight, KeyCode::Enter, KeyCode::Control, KeyCode::A, KeyCode::S, KeyCode::D, KeyCode::F, KeyCode::G, KeyCode::H, KeyCode::J, KeyCode::K, KeyCode::L, KeyCode::Semicolon, KeyCode::Quote, KeyCode::Backtick, KeyCode::Shift, KeyCode::Backslash, KeyCode::Z, KeyCode::X, KeyCode::C, KeyCode::V, KeyCode::B, KeyCode::N, KeyCode::M, KeyCode::Comma, KeyCode::Period, KeyCode::Slash, KeyCode::Shift, KeyCode::None, KeyCode::Alt, KeyCode::Space, KeyCode::Caps, KeyCode::None, ]; pub fn get_keycode(scan_code: u8) -> KeyCode { if scan_code < 60 { SCANCODES_TO_KEYCODES[scan_code as usize] } else { KeyCode::None } } pub fn get_extended_keycode(scan_code: u8) -> KeyCode { match scan_code { 0x1c => KeyCode::Enter, 0x48 => KeyCode::ArrowUp, 0x4b => KeyCode::ArrowLeft, 0x4d => KeyCode::ArrowRight, 0x50 => KeyCode::ArrowDown, _ => KeyCode::None, } }
#[derive(Copy, Clone)] #[repr(u8)] pub enum KeyCode { None = 0x00, Delete = 0x07, Backspace = 0x08, Tab = 0x09, Enter = 0x0d, Caps = 0x10, Shift = 0x11, Control = 0x12, Menu = 0x13, Alt = 0x14, Escape = 0x1b, Space = 0x20, ArrowLeft = 0x21, ArrowUp = 0x22, ArrowRight = 0x23, ArrowDown = 0x24, Comma = 0x2c, Minus = 0x2d, Period = 0x2e, Slash = 0x2f, Num0 = 0x30, Num1 = 0x31, Num2 = 0x32, Num3 = 0x33, Num4 = 0x34, Num5 = 0x35, Num6 = 0x36, Num7 = 0x37, Num8 = 0x38, Num9 = 0x39, Semicolon = 0x3a, Quote = 0x3b, LessThan = 0x3c, Equals = 0x3d, GreaterThan = 0x3e, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4a, K = 0x4b, L = 0x4c, M = 0x4d, N = 0x4e, O = 0x4f, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5a, BracketLeft = 0x5b, Backslash = 0x5c, BracketRight = 0x5d, Backtick = 0x5f, } pub const US_LAYOUT: [(u8, u8); 0x60] = [ (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0x7f, 0x7f), (0x08, 0x08), (0x09, 0x09), (0, 0), (0, 0), (0, 0), (0x0a, 0x0a), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0x1b, 0x1b), (0, 0), (0, 0), (0, 0), (0, 0), (0x20, 0x20), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0x2c, 0x3c), (0x2d, 0x5f), (0x2e, 0x3e), (0x2f, 0x3f), (0x30, 0x29), (0x31, 0x21), (0x32, 0x40), (0x33, 0x23), (0x34, 0x24), (0x35, 0x25), (0x36, 0x5e), (0x37, 0x26), (0x38, 0x2a), (0x39, 0x28), (0x3b, 0x3a), (0x27, 0x22), (0, 0), (0x3d, 0x2b), (0, 0), (0, 0), (0, 0), (0x61, 0x41), (0x62, 0x42), (0x63, 0x43), (0x64, 0x44), (0x65, 0x45), (0x66, 0x46), (0x67, 0x47), (0x68, 0x48), (0x69, 0x49), (0x6a, 0x4a), (0x6b, 0x4b), (0x6c, 0x4c), (0x6d, 0x4d), (0x6e, 0x4e), (0x6f, 0x4f), (0x70, 0x50), (0x71, 0x51), (0x72, 0x52), (0x73, 0x53), (0x74, 0x54), (0x75, 0x55), (0x76, 0x56), (0x77, 0x57), (0x78, 0x58), (0x79, 0x59), (0x7a, 0x5a), (0x5b, 0x7b), (0x5c, 0x7c), (0x5d, 0x7d), (0, 0), (0x60, 0x7e), ];
eyCode::Enter, 0x48 => KeyCode::ArrowUp, 0x4b => KeyCode::ArrowLeft, 0x4d => KeyCode::ArrowRight, 0x50 => KeyCode::ArrowDown, _ => KeyCode::None, } }
pub const SCANCODES_TO_KEYCODES: [KeyCode; 60] = [ KeyCode::None, KeyCode::Escape, KeyCode::Num1, KeyCode::Num2, KeyCode::Num3, KeyCode::Num4, KeyCode::Num5, KeyCode::Num6, KeyCode::Num7, KeyCode::Num8, KeyCode::Num9, KeyCode::Num0, KeyCode::Minus, KeyCode::Equals, KeyCode::Backspace, KeyCode::Tab, KeyCode::Q, KeyCode::W, KeyCode::E, KeyCode::R, KeyCode::T, KeyCode::Y, KeyCode::U, KeyCode::I, KeyCode::O, KeyCode::P, KeyCode::BracketLeft, KeyCode::BracketRight, KeyCode::Enter, KeyCode::Control, KeyCode::A, KeyCode::S, KeyCode::D, KeyCode::F, KeyCode::G, KeyCode::H, KeyCode::J, KeyCode::K, KeyCode::L, KeyCode::Semicolon, KeyCode::Quote, KeyCode::Backtick, KeyCode::Shift, KeyCode::Backslash, KeyCode::Z, KeyCode::X, KeyCode::C, KeyCode::V, KeyCode::B, KeyCode::N, KeyCode::M, KeyCode::Comma, KeyCode::Period, KeyCode::Slash, KeyCode::Shift, KeyCode::None, KeyCode::Alt, KeyCode::Space, KeyCode::Caps, KeyCode::None, ]; pub fn get_keycode(scan_code: u8) -> KeyCode { if scan_code < 60 { SCANCODES_TO_KEYCODES[scan_code as usize] } else { KeyCode::None } } pub fn get_extended_keycode(scan_code: u8) -> KeyCode { match scan_code { 0x1c => K
random
[]
Rust
futures-util/src/compat/compat03as01.rs
EkardNT/futures-rs
90c83b8faca107e6c4db63d10b0d4f2ea36d6628
use futures_01::{ task as task01, Async as Async01, Future as Future01, Poll as Poll01, Stream as Stream01, }; #[cfg(feature = "sink")] use futures_01::{ AsyncSink as AsyncSink01, Sink as Sink01, StartSend as StartSend01, }; use futures_core::{ task::{RawWaker, RawWakerVTable}, TryFuture as TryFuture03, TryStream as TryStream03, }; #[cfg(feature = "sink")] use futures_sink::Sink as Sink03; use crate::task::{ self as task03, ArcWake as ArcWake03, WakerRef, }; #[cfg(feature = "sink")] use std::marker::PhantomData; use std::{ mem, pin::Pin, sync::Arc, task::Context, }; #[derive(Debug, Clone, Copy)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Compat<T> { pub(crate) inner: T, } #[cfg(feature = "sink")] #[derive(Debug)] #[must_use = "sinks do nothing unless polled"] pub struct CompatSink<T, Item> { inner: T, _phantom: PhantomData<fn(Item)>, } impl<T> Compat<T> { pub fn new(inner: T) -> Compat<T> { Compat { inner } } pub fn get_ref(&self) -> &T { &self.inner } pub fn get_mut(&mut self) -> &mut T { &mut self.inner } pub fn into_inner(self) -> T { self.inner } } #[cfg(feature = "sink")] impl<T, Item> CompatSink<T, Item> { pub fn new(inner: T) -> Self { CompatSink { inner, _phantom: PhantomData, } } pub fn get_ref(&self) -> &T { &self.inner } pub fn get_mut(&mut self) -> &mut T { &mut self.inner } pub fn into_inner(self) -> T { self.inner } } fn poll_03_to_01<T, E>(x: task03::Poll<Result<T, E>>) -> Result<Async01<T>, E> { match x? { task03::Poll::Ready(t) => Ok(Async01::Ready(t)), task03::Poll::Pending => Ok(Async01::NotReady), } } impl<Fut> Future01 for Compat<Fut> where Fut: TryFuture03 + Unpin, { type Item = Fut::Ok; type Error = Fut::Error; fn poll(&mut self) -> Poll01<Self::Item, Self::Error> { with_context(self, |inner, cx| poll_03_to_01(inner.try_poll(cx))) } } impl<St> Stream01 for Compat<St> where St: TryStream03 + Unpin, { type Item = St::Ok; type Error = St::Error; fn poll(&mut self) -> Poll01<Option<Self::Item>, Self::Error> { with_context(self, |inner, cx| match inner.try_poll_next(cx)? { task03::Poll::Ready(None) => Ok(Async01::Ready(None)), task03::Poll::Ready(Some(t)) => Ok(Async01::Ready(Some(t))), task03::Poll::Pending => Ok(Async01::NotReady), }) } } #[cfg(feature = "sink")] impl<T, Item> Sink01 for CompatSink<T, Item> where T: Sink03<Item> + Unpin, { type SinkItem = Item; type SinkError = T::Error; fn start_send( &mut self, item: Self::SinkItem, ) -> StartSend01<Self::SinkItem, Self::SinkError> { with_sink_context(self, |mut inner, cx| { match inner.as_mut().poll_ready(cx)? { task03::Poll::Ready(()) => { inner.start_send(item).map(|()| AsyncSink01::Ready) } task03::Poll::Pending => Ok(AsyncSink01::NotReady(item)), } }) } fn poll_complete(&mut self) -> Poll01<(), Self::SinkError> { with_sink_context(self, |inner, cx| poll_03_to_01(inner.poll_flush(cx))) } fn close(&mut self) -> Poll01<(), Self::SinkError> { with_sink_context(self, |inner, cx| poll_03_to_01(inner.poll_close(cx))) } } #[derive(Clone)] struct Current(task01::Task); impl Current { fn new() -> Current { Current(task01::current()) } fn as_waker(&self) -> WakerRef<'_> { unsafe fn ptr_to_current<'a>(ptr: *const ()) -> &'a Current { &*(ptr as *const Current) } fn current_to_ptr(current: &Current) -> *const () { current as *const Current as *const () } unsafe fn clone(ptr: *const ()) -> RawWaker { mem::transmute::<task03::Waker, RawWaker>( task03::waker(Arc::new(ptr_to_current(ptr).clone())) ) } unsafe fn drop(_: *const ()) {} unsafe fn wake(ptr: *const ()) { ptr_to_current(ptr).0.notify() } let ptr = current_to_ptr(self); let vtable = &RawWakerVTable::new(clone, wake, wake, drop); WakerRef::new_unowned(std::mem::ManuallyDrop::new(unsafe { task03::Waker::from_raw(RawWaker::new(ptr, vtable)) })) } } impl ArcWake03 for Current { fn wake_by_ref(arc_self: &Arc<Self>) { arc_self.0.notify(); } } fn with_context<T, R, F>(compat: &mut Compat<T>, f: F) -> R where T: Unpin, F: FnOnce(Pin<&mut T>, &mut Context<'_>) -> R, { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); f(Pin::new(&mut compat.inner), &mut cx) } #[cfg(feature = "sink")] fn with_sink_context<T, Item, R, F>(compat: &mut CompatSink<T, Item>, f: F) -> R where T: Unpin, F: FnOnce(Pin<&mut T>, &mut Context<'_>) -> R, { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); f(Pin::new(&mut compat.inner), &mut cx) } #[cfg(feature = "io-compat")] mod io { use super::*; use futures_io::{AsyncRead as AsyncRead03, AsyncWrite as AsyncWrite03}; use tokio_io::{AsyncRead as AsyncRead01, AsyncWrite as AsyncWrite01}; fn poll_03_to_io<T>(x: task03::Poll<Result<T, std::io::Error>>) -> Result<T, std::io::Error> { match x { task03::Poll::Ready(Ok(t)) => Ok(t), task03::Poll::Pending => Err(std::io::ErrorKind::WouldBlock.into()), task03::Poll::Ready(Err(e)) => Err(e), } } impl<R: AsyncRead03 + Unpin> std::io::Read for Compat<R> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); poll_03_to_io(Pin::new(&mut self.inner).poll_read(&mut cx, buf)) } } impl<R: AsyncRead03 + Unpin> AsyncRead01 for Compat<R> { unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { let initializer = self.inner.initializer(); let does_init = initializer.should_initialize(); if does_init { initializer.initialize(buf); } does_init } } impl<W: AsyncWrite03 + Unpin> std::io::Write for Compat<W> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); poll_03_to_io(Pin::new(&mut self.inner).poll_write(&mut cx, buf)) } fn flush(&mut self) -> std::io::Result<()> { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); poll_03_to_io(Pin::new(&mut self.inner).poll_flush(&mut cx)) } } impl<W: AsyncWrite03 + Unpin> AsyncWrite01 for Compat<W> { fn shutdown(&mut self) -> std::io::Result<Async01<()>> { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); poll_03_to_01(Pin::new(&mut self.inner).poll_close(&mut cx)) } } }
use futures_01::{ task as task01, Async as Async01, Future as Future01, Poll as Poll01, Stream as Stream01, }; #[cfg(feature = "sink")] use futures_01::{ AsyncSink as AsyncSink01, Sink as Sink01, StartSend as StartSend01, }; use futures_core::{ task::{RawWaker, RawWakerVTable}, TryFuture as TryFuture03, TryStream as TryStream03, }; #[cfg(feature = "sink")] use futures_sink::Sink as Sink03; use crate::task::{ self as task03, ArcWake as ArcWake03, WakerRef, }; #[cfg(feature = "sink")] use std::marker::PhantomData; use std::{ mem, pin::Pin, sync::Arc, task::Context, }; #[derive(Debug, Clone, Copy)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Compat<T> { pub(crate) inner: T, } #[cfg(feature = "sink")] #[derive(Debug)] #[must_use = "sinks do nothing unless polled"] pub struct CompatSink<T, Item> { inner: T, _phantom: PhantomData<fn(Item)>, } impl<T> Compat<T> { pub fn new(inner: T) -> Compat<T> { Compat { inner } } pub fn get_ref(&self) -> &T { &self.inner } pub fn get_mut(&mut self) -> &mut T { &mut self.inner } pub fn into_inner(self) -> T { self.inner } } #[cfg(feature = "sink")] impl<T, Item> CompatSink<T, Item> { pub fn new(inner: T) -> Self { CompatSink { inner, _phantom: PhantomData, } } pub fn get_ref(&self) -> &T { &self.inner } pub fn get_mut(&mut self) -> &mut T { &mut self.inner } pub fn into_inner(self) -> T { self.inner } } fn poll_03_to_01<T, E>(x: task03::Poll<Result<T, E>>) -> Result<Async01<T>, E> { match x? { task03::Poll::Ready(t) => Ok(Async01::Ready(t)), task03::Poll::Pending => Ok(Async01::NotReady), } } impl<Fut> Future01 for Compat<Fut> where Fut: TryFuture03 + Unpin, { type Item = Fut::Ok; type Error = Fut::Error; fn poll(&mut self) -> Poll01<Self::Item, Self::Error> { with_context(self, |inner, cx| poll_03_to_01(inner.try_poll(cx))) } } impl<St> Stream01 for Compat<St> where St: TryStream03 + Unpin, { type Item = St::Ok; type Error = St::Error; fn poll(&mut self) -> Poll01<Option<Self::Item>, Self::Error> { with_context(self, |inner, cx| match inner.try_poll_next(cx)? { task03::Poll::Ready(None) => Ok(Async01::Ready(None)), task03::Poll::Ready(Some(t)) => Ok(Async01::Ready(Some(t))), task03::Poll::Pending => Ok(Async01::NotReady), }) } } #[cfg(feature = "sink")] impl<T, Item> Sink01 for CompatSink<T, Item> where T: Sink03<Item> + Unpin, { type SinkItem = Item; type SinkError = T::Error; fn start_send( &mut self, item: Self::SinkItem, ) -> StartSend01<Self::SinkItem, Self::SinkError> { with_sink_context(self, |mut inner, cx| { match inner.as_mut().poll_ready(cx)? { task03::Poll::Ready(()) => { inner.start_send(item).map(|()| AsyncSink01::Ready) } task03::Poll::Pending => Ok(AsyncSink01::NotReady(item)), } }) } fn poll_complete(&mut self) -> Poll01<(), Self::SinkError> { with_sink_context(self, |inner, cx| poll_03_to_01(inner.poll_flush(cx))) } fn close(&mut self) -> Poll01<(), Self::SinkError> { with_sink_context(self, |inner, cx| poll_03_to_01(inner.poll_close(cx))) } } #[derive(Clone)] struct Current(task01::Task); impl Current { fn new() -> Current { Current(task01::current()) } fn as_waker(&self) -> WakerRef<'_> { unsafe fn ptr_to_current<'a>(ptr: *const ()) -> &'a Current { &*(ptr as *const Current) } fn current_to_ptr(current: &Current) -> *const () { current as *const Current as *const () } unsafe fn clone(ptr: *const ()) -> RawWaker { mem::transmute::<task03::Waker, RawWaker>( task03::waker(Arc::new(ptr_to_current(ptr).clone())) ) } unsafe fn drop(_: *const ()) {} unsafe fn wake(ptr: *const ()) { ptr_to_current(ptr).0.notify() } let ptr = current_to_ptr(self); let vtable = &RawWakerVTable::new(clone, wake, wake, drop); WakerRef::new_unowned(std::mem::ManuallyDrop::new(unsafe { task03::Waker::from_raw(RawWaker::new(ptr, vtable)) })) } } impl ArcWake03 for Current { fn wake_by_ref(arc_self: &Arc<Self>) { arc_self.0.notify(); } } fn with_context<T, R, F>(compat: &mut Compat<T>, f: F) -> R where T: Unpin, F: FnOnce(Pin<&mut T>, &mut Context<'_>) -> R, { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); f(Pin::new(&mut compat.inner), &mut cx) } #[cfg(feature = "sink")] fn with_sink_context<T, Item, R, F>(compat: &mut CompatSink<T, Item>, f: F) -> R where T: Unpin, F: FnOnce(Pin<&mut T>, &mut Context<'_>) -> R, { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); f(Pin::new(&mut compat.inner), &mut cx) } #[cfg(feature = "io-compat")] mod io { use super::*; use futures_io::{AsyncRead as AsyncRead03, AsyncWrite as AsyncWrite03}; use tokio_io::{AsyncRead as AsyncRead01, AsyncWrite as AsyncWrite01}; fn poll_03_to_io<T>(x: task03::Poll<Result<T, std::io::Error>>) -> Result<T, std::io::Error> { match x { task03::Poll::Ready(Ok(t)) => Ok(t), task03::Poll::Pending => Err(std::io::ErrorKind::WouldBlock.into()), task03::Poll::Ready(Err(e)) => Err(e), } } impl<R: AsyncRead03 + Unpin> std::io::Read for Compat<R> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); poll_03_to_io(Pin::new(&mut self.inner).poll_read(&mut cx, buf)) } } impl<R: AsyncRead03 + Unpin> AsyncRead01 for Compat<R> { unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { let initializer = self.inner.initializer(); let does_init = initializer.should_initialize(); if does_init { initializer.initialize(buf); } does_init } } impl<W: AsyncWrite03 + Unpin> std::io::Write for Compat<W> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); poll_03_to_io(Pin::new(&mut self.inner).poll_write(&mut cx, buf)) } fn flush(&mut self) -> std::io::Result<()> { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); poll_03_to_io(Pin::new(&mut self.inner).poll_flush(&mut cx)) } } impl<W: AsyncWrite03 + Unpin> AsyncWrite01 for Compat<W> { fn shutdown(&mut
} }
self) -> std::io::Result<Async01<()>> { let current = Current::new(); let waker = current.as_waker(); let mut cx = Context::from_waker(&waker); poll_03_to_01(Pin::new(&mut self.inner).poll_close(&mut cx)) }
function_block-function_prefixed
[ { "content": "#[doc(hidden)]\n\npub fn poll<F: Future + Unpin>(future: F) -> PollOnce<F> {\n\n PollOnce { future }\n\n}\n\n\n\n#[allow(missing_debug_implementations)]\n\n#[doc(hidden)]\n\npub struct PollOnce<F: Future + Unpin> {\n\n future: F,\n\n}\n\n\n\nimpl<F: Future + Unpin> Future for PollOnce<F> {\n...
Rust
src/usbphy/pll_sic_tog.rs
thorhs/mk66f18
ea5a3c933656be9f2f548b28dee91d0bb7821923
#[doc = "Reader of register PLL_SIC_TOG"] pub type R = crate::R<u32, super::PLL_SIC_TOG>; #[doc = "Writer for register PLL_SIC_TOG"] pub type W = crate::W<u32, super::PLL_SIC_TOG>; #[doc = "Register PLL_SIC_TOG `reset()`'s with value 0x0001_2000"] impl crate::ResetValue for super::PLL_SIC_TOG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0001_2000 } } #[doc = "This field controls the USB PLL feedback loop divider\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PLL_DIV_SEL_A { #[doc = "0: PLL reference frequency = 24MHz"] _00, #[doc = "1: PLL reference frequency = 16MHz"] _01, } impl From<PLL_DIV_SEL_A> for u8 { #[inline(always)] fn from(variant: PLL_DIV_SEL_A) -> Self { match variant { PLL_DIV_SEL_A::_00 => 0, PLL_DIV_SEL_A::_01 => 1, } } } #[doc = "Reader of field `PLL_DIV_SEL`"] pub type PLL_DIV_SEL_R = crate::R<u8, PLL_DIV_SEL_A>; impl PLL_DIV_SEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, PLL_DIV_SEL_A> { use crate::Variant::*; match self.bits { 0 => Val(PLL_DIV_SEL_A::_00), 1 => Val(PLL_DIV_SEL_A::_01), i => Res(i), } } #[doc = "Checks if the value of the field is `_00`"] #[inline(always)] pub fn is_00(&self) -> bool { *self == PLL_DIV_SEL_A::_00 } #[doc = "Checks if the value of the field is `_01`"] #[inline(always)] pub fn is_01(&self) -> bool { *self == PLL_DIV_SEL_A::_01 } } #[doc = "Write proxy for field `PLL_DIV_SEL`"] pub struct PLL_DIV_SEL_W<'a> { w: &'a mut W, } impl<'a> PLL_DIV_SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL_DIV_SEL_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "PLL reference frequency = 24MHz"] #[inline(always)] pub fn _00(self) -> &'a mut W { self.variant(PLL_DIV_SEL_A::_00) } #[doc = "PLL reference frequency = 16MHz"] #[inline(always)] pub fn _01(self) -> &'a mut W { self.variant(PLL_DIV_SEL_A::_01) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03); self.w } } #[doc = "Reader of field `PLL_EN_USB_CLKS`"] pub type PLL_EN_USB_CLKS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_EN_USB_CLKS`"] pub struct PLL_EN_USB_CLKS_W<'a> { w: &'a mut W, } impl<'a> PLL_EN_USB_CLKS_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 `PLL_HOLD_RING_OFF`"] pub type PLL_HOLD_RING_OFF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_HOLD_RING_OFF`"] pub struct PLL_HOLD_RING_OFF_W<'a> { w: &'a mut W, } impl<'a> PLL_HOLD_RING_OFF_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 `PLL_POWER`"] pub type PLL_POWER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_POWER`"] pub struct PLL_POWER_W<'a> { w: &'a mut W, } impl<'a> PLL_POWER_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 `PLL_ENABLE`"] pub type PLL_ENABLE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_ENABLE`"] pub struct PLL_ENABLE_W<'a> { w: &'a mut W, } impl<'a> PLL_ENABLE_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 `PLL_BYPASS`"] pub type PLL_BYPASS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_BYPASS`"] pub struct PLL_BYPASS_W<'a> { w: &'a mut W, } impl<'a> PLL_BYPASS_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 = "USB PLL lock status indicator\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PLL_LOCK_A { #[doc = "0: PLL is not currently locked"] _0, #[doc = "1: PLL is currently locked"] _1, } impl From<PLL_LOCK_A> for bool { #[inline(always)] fn from(variant: PLL_LOCK_A) -> Self { match variant { PLL_LOCK_A::_0 => false, PLL_LOCK_A::_1 => true, } } } #[doc = "Reader of field `PLL_LOCK`"] pub type PLL_LOCK_R = crate::R<bool, PLL_LOCK_A>; impl PLL_LOCK_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PLL_LOCK_A { match self.bits { false => PLL_LOCK_A::_0, true => PLL_LOCK_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == PLL_LOCK_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == PLL_LOCK_A::_1 } } impl R { #[doc = "Bits 0:1 - This field controls the USB PLL feedback loop divider"] #[inline(always)] pub fn pll_div_sel(&self) -> PLL_DIV_SEL_R { PLL_DIV_SEL_R::new((self.bits & 0x03) as u8) } #[doc = "Bit 6 - Enable the USB clock output from the USB PHY PLL."] #[inline(always)] pub fn pll_en_usb_clks(&self) -> PLL_EN_USB_CLKS_R { PLL_EN_USB_CLKS_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 11 - Analog debug bit"] #[inline(always)] pub fn pll_hold_ring_off(&self) -> PLL_HOLD_RING_OFF_R { PLL_HOLD_RING_OFF_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - Power up the USB PLL."] #[inline(always)] pub fn pll_power(&self) -> PLL_POWER_R { PLL_POWER_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - Enable the clock output from the USB PLL."] #[inline(always)] pub fn pll_enable(&self) -> PLL_ENABLE_R { PLL_ENABLE_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 16 - Bypass the USB PLL."] #[inline(always)] pub fn pll_bypass(&self) -> PLL_BYPASS_R { PLL_BYPASS_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 31 - USB PLL lock status indicator"] #[inline(always)] pub fn pll_lock(&self) -> PLL_LOCK_R { PLL_LOCK_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:1 - This field controls the USB PLL feedback loop divider"] #[inline(always)] pub fn pll_div_sel(&mut self) -> PLL_DIV_SEL_W { PLL_DIV_SEL_W { w: self } } #[doc = "Bit 6 - Enable the USB clock output from the USB PHY PLL."] #[inline(always)] pub fn pll_en_usb_clks(&mut self) -> PLL_EN_USB_CLKS_W { PLL_EN_USB_CLKS_W { w: self } } #[doc = "Bit 11 - Analog debug bit"] #[inline(always)] pub fn pll_hold_ring_off(&mut self) -> PLL_HOLD_RING_OFF_W { PLL_HOLD_RING_OFF_W { w: self } } #[doc = "Bit 12 - Power up the USB PLL."] #[inline(always)] pub fn pll_power(&mut self) -> PLL_POWER_W { PLL_POWER_W { w: self } } #[doc = "Bit 13 - Enable the clock output from the USB PLL."] #[inline(always)] pub fn pll_enable(&mut self) -> PLL_ENABLE_W { PLL_ENABLE_W { w: self } } #[doc = "Bit 16 - Bypass the USB PLL."] #[inline(always)] pub fn pll_bypass(&mut self) -> PLL_BYPASS_W { PLL_BYPASS_W { w: self } } }
#[doc = "Reader of register PLL_SIC_TOG"] pub type R = crate::R<u32, super::PLL_SIC_TOG>; #[doc = "Writer for register PLL_SIC_TOG"] pub type W = crate::W<u32, super::PLL_SIC_TOG>; #[doc = "Register PLL_SIC_TOG `reset()`'s with value 0x0001_2000"] impl crate::ResetValue for super::PLL_SIC_TOG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0001_2000 } } #[doc = "This field controls the USB PLL feedback loop divider\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PLL_DIV_SEL_A { #[doc = "0: PLL reference frequency = 24MHz"] _00, #[doc = "1: PLL reference frequency = 16MHz"] _01, } impl From<PLL_DIV_SEL_A> for u8 { #[inline(always)] fn from(variant: PLL_DIV_SEL_A) -> Self { match variant { PLL_DIV_SEL_A::_00 => 0, PLL_DIV_SEL_A::_01 => 1, } } } #[doc = "Reader of field `PLL_DIV_SEL`"] pub type PLL_DIV_SEL_R = crate::R<u8, PLL_DIV_SEL_A>; impl PLL_DIV_SEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)]
#[doc = "Checks if the value of the field is `_00`"] #[inline(always)] pub fn is_00(&self) -> bool { *self == PLL_DIV_SEL_A::_00 } #[doc = "Checks if the value of the field is `_01`"] #[inline(always)] pub fn is_01(&self) -> bool { *self == PLL_DIV_SEL_A::_01 } } #[doc = "Write proxy for field `PLL_DIV_SEL`"] pub struct PLL_DIV_SEL_W<'a> { w: &'a mut W, } impl<'a> PLL_DIV_SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL_DIV_SEL_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "PLL reference frequency = 24MHz"] #[inline(always)] pub fn _00(self) -> &'a mut W { self.variant(PLL_DIV_SEL_A::_00) } #[doc = "PLL reference frequency = 16MHz"] #[inline(always)] pub fn _01(self) -> &'a mut W { self.variant(PLL_DIV_SEL_A::_01) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03); self.w } } #[doc = "Reader of field `PLL_EN_USB_CLKS`"] pub type PLL_EN_USB_CLKS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_EN_USB_CLKS`"] pub struct PLL_EN_USB_CLKS_W<'a> { w: &'a mut W, } impl<'a> PLL_EN_USB_CLKS_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 `PLL_HOLD_RING_OFF`"] pub type PLL_HOLD_RING_OFF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_HOLD_RING_OFF`"] pub struct PLL_HOLD_RING_OFF_W<'a> { w: &'a mut W, } impl<'a> PLL_HOLD_RING_OFF_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 `PLL_POWER`"] pub type PLL_POWER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_POWER`"] pub struct PLL_POWER_W<'a> { w: &'a mut W, } impl<'a> PLL_POWER_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 `PLL_ENABLE`"] pub type PLL_ENABLE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_ENABLE`"] pub struct PLL_ENABLE_W<'a> { w: &'a mut W, } impl<'a> PLL_ENABLE_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 `PLL_BYPASS`"] pub type PLL_BYPASS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLL_BYPASS`"] pub struct PLL_BYPASS_W<'a> { w: &'a mut W, } impl<'a> PLL_BYPASS_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 = "USB PLL lock status indicator\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PLL_LOCK_A { #[doc = "0: PLL is not currently locked"] _0, #[doc = "1: PLL is currently locked"] _1, } impl From<PLL_LOCK_A> for bool { #[inline(always)] fn from(variant: PLL_LOCK_A) -> Self { match variant { PLL_LOCK_A::_0 => false, PLL_LOCK_A::_1 => true, } } } #[doc = "Reader of field `PLL_LOCK`"] pub type PLL_LOCK_R = crate::R<bool, PLL_LOCK_A>; impl PLL_LOCK_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PLL_LOCK_A { match self.bits { false => PLL_LOCK_A::_0, true => PLL_LOCK_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == PLL_LOCK_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == PLL_LOCK_A::_1 } } impl R { #[doc = "Bits 0:1 - This field controls the USB PLL feedback loop divider"] #[inline(always)] pub fn pll_div_sel(&self) -> PLL_DIV_SEL_R { PLL_DIV_SEL_R::new((self.bits & 0x03) as u8) } #[doc = "Bit 6 - Enable the USB clock output from the USB PHY PLL."] #[inline(always)] pub fn pll_en_usb_clks(&self) -> PLL_EN_USB_CLKS_R { PLL_EN_USB_CLKS_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 11 - Analog debug bit"] #[inline(always)] pub fn pll_hold_ring_off(&self) -> PLL_HOLD_RING_OFF_R { PLL_HOLD_RING_OFF_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - Power up the USB PLL."] #[inline(always)] pub fn pll_power(&self) -> PLL_POWER_R { PLL_POWER_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - Enable the clock output from the USB PLL."] #[inline(always)] pub fn pll_enable(&self) -> PLL_ENABLE_R { PLL_ENABLE_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 16 - Bypass the USB PLL."] #[inline(always)] pub fn pll_bypass(&self) -> PLL_BYPASS_R { PLL_BYPASS_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 31 - USB PLL lock status indicator"] #[inline(always)] pub fn pll_lock(&self) -> PLL_LOCK_R { PLL_LOCK_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:1 - This field controls the USB PLL feedback loop divider"] #[inline(always)] pub fn pll_div_sel(&mut self) -> PLL_DIV_SEL_W { PLL_DIV_SEL_W { w: self } } #[doc = "Bit 6 - Enable the USB clock output from the USB PHY PLL."] #[inline(always)] pub fn pll_en_usb_clks(&mut self) -> PLL_EN_USB_CLKS_W { PLL_EN_USB_CLKS_W { w: self } } #[doc = "Bit 11 - Analog debug bit"] #[inline(always)] pub fn pll_hold_ring_off(&mut self) -> PLL_HOLD_RING_OFF_W { PLL_HOLD_RING_OFF_W { w: self } } #[doc = "Bit 12 - Power up the USB PLL."] #[inline(always)] pub fn pll_power(&mut self) -> PLL_POWER_W { PLL_POWER_W { w: self } } #[doc = "Bit 13 - Enable the clock output from the USB PLL."] #[inline(always)] pub fn pll_enable(&mut self) -> PLL_ENABLE_W { PLL_ENABLE_W { w: self } } #[doc = "Bit 16 - Bypass the USB PLL."] #[inline(always)] pub fn pll_bypass(&mut self) -> PLL_BYPASS_W { PLL_BYPASS_W { w: self } } }
pub fn variant(&self) -> crate::Variant<u8, PLL_DIV_SEL_A> { use crate::Variant::*; match self.bits { 0 => Val(PLL_DIV_SEL_A::_00), 1 => Val(PLL_DIV_SEL_A::_01), i => Res(i), } }
function_block-full_function
[ { "content": " ///\n\n ///Registers marked with `Readable` can be also `modify`'ed\n\n pub trait Writable { } ///Reset value of the register\n", "file_path": "lib.rs", "rank": 0, "score": 220323.13240861555 }, { "content": " ///\n\n ///This value is initial value for `write` method.\n\n ///I...
Rust
termwiz/src/hyperlink.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
use anyhow::{anyhow, ensure, Error}; use regex::{Captures, Regex}; use serde::{self, Deserialize, Deserializer, Serialize}; use std::collections::HashMap; use std::fmt::{Display, Error as FmtError, Formatter}; use std::ops::Range; use std::sync::Arc; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Hyperlink { params: HashMap<String, String>, uri: String, implicit: bool, } impl Hyperlink { pub fn uri(&self) -> &str { &self.uri } pub fn params(&self) -> &HashMap<String, String> { &self.params } pub fn new<S: Into<String>>(uri: S) -> Self { Self { uri: uri.into(), params: HashMap::new(), implicit: false, } } #[inline] pub fn is_implicit(&self) -> bool { self.implicit } pub fn new_implicit<S: Into<String>>(uri: S) -> Self { Self { uri: uri.into(), params: HashMap::new(), implicit: true, } } pub fn new_with_id<S: Into<String>, S2: Into<String>>(uri: S, id: S2) -> Self { let mut params = HashMap::new(); params.insert("id".into(), id.into()); Self { uri: uri.into(), params, implicit: false, } } pub fn new_with_params<S: Into<String>>(uri: S, params: HashMap<String, String>) -> Self { Self { uri: uri.into(), params, implicit: false, } } pub fn parse(osc: &[&[u8]]) -> Result<Option<Hyperlink>, Error> { ensure!(osc.len() == 3, "wrong param count"); if osc[1].is_empty() && osc[2].is_empty() { Ok(None) } else { let param_str = String::from_utf8(osc[1].to_vec())?; let uri = String::from_utf8(osc[2].to_vec())?; let mut params = HashMap::new(); if !param_str.is_empty() { for pair in param_str.split(':') { let mut iter = pair.splitn(2, '='); let key = iter.next().ok_or_else(|| anyhow!("bad params"))?; let value = iter.next().ok_or_else(|| anyhow!("bad params"))?; params.insert(key.to_owned(), value.to_owned()); } } Ok(Some(Hyperlink::new_with_params(uri, params))) } } } impl Display for Hyperlink { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { write!(f, "8;")?; for (idx, (k, v)) in self.params.iter().enumerate() { if idx > 0 { write!(f, ":")?; } write!(f, "{}={}", k, v)?; } write!(f, ";{}", self.uri)?; Ok(()) } } #[derive(Debug, Clone, Deserialize)] pub struct Rule { #[serde(deserialize_with = "deserialize_regex")] regex: Regex, format: String, } fn deserialize_regex<'de, D>(deserializer: D) -> Result<Regex, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; Regex::new(&s).map_err(|e| serde::de::Error::custom(format!("{:?}", e))) } #[derive(Debug, PartialEq)] pub struct RuleMatch { pub range: Range<usize>, pub link: Arc<Hyperlink>, } struct Match<'t> { rule: &'t Rule, captures: Captures<'t>, } impl<'t> Match<'t> { fn len(&self) -> usize { let c0 = self.captures.get(0).unwrap(); c0.end() - c0.start() } fn range(&self) -> Range<usize> { let c0 = self.captures.get(0).unwrap(); c0.start()..c0.end() } fn expand(&self) -> String { let mut result = self.rule.format.clone(); for n in (0..self.captures.len()).rev() { let search = format!("${}", n); result = result.replace(&search, self.captures.get(n).unwrap().as_str()); } result } } impl Rule { pub fn new(regex: &str, format: &str) -> Result<Self, Error> { Ok(Self { regex: Regex::new(regex)?, format: format.to_owned(), }) } pub fn match_hyperlinks(line: &str, rules: &[Rule]) -> Vec<RuleMatch> { let mut matches = Vec::new(); for rule in rules.iter() { for captures in rule.regex.captures_iter(line) { matches.push(Match { rule, captures }); } } matches.sort_by(|a, b| b.len().cmp(&a.len())); matches .into_iter() .map(|m| { let url = m.expand(); let link = Arc::new(Hyperlink::new_implicit(url)); RuleMatch { link, range: m.range(), } }) .collect() } } #[cfg(test)] mod test { use super::*; #[test] fn parse_implicit() { let rules = vec![ Rule::new(r"\b\w+://(?:[\w.-]+)\.[a-z]{2,15}\S*\b", "$0").unwrap(), Rule::new(r"\b\w+@[\w-]+(\.[\w-]+)+\b", "mailto:$0").unwrap(), ]; assert_eq!( Rule::match_hyperlinks(" http://example.com", &rules), vec![RuleMatch { range: 2..20, link: Arc::new(Hyperlink::new_implicit("http://example.com")), }] ); assert_eq!( Rule::match_hyperlinks(" foo@example.com woot@example.com", &rules), vec![ RuleMatch { range: 18..34, link: Arc::new(Hyperlink::new_implicit("mailto:woot@example.com")), }, RuleMatch { range: 2..17, link: Arc::new(Hyperlink::new_implicit("mailto:foo@example.com")), }, ] ); } }
use anyhow::{anyhow, ensure, Error}; use regex::{Captures, Regex}; use serde::{self, Deserialize, Deserializer, Serialize}; use std::collections::HashMap; use std::fmt::{Display, Error as FmtError, Formatter}; use std::ops::Range; use std::sync::Arc; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Hyperlink { params: HashMap<String, String>, uri: String, implicit: bool, } impl Hyperlink { pub fn uri(&self) -> &str { &self.uri } pub fn params(&self) -> &HashMap<String, String> { &self.params } pub fn new<S: Into<String>>(uri: S) -> Self { Self { uri: uri.into(), params: HashMap::new(), implicit: false, } } #[inline] pub fn is_implicit(&self) -> bool { self.implicit } pub fn new_implicit<S: Into<String>>(uri: S) -> Self { Self { uri: uri.into(), params: HashMap::new(), implicit: true, } } pub fn new_with_id<S: Into<String>, S2: Into<String>>(uri: S, id: S2) -> Self { let mut params = HashMap::new(); params.insert("id".into(), id.into()); Self { uri: uri.into(), params, implicit: false, } } pub fn new_with_params<S: Into<String>>(uri: S, params: HashMap<String, String>) -> Self { Self { uri: uri.into(), params, implicit: false, } } pub fn parse(osc: &[&[u8]]) -> Result<Option<Hyperlink>, Error> { ensure!(osc.len() == 3, "wrong param count"); if osc[1].is_empty() && osc[2].is_empty() { Ok(None) } else { let param_str = String::from_utf8(osc[1].to_vec())?; let uri = String::from_utf8(osc[2].to_vec())?; let mut params = HashMap::new(); if !param_str.is_empty() { for pair in param_str.split(':') { let mut iter = pair.splitn(2, '='); let key = iter.next().ok_or_else(|| anyhow!("bad params"))?; let value = iter.next().ok_or_else(|| anyhow!("bad params"))?; params.insert(key.to_owned(), value.to_owned()); } } Ok(Some(Hyperlink::new_with_params(uri, params))) } } } impl Display for Hyperlink { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { write!(f, "8;")?; for (idx, (k, v)) in self.params.iter().enumerate() { if idx > 0 { write!(f, ":")?; } write!(f, "{}={}", k, v)?; } write!(f, ";{}", self.uri)?; Ok(()) } } #[derive(Debug, Clone, Deserialize)] pub struct Rule { #[serde(deserialize_with = "deserialize_regex")] regex: Regex, format: String, } fn deserialize_regex<'de, D>(deserializer: D) -> Result<Regex, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; Regex::new(&s).map_err(|e| serde::de::Error::custom(format!("{:?}", e))) } #[derive(Debug, PartialEq)] pub struct RuleMatch { pub range: Range<usize>, pub link: Arc<Hyperlink>, } struct Match<'t> { rule: &'t Rule, captures: Captures<'t>, } impl<'t> Match<'t> { fn len(&self) -> usize { let c0 = self.captures.get(0).unwrap(); c0.end() - c0.start() } fn range(&self) -> Range<usize> { let c0 = self.captures.get(0).unwrap(); c0.start()..c0.end() } fn expand(&self) -> String { let mut result = self.rule.format.clone(); for n in (0..self.captures.len()).rev() { let search = fo
} impl Rule { pub fn new(regex: &str, format: &str) -> Result<Self, Error> { Ok(Self { regex: Regex::new(regex)?, format: format.to_owned(), }) } pub fn match_hyperlinks(line: &str, rules: &[Rule]) -> Vec<RuleMatch> { let mut matches = Vec::new(); for rule in rules.iter() { for captures in rule.regex.captures_iter(line) { matches.push(Match { rule, captures }); } } matches.sort_by(|a, b| b.len().cmp(&a.len())); matches .into_iter() .map(|m| { let url = m.expand(); let link = Arc::new(Hyperlink::new_implicit(url)); RuleMatch { link, range: m.range(), } }) .collect() } } #[cfg(test)] mod test { use super::*; #[test] fn parse_implicit() { let rules = vec![ Rule::new(r"\b\w+://(?:[\w.-]+)\.[a-z]{2,15}\S*\b", "$0").unwrap(), Rule::new(r"\b\w+@[\w-]+(\.[\w-]+)+\b", "mailto:$0").unwrap(), ]; assert_eq!( Rule::match_hyperlinks(" http://example.com", &rules), vec![RuleMatch { range: 2..20, link: Arc::new(Hyperlink::new_implicit("http://example.com")), }] ); assert_eq!( Rule::match_hyperlinks(" foo@example.com woot@example.com", &rules), vec![ RuleMatch { range: 18..34, link: Arc::new(Hyperlink::new_implicit("mailto:woot@example.com")), }, RuleMatch { range: 2..17, link: Arc::new(Hyperlink::new_implicit("mailto:foo@example.com")), }, ] ); } }
rmat!("${}", n); result = result.replace(&search, self.captures.get(n).unwrap().as_str()); } result }
function_block-function_prefixed
[ { "content": "pub fn language_from_string(s: &str) -> Result<hb_language_t, Error> {\n\n unsafe {\n\n let lang = hb_language_from_string(s.as_ptr() as *const i8, s.len() as i32);\n\n ensure!(!lang.is_null(), \"failed to convert {} to language\");\n\n Ok(lang)\n\n }\n\n}\n\n\n", "f...
Rust
src/recovery/hystart.rs
ehaydenr/quiche
d0b40f791fd46f1ffdf0357f18e1ba5953723a59
use std::cmp; use std::time::Duration; use std::time::Instant; use crate::packet; use crate::recovery; const LOW_CWND: usize = 16; const MIN_RTT_THRESH: Duration = Duration::from_millis(4); const MAX_RTT_THRESH: Duration = Duration::from_millis(16); pub const LSS_DIVISOR: f64 = 0.25; pub const N_RTT_SAMPLE: usize = 8; #[derive(Default)] pub struct Hystart { enabled: bool, window_end: Option<u64>, last_round_min_rtt: Option<Duration>, current_round_min_rtt: Option<Duration>, rtt_sample_count: usize, lss_start_time: Option<Instant>, } impl std::fmt::Debug for Hystart { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "window_end={:?} ", self.window_end)?; write!(f, "last_round_min_rtt={:?} ", self.last_round_min_rtt)?; write!(f, "current_round_min_rtt={:?} ", self.current_round_min_rtt)?; write!(f, "rtt_sample_count={:?} ", self.rtt_sample_count)?; write!(f, "lss_start_time={:?} ", self.lss_start_time)?; Ok(()) } } impl Hystart { pub fn new(enabled: bool) -> Self { Self { enabled, ..Default::default() } } pub fn enabled(&self) -> bool { self.enabled } pub fn lss_start_time(&self) -> Option<Instant> { self.lss_start_time } pub fn in_lss(&self, epoch: packet::Epoch) -> bool { self.enabled && epoch == packet::EPOCH_APPLICATION && self.lss_start_time().is_some() } pub fn start_round(&mut self, pkt_num: u64) { if self.window_end.is_none() { *self = Hystart { enabled: self.enabled, window_end: Some(pkt_num), last_round_min_rtt: self.current_round_min_rtt, current_round_min_rtt: None, rtt_sample_count: 0, lss_start_time: None, }; } } pub fn try_enter_lss( &mut self, packet: &recovery::Acked, rtt: Duration, cwnd: usize, now: Instant, max_datagram_size: usize, ) -> bool { if self.lss_start_time().is_none() { if let Some(current_round_min_rtt) = self.current_round_min_rtt { self.current_round_min_rtt = Some(cmp::min(current_round_min_rtt, rtt)); } else { self.current_round_min_rtt = Some(rtt); } self.rtt_sample_count += 1; if cwnd >= (LOW_CWND * max_datagram_size) && self.rtt_sample_count >= N_RTT_SAMPLE && self.current_round_min_rtt.is_some() && self.last_round_min_rtt.is_some() { let rtt_thresh = cmp::max( self.last_round_min_rtt.unwrap() / 8, MIN_RTT_THRESH, ); let rtt_thresh = cmp::min(rtt_thresh, MAX_RTT_THRESH); if self.current_round_min_rtt.unwrap() >= (self.last_round_min_rtt.unwrap() + rtt_thresh) { self.lss_start_time = Some(now); } } if let Some(end_pkt_num) = self.window_end { if packet.pkt_num >= end_pkt_num { self.window_end = None; } } } self.lss_start_time.is_some() } pub fn lss_cwnd( &self, pkt_size: usize, bytes_acked: usize, cwnd: usize, ssthresh: usize, max_datagram_size: usize, ) -> usize { let k = cwnd as f64 / (LSS_DIVISOR * ssthresh as f64); cwnd + cmp::min( pkt_size, max_datagram_size * recovery::ABC_L - cmp::min(bytes_acked, max_datagram_size * recovery::ABC_L), ) / k as usize } pub fn congestion_event(&mut self) { self.window_end = None; self.lss_start_time = None; } } #[cfg(test)] mod tests { use super::*; #[test] fn start_round() { let mut hspp = Hystart::default(); let pkt_num = 100; hspp.start_round(pkt_num); assert_eq!(hspp.window_end, Some(pkt_num)); assert_eq!(hspp.current_round_min_rtt, None); } #[test] fn lss_cwnd() { let hspp = Hystart::default(); let datagram_size = 1200; let mut cwnd = 24000; let ssthresh = 24000; let lss_cwnd = hspp.lss_cwnd(datagram_size, 0, cwnd, ssthresh, datagram_size); assert_eq!( cwnd + (datagram_size as f64 * LSS_DIVISOR) as usize, lss_cwnd ); cwnd = lss_cwnd; let lss_cwnd = hspp.lss_cwnd( datagram_size, datagram_size, cwnd, ssthresh, datagram_size, ); assert_eq!( cwnd + (datagram_size as f64 * LSS_DIVISOR) as usize, lss_cwnd ); } #[test] fn congestion_event() { let mut hspp = Hystart::default(); let pkt_num = 100; hspp.start_round(pkt_num); assert_eq!(hspp.window_end, Some(pkt_num)); hspp.congestion_event(); assert_eq!(hspp.window_end, None); } }
use std::cmp; use std::time::Duration; use std::time::Instant; use crate::packet; use crate::recovery; const LOW_CWND: usize = 16; const MIN_RTT_THRESH: Duration = Duration::from_millis(4); const MAX_RTT_THRESH: Duration = Duration::from_millis(16); pub const LSS_DIVISOR: f64 = 0.25; pub const N_RTT_SAMPLE: usize = 8; #[derive(Default)] pub struct Hystart { enabled: bool, window_end: Option<u64>, last_round_min_rtt: Option<Duration>, current_round_min_rtt: Option<Duration>, rtt_sample_count: usize, lss_start_time: Option<Instant>, } impl std::fmt::Debug for Hystart { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "window_end={:?} ", self.window_end)?; write!(f, "last_round_min_rtt={:?} ", self.last_round_min_rtt)?; write!(f, "current_round_min_rtt={:?} ", self.current_round_min_rtt)?; write!(f, "rtt_sample_count={:?} ", self.rtt_sample_count)?; write!(f, "lss_start_time={:?} ", self.lss_start_time)?; Ok(()) } } impl Hystart { pub fn new(enabled: bool) -> Self { Self { enabled, ..Default::default() } } pub fn enabled(&self) -> bool { self.enabled } pub fn lss_start_time(&self) -> Option<Instant> { self.lss_start_time } pub fn in_lss(&self, epoch: packet::Epoch) -> bool { self.enabled && epoch == packet::EPOCH_APPLICATION && self.lss_start_time().is_some() } pub fn start_round(&mut self, pkt_num: u64) {
} pub fn try_enter_lss( &mut self, packet: &recovery::Acked, rtt: Duration, cwnd: usize, now: Instant, max_datagram_size: usize, ) -> bool { if self.lss_start_time().is_none() { if let Some(current_round_min_rtt) = self.current_round_min_rtt { self.current_round_min_rtt = Some(cmp::min(current_round_min_rtt, rtt)); } else { self.current_round_min_rtt = Some(rtt); } self.rtt_sample_count += 1; if cwnd >= (LOW_CWND * max_datagram_size) && self.rtt_sample_count >= N_RTT_SAMPLE && self.current_round_min_rtt.is_some() && self.last_round_min_rtt.is_some() { let rtt_thresh = cmp::max( self.last_round_min_rtt.unwrap() / 8, MIN_RTT_THRESH, ); let rtt_thresh = cmp::min(rtt_thresh, MAX_RTT_THRESH); if self.current_round_min_rtt.unwrap() >= (self.last_round_min_rtt.unwrap() + rtt_thresh) { self.lss_start_time = Some(now); } } if let Some(end_pkt_num) = self.window_end { if packet.pkt_num >= end_pkt_num { self.window_end = None; } } } self.lss_start_time.is_some() } pub fn lss_cwnd( &self, pkt_size: usize, bytes_acked: usize, cwnd: usize, ssthresh: usize, max_datagram_size: usize, ) -> usize { let k = cwnd as f64 / (LSS_DIVISOR * ssthresh as f64); cwnd + cmp::min( pkt_size, max_datagram_size * recovery::ABC_L - cmp::min(bytes_acked, max_datagram_size * recovery::ABC_L), ) / k as usize } pub fn congestion_event(&mut self) { self.window_end = None; self.lss_start_time = None; } } #[cfg(test)] mod tests { use super::*; #[test] fn start_round() { let mut hspp = Hystart::default(); let pkt_num = 100; hspp.start_round(pkt_num); assert_eq!(hspp.window_end, Some(pkt_num)); assert_eq!(hspp.current_round_min_rtt, None); } #[test] fn lss_cwnd() { let hspp = Hystart::default(); let datagram_size = 1200; let mut cwnd = 24000; let ssthresh = 24000; let lss_cwnd = hspp.lss_cwnd(datagram_size, 0, cwnd, ssthresh, datagram_size); assert_eq!( cwnd + (datagram_size as f64 * LSS_DIVISOR) as usize, lss_cwnd ); cwnd = lss_cwnd; let lss_cwnd = hspp.lss_cwnd( datagram_size, datagram_size, cwnd, ssthresh, datagram_size, ); assert_eq!( cwnd + (datagram_size as f64 * LSS_DIVISOR) as usize, lss_cwnd ); } #[test] fn congestion_event() { let mut hspp = Hystart::default(); let pkt_num = 100; hspp.start_round(pkt_num); assert_eq!(hspp.window_end, Some(pkt_num)); hspp.congestion_event(); assert_eq!(hspp.window_end, None); } }
if self.window_end.is_none() { *self = Hystart { enabled: self.enabled, window_end: Some(pkt_num), last_round_min_rtt: self.current_round_min_rtt, current_round_min_rtt: None, rtt_sample_count: 0, lss_start_time: None, }; }
if_condition
[ { "content": "/// Returns true if the stream is bidirectional.\n\npub fn is_bidi(stream_id: u64) -> bool {\n\n (stream_id & 0x2) == 0\n\n}\n\n\n\n/// An iterator over QUIC streams.\n\n#[derive(Default)]\n\npub struct StreamIter {\n\n streams: Vec<u64>,\n\n}\n\n\n\nimpl StreamIter {\n\n #[inline]\n\n ...
Rust
src/ketos/string.rs
salewski/ketos
011287590ebeb6e6a199e34c8b9da14e2daeb1ce
use std::str::CharIndices; use crate::lexer::{BytePos, Span}; use crate::parser::{ParseError, ParseErrorKind}; pub fn parse_byte(s: &str, pos: BytePos) -> Result<(u8, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Single); r.parse_byte() } pub fn parse_byte_string(s: &str, pos: BytePos) -> Result<(Vec<u8>, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Normal); r.parse_byte_string() } pub fn parse_raw_byte_string(s: &str, pos: BytePos) -> Result<(Vec<u8>, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Raw); r.parse_byte_string() } pub fn parse_char(s: &str, pos: BytePos) -> Result<(char, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Single); r.parse_char() } pub fn parse_string(s: &str, pos: BytePos) -> Result<(String, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Normal); r.parse_string() } pub fn parse_raw_string(s: &str, pos: BytePos) -> Result<(String, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Raw); r.parse_string() } #[derive(Copy, Clone, Debug, Eq, PartialEq)] enum StringType { Single, Normal, Raw, } struct StringReader<'a> { chars: CharIndices<'a>, start: BytePos, last_index: usize, end_index: usize, ty: StringType, } impl<'a> StringReader<'a> { fn new(input: &str, pos: BytePos, ty: StringType) -> StringReader { StringReader{ chars: input.char_indices(), start: pos, last_index: 0, end_index: 0, ty, } } fn parse_byte(&mut self) -> Result<(u8, usize), ParseError> { self.expect('#', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; self.expect('b', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; self.expect('\'', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; let ch = match self.consume_char()? { '\'' => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidChar('\''))), '\\' => self.parse_byte_escape()?, ch if ch.is_ascii() => ch as u8, ch => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidByte(ch))) }; self.expect('\'', |slf, _| ParseError::new( slf.span_from(slf.start, 1), ParseErrorKind::UnterminatedChar))?; Ok((ch, self.last_index + 1)) } fn parse_char(&mut self) -> Result<(char, usize), ParseError> { self.expect('#', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; self.expect('\'', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; let ch = match self.consume_char()? { '\'' => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidChar('\''))), '\\' => self.parse_char_escape()?, ch => ch }; self.expect('\'', |slf, _| ParseError::new( slf.span_from(slf.start, 1), ParseErrorKind::UnterminatedChar))?; Ok((ch, self.last_index + 1)) } fn parse_byte_string(&mut self) -> Result<(Vec<u8>, usize), ParseError> { let mut res = Vec::new(); let n_hash = if self.ty == StringType::Raw { self.parse_raw_prefix()? } else { self.expect('"', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; 0 }; loop { match self.consume_char()? { '"' => { if n_hash == 0 || self.check_end(n_hash)? { break; } else { res.push(b'"'); } } '\\' if self.ty == StringType::Normal => { if let Some(ch) = self.parse_byte_string_escape()? { res.push(ch); } } ch if ch.is_ascii() => { res.push(ch as u8); } ch => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidByte(ch))) } } Ok((res, self.last_index + 1)) } fn parse_string(&mut self) -> Result<(String, usize), ParseError> { let mut res = String::new(); let n_hash = if self.ty == StringType::Raw { self.parse_raw_prefix()? } else { self.expect('"', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; 0usize }; loop { match self.consume_char()? { '"' => { if n_hash == 0 || self.check_end(n_hash)? { break; } else { res.push('"'); } } '\\' if self.ty == StringType::Normal => { if let Some(ch) = self.parse_string_escape()? { res.push(ch); } } ch => res.push(ch) } } Ok((res, self.last_index + 1)) } fn parse_raw_prefix(&mut self) -> Result<usize, ParseError> { let mut n_hash = 0; self.expect('r', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; loop { match self.consume_char()? { '#' => n_hash += 1, '"' => break, ch => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidChar(ch))) } } Ok(n_hash) } fn check_end(&mut self, n_hash: usize) -> Result<bool, ParseError> { let save_chars = self.chars.clone(); let save_index = self.last_index; for _ in 0..n_hash { if self.consume_char()? != '#' { self.chars = save_chars; self.last_index = save_index; return Ok(false); } } Ok(true) } fn consume_char(&mut self) -> Result<char, ParseError> { match self.chars.next() { Some((ind, '\r')) => { self.last_index = ind; self.end_index = ind + 1; match self.chars.next() { Some((ind, '\n')) => { self.last_index = ind; self.end_index = ind + 1; Ok('\n') } _ => Err(ParseError::new( self.span_from(ind as BytePos, 1), ParseErrorKind::InvalidChar('\r'))) } } Some((ind, ch)) => { self.last_index = ind; self.end_index = ind + ch.len_utf8(); Ok(ch) } None => Err(ParseError::new(self.span_from(self.start, 1), if self.ty == StringType::Single { ParseErrorKind::UnterminatedChar } else { ParseErrorKind::UnterminatedString })) } } fn expect<F>(&mut self, ch: char, f: F) -> Result<(), ParseError> where F: FnOnce(&Self, char) -> ParseError { let c = self.consume_char()?; if c == ch { Ok(()) } else { Err(f(self, c)) } } fn parse_byte_escape(&mut self) -> Result<u8, ParseError> { match self.consume_char()? { '\\' => Ok(b'\\'), '\'' => Ok(b'\''), '"' => Ok(b'"'), '0' => Ok(b'\0'), 'n' => Ok(b'\n'), 'r' => Ok(b'\r'), 't' => Ok(b'\t'), 'u' => Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidByteEscape('u'))), 'x' => self.parse_hex_byte_escape(), ch => Err(ParseError::new(self.span_one(), ParseErrorKind::UnknownCharEscape(ch))) } } fn parse_char_escape(&mut self) -> Result<char, ParseError> { match self.consume_char()? { '\\' => Ok('\\'), '\'' => Ok('\''), '"' => Ok('"'), '0' => Ok('\0'), 'n' => Ok('\n'), 'r' => Ok('\r'), 't' => Ok('\t'), 'u' => self.parse_unicode(), 'x' => self.parse_hex_char_escape(), ch => Err(ParseError::new(self.span_one(), ParseErrorKind::UnknownCharEscape(ch))) } } fn parse_byte_string_escape(&mut self) -> Result<Option<u8>, ParseError> { match self.peek_char()? { '\r' | '\n' => { self.consume_char()?; loop { match self.peek_char()? { ' ' | '\t' => { self.consume_char()?; }, _ => break } } Ok(None) } _ => self.parse_byte_escape().map(Some) } } fn parse_string_escape(&mut self) -> Result<Option<char>, ParseError> { match self.peek_char()? { '\r' | '\n' => { self.consume_char()?; loop { match self.peek_char()? { ' ' | '\t' => { self.consume_char()?; }, _ => break } } Ok(None) } _ => self.parse_char_escape().map(Some) } } fn parse_hex_byte_escape(&mut self) -> Result<u8, ParseError> { let a = match self.consume_char()? { ch if !ch.is_digit(16) => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape('x'))), ch => ch }; let b = match self.consume_char()? { ch if !ch.is_digit(16) => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape('x'))), ch => ch }; Ok(((a.to_digit(16).unwrap() << 4) | b.to_digit(16).unwrap()) as u8) } fn parse_hex_char_escape(&mut self) -> Result<char, ParseError> { let a = match self.consume_char()? { ch if !ch.is_digit(16) => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape('x'))), ch => ch }; let b = match self.consume_char()? { ch if !ch.is_digit(16) => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape('x'))), ch => ch }; if a > '7' { return Err(ParseError::new(self.back_span(1, 2), ParseErrorKind::InvalidNumericEscape('x'))); } Ok(((a.to_digit(16).unwrap() << 4) | b.to_digit(16).unwrap()) as u8 as char) } fn parse_unicode(&mut self) -> Result<char, ParseError> { self.expect('{', |slf, _| ParseError::new(slf.span_one(), ParseErrorKind::InvalidNumericEscape('u')))?; let mut n_digits = 0; let mut n_pad = 0; let mut total = 0; loop { match self.consume_char()? { '_' => { n_pad += 1; } '}' if n_digits != 0 => break, ch if ch.is_digit(16) => { if n_digits == 6 { return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidNumericEscape(ch))); } n_digits += 1; total = (total << 4) | ch.to_digit(16).unwrap(); } ch => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape(ch))), } } ::std::char::from_u32(total) .ok_or_else(|| ParseError::new( self.back_span(n_digits + n_pad, n_digits + n_pad), ParseErrorKind::InvalidNumericEscape('u'))) } fn peek_char(&mut self) -> Result<char, ParseError> { match self.chars.clone().next() { Some((_, ch)) => Ok(ch), None => Err(ParseError::new(self.span_from(self.start, 1), if self.ty == StringType::Single { ParseErrorKind::UnterminatedChar } else { ParseErrorKind::UnterminatedString })) } } fn back_span(&self, back: BytePos, len: BytePos) -> Span { let start = self.start + self.last_index as BytePos - back; Span{lo: start, hi: start + len} } fn span_one(&self) -> Span { Span{ lo: self.start + self.last_index as BytePos, hi: self.start + self.end_index as BytePos, } } fn span_from(&self, start: BytePos, len: BytePos) -> Span { Span{lo: start, hi: start + len} } } #[cfg(test)] mod test { use crate::parser::ParseError; use super::{StringReader, StringType}; fn parse_bytes(s: &str) -> Result<Vec<u8>, ParseError> { let mut r = StringReader::new(s, 0, StringType::Normal); r.parse_byte_string().map(|r| r.0) } fn parse_char(s: &str) -> Result<char, ParseError> { let mut r = StringReader::new(s, 0, StringType::Single); r.parse_char().map(|r| r.0) } fn parse_string(s: &str, ty: StringType) -> Result<String, ParseError> { let mut r = StringReader::new(s, 0, ty); r.parse_string().map(|r| r.0) } #[test] fn test_parse_string() { let n = StringType::Normal; let r = StringType::Raw; assert_eq!(parse_char(r"#'a'").unwrap(), 'a'); assert_eq!(parse_char(r"#'\''").unwrap(), '\''); assert_eq!(parse_char(r"#'\x7f'").unwrap(), '\x7f'); assert_eq!(parse_char(r"#'\u{1234}'").unwrap(), '\u{1234}'); assert_eq!(parse_char(r"#'\u{1_2__3_4}'").unwrap(), '\u{1234}'); assert_eq!(parse_string(r#""foo""#, n).unwrap(), "foo"); assert_eq!(parse_string(r#"r"foo""#, r).unwrap(), "foo"); assert_eq!(parse_string(r##"r#""foo""#"##, r).unwrap(), r#""foo""#); } #[test] fn test_errors() { assert_eq!(parse_bytes(r#""abc\xff""#).unwrap(), b"abc\xff"); assert!(parse_bytes(r#""abc\u{ff}""#).is_err()); } }
use std::str::CharIndices; use crate::lexer::{BytePos, Span}; use crate::parser::{ParseError, ParseErrorKind}; pub fn parse_byte(s: &str, pos: BytePos) -> Result<(u8, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Single); r.parse_byte() } pub fn parse_byte_string(s: &str, pos: BytePos) -> Result<(Vec<u8>, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Normal); r.parse_byte_string() } pub fn parse_raw_byte_string(s: &str, pos: BytePos) -> Result<(Vec<u8>, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Raw); r.parse_byte_string() } pub fn parse_char(s: &str, pos: BytePos) -> Result<(char, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Single); r.parse_char() } pub fn parse_string(s: &str, pos: BytePos) -> Result<(String, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Normal); r.parse_string() } pub fn parse_raw_string(s: &str, pos: BytePos) -> Result<(String, usize), ParseError> { let mut r = StringReader::new(s, pos, StringType::Raw); r.parse_string() } #[derive(Copy, Clone, Debug, Eq, PartialEq)] enum StringType { Single, Normal, Raw, } struct StringReader<'a> { chars: CharIndices<'a>, start: BytePos, last_index: usize, end_index: usize, ty: StringType, } impl<'a> StringReader<'a> { fn new(input: &str, pos: BytePos, ty: StringType) -> StringReader { StringReader{ chars: input.char_indices(), start: pos, last_index: 0, end_index: 0, ty, } } fn parse_byte(&mut self) -> Result<(u8, usize), ParseError> { self.expect('#', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; self.expect('b', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; self.expect('\'', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; let ch = match self.consume_char()? { '\'' => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidChar('\''))), '\\' => self.parse_byte_escape()?, ch if ch.is_ascii() => ch as u8, ch => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidByte(ch))) }; self.expect('\'', |slf, _| ParseError::new( slf.span_from(slf.start, 1), ParseErrorKind::UnterminatedChar))?; Ok((ch, self.last_index + 1)) } fn parse_char(&mut self) -> Result<(char, usize), ParseError> { self.expect('#', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; self.expect('\'', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; let ch = match self.consume_char()? { '\'' => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidChar('\''))), '\\' => self.parse_char_escape()?, ch => ch }; self.expect('\'', |slf, _| ParseError::new( slf.span_from(slf.start, 1), ParseErrorKind::UnterminatedChar))?; Ok((ch, self.last_index + 1)) } fn parse_byte_string(&mut self) -> Result<(Vec<u8>, usize), ParseError> { let mut res = Vec::new(); let n_hash = if self.ty == StringType::Raw { self.parse_raw_prefix()? } else { self.expect('"', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; 0 }; loop { match self.consume_char()? { '"' => { if n_hash == 0 || self.check_end(n_hash)? { break; } else { res.push(b'"'); } } '\\' if self.ty == StringType::Normal => { if let Some(ch) = self.parse_byte_string_escape()? { res.push(ch); } } ch if ch.is_ascii() => { res.push(ch as u8); } ch => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidByte(ch))) } } Ok((res, self.last_index + 1)) } fn parse_string(&mut self) -> Result<(String, usize), ParseError> { let mut res = String::new(); let n_hash = if self.ty == StringType::Raw { self.parse_raw_prefix()? } else { self.expect('"', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; 0usize }; loop { match self.consume_char()? { '"' => { if n_hash == 0 || self.check_end(n_hash)? { break; } else { res.push('"'); } } '\\' if self.ty == StringType::Normal => { if let Some(ch) = self.parse_string_escape()? { res.push(ch); } } ch => res.push(ch) } } Ok((res, self.last_index + 1)) } fn parse_raw_prefix(&mut self) -> Result<usize, ParseError> { let mut n_hash = 0; self.expect('r', |slf, ch| ParseError::new(slf.span_one(), ParseErrorKind::InvalidChar(ch)))?; loop { match self.consume_char()? { '#' => n_hash += 1, '"' => break, ch => return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidChar(ch))) } } Ok(n_hash) } fn check_end(&mut self, n_hash: usize) -> Result<bool, ParseError> { let save_chars = self.chars.clone(); let save_index = self.last_index; for _ in 0..n_hash { if self.consume_char()? != '#' { self.chars = save_chars; self.last_index = save_index; return Ok(false); } } Ok(true) } fn consume_char(&mut self) -> Result<char, ParseError> { match self.chars.next() { Some((ind, '\r')) => { self.last_index = ind; self.end_index = ind + 1; match self.chars.next() { Some((ind, '\n')) => { self.last_index = ind; self.end_index = ind + 1; Ok('\n') } _ => Err(ParseError::new( self.span_from(ind as BytePos, 1), ParseErrorKind::InvalidChar('\r'))) } } Some((ind, ch)) => { self.last_index = ind; self.end_index = ind + ch.len_utf8(); Ok(ch) } None => Err(ParseError::new(self.span_from(self.start, 1), if self.ty == StringType::Single { ParseErrorKind::UnterminatedChar } else { ParseErrorKind::UnterminatedString })) } } fn expect<F>(&mut self, ch: char, f: F) -> Result<(), ParseError> where F: FnOnce(&Self, char) -> ParseError { let c = self.consume_char()?; if c == ch { Ok(()) } else { Err(f(self, c)) } } fn parse_byte_escape(&mut self) -> Result<u8, ParseError> { match self.consume_char()? { '\\' => Ok(b'\\'), '\'' => Ok(b'\''), '"' => Ok(b'"'), '0' => Ok(b'\0'), 'n' => Ok(b'\n'), 'r' => Ok(b'\r'), 't' => Ok(b'\t'), 'u' => Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidByteEscape('u'))), 'x' => self.parse_hex_byte_escape(), ch => Err(ParseError::new(self.span_one(), ParseErrorKind::UnknownCharEscape(ch))) } } fn parse_char_escape(&mut self) -> Result<char, ParseError> { match self.consume_char()? { '\\' => Ok('\\'), '\'' => Ok('\''), '"' => Ok('"'), '0' => Ok('\0'), 'n' => Ok('\n'), 'r' => Ok('\r'), 't' => Ok('\t'), 'u' => self.parse_unicode(), 'x' => self.parse_hex_char_escape(), ch => Err(ParseError::new(self.span_one(), ParseErrorKind::UnknownCharEscape(ch))) } } fn parse_byte_string_escape(&mut self) -> Result<Option<u8>, ParseError> { match self.peek_char()? { '\r' | '\n' => { self.consume_char()?; loop { match self.peek_char()? { ' ' | '\t' => { self.consume_char()?; }, _ => break } } Ok(None) } _ => self.parse_byte_escape().map(Some) } } fn parse_string_escape(&mut self) -> Result<Option<char>, ParseError> { match self.peek_char()? { '\r' | '\n' => { self.consume_char()?; loop { match self.peek_char()? { ' ' | '\t' => { self.consume_char()?; }, _ => break } } Ok(None) } _ => self.parse_char_escape().map(Some) } } fn parse_hex_byte_escape(&mut self) -> Result<u8, ParseError> { let a = match self.consume_char()? { ch if !ch.is_digit(16) => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape('x'))), ch => ch }; let b = match self.consume_char()? { ch if !ch.is_digit(16) => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape('x'))), ch => ch }; Ok(((a.to_digit(16).unwrap() << 4) | b.to_digit(16).unwrap()) as u8) } fn parse_hex_char_escape(&mut self) -> Result<char, ParseError> { let a = match self.consume_char()? { ch if !ch.is_digit(16) => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape('x'))), ch => ch }; let b = match self.consume_char()? { ch if !ch.is_digit(16) => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape('x'))), ch => ch }; if a > '7' { return Err(ParseError::new(self.back_span(1, 2), ParseErrorKind::InvalidNumericEscape('x'))); } Ok(((a.to_digit(16).unwrap() << 4) | b.to_digit(16).unwrap()) as u8 as char) } fn parse_unicode(&mut self) -> Result<char, ParseError> { self.expect('{', |slf, _| ParseError::new(slf.span_one(), ParseErrorKind::InvalidNumericEscape('u')))?; let mut n_digits = 0; let mut n_pad = 0; let mut total = 0; loop { match self.consume_char()? { '_' => { n_pad += 1; } '}' if n_digits != 0 => break, ch if ch.is_digit(16) => { if n_digits == 6 { return Err(ParseError::new(self.span_one(), ParseErrorKind::InvalidNumericEscape(ch))); } n_digits += 1; total = (total << 4) | ch.to_digit(16).unwrap(); } ch => return Err(ParseError::new( self.span_one(), ParseErrorKind::InvalidNumericEscape(ch))), } } ::std::char::from_u32(total) .ok_or_else(|| ParseError::new( self.back_span(n_digits + n_pad, n_digits + n_pad), ParseErrorKind::InvalidNumericEscape('u'))) } fn peek_char(&mut self) -> Result<char, ParseError> {
} fn back_span(&self, back: BytePos, len: BytePos) -> Span { let start = self.start + self.last_index as BytePos - back; Span{lo: start, hi: start + len} } fn span_one(&self) -> Span { Span{ lo: self.start + self.last_index as BytePos, hi: self.start + self.end_index as BytePos, } } fn span_from(&self, start: BytePos, len: BytePos) -> Span { Span{lo: start, hi: start + len} } } #[cfg(test)] mod test { use crate::parser::ParseError; use super::{StringReader, StringType}; fn parse_bytes(s: &str) -> Result<Vec<u8>, ParseError> { let mut r = StringReader::new(s, 0, StringType::Normal); r.parse_byte_string().map(|r| r.0) } fn parse_char(s: &str) -> Result<char, ParseError> { let mut r = StringReader::new(s, 0, StringType::Single); r.parse_char().map(|r| r.0) } fn parse_string(s: &str, ty: StringType) -> Result<String, ParseError> { let mut r = StringReader::new(s, 0, ty); r.parse_string().map(|r| r.0) } #[test] fn test_parse_string() { let n = StringType::Normal; let r = StringType::Raw; assert_eq!(parse_char(r"#'a'").unwrap(), 'a'); assert_eq!(parse_char(r"#'\''").unwrap(), '\''); assert_eq!(parse_char(r"#'\x7f'").unwrap(), '\x7f'); assert_eq!(parse_char(r"#'\u{1234}'").unwrap(), '\u{1234}'); assert_eq!(parse_char(r"#'\u{1_2__3_4}'").unwrap(), '\u{1234}'); assert_eq!(parse_string(r#""foo""#, n).unwrap(), "foo"); assert_eq!(parse_string(r#"r"foo""#, r).unwrap(), "foo"); assert_eq!(parse_string(r##"r#""foo""#"##, r).unwrap(), r#""foo""#); } #[test] fn test_errors() { assert_eq!(parse_bytes(r#""abc\xff""#).unwrap(), b"abc\xff"); assert!(parse_bytes(r#""abc\u{ff}""#).is_err()); } }
match self.chars.clone().next() { Some((_, ch)) => Ok(ch), None => Err(ParseError::new(self.span_from(self.start, 1), if self.ty == StringType::Single { ParseErrorKind::UnterminatedChar } else { ParseErrorKind::UnterminatedString })) }
if_condition
[ { "content": "fn consume_block_comment(start: usize, chars: &mut CharIndices) -> Result<usize, ParseErrorKind> {\n\n let mut n_blocks = 1;\n\n\n\n loop {\n\n match chars.next() {\n\n Some((_, '|')) => match chars.clone().next() {\n\n Some((ind, '#')) => {\n\n ...
Rust
src/value.rs
Mingun/serde-gff
2bfacbb0b6b361da749082f99edaec474ccc6c7c
use indexmap::IndexMap; use crate::{Label, LocString, ResRef}; use crate::index::{U64Index, I64Index, F64Index, StringIndex, ResRefIndex, LocStringIndex, BinaryIndex}; #[derive(Debug, Clone, PartialEq)] pub enum SimpleValueRef { Byte(u8), Char(i8), Word(u16), Short(i16), Dword(u32), Int(i32), Dword64(U64Index), Int64(I64Index), Float(f32), Double(F64Index), String(StringIndex), ResRef(ResRefIndex), LocString(LocStringIndex), Void(BinaryIndex), } #[derive(Debug, Clone, PartialEq)] pub enum SimpleValue { Byte(u8), Char(i8), Word(u16), Short(i16), Dword(u32), Int(i32), Dword64(u64), Int64(i64), Float(f32), Double(f64), String(String), ResRef(ResRef), LocString(LocString), Void(Vec<u8>), } #[derive(Debug, Clone, PartialEq)] pub enum Value { Byte(u8), Char(i8), Word(u16), Short(i16), Dword(u32), Int(i32), Dword64(u64), Int64(i64), Float(f32), Double(f64), String(String), ResRef(ResRef), LocString(LocString), Void(Vec<u8>), Struct(IndexMap<Label, Value>), List(Vec<Value>), } impl From<SimpleValue> for Value { #[inline] fn from(value: SimpleValue) -> Value { use self::SimpleValue::*; match value { Byte(val) => Value::Byte(val), Char(val) => Value::Char(val), Word(val) => Value::Word(val), Short(val) => Value::Short(val), Dword(val) => Value::Dword(val), Int(val) => Value::Int(val), Dword64(val) => Value::Dword64(val), Int64(val) => Value::Int64(val), Float(val) => Value::Float(val), Double(val) => Value::Double(val), String(val) => Value::String(val), ResRef(val) => Value::ResRef(val), LocString(val) => Value::LocString(val), Void(val) => Value::Void(val), } } }
use indexmap::IndexMap; use crate::{Label, LocString, ResRef}; use crate::index::{U64Index, I64Index, F64Index, StringIndex, ResRefIndex, LocStringIndex, BinaryIndex}; #[derive(Debug, Clone, PartialEq)] pub enum SimpleValueRef { Byte(u8), Char(i8), Word(u16), Short(i16), Dword(u32), Int(i32), Dword64(U64Index), Int64(I64Index), Float(f32), Double(F64Index), String(StringIndex), ResRef(ResRefIndex), LocString(LocStringIndex), Void(BinaryIndex), } #[derive(Debug, Clone, PartialEq)] pub enum SimpleValue { Byte(u8), Char(i8), Word(u16),
(val) => Value::LocString(val), Void(val) => Value::Void(val), } } }
Short(i16), Dword(u32), Int(i32), Dword64(u64), Int64(i64), Float(f32), Double(f64), String(String), ResRef(ResRef), LocString(LocString), Void(Vec<u8>), } #[derive(Debug, Clone, PartialEq)] pub enum Value { Byte(u8), Char(i8), Word(u16), Short(i16), Dword(u32), Int(i32), Dword64(u64), Int64(i64), Float(f32), Double(f64), String(String), ResRef(ResRef), LocString(LocString), Void(Vec<u8>), Struct(IndexMap<Label, Value>), List(Vec<Value>), } impl From<SimpleValue> for Value { #[inline] fn from(value: SimpleValue) -> Value { use self::SimpleValue::*; match value { Byte(val) => Value::Byte(val), Char(val) => Value::Char(val), Word(val) => Value::Word(val), Short(val) => Value::Short(val), Dword(val) => Value::Dword(val), Int(val) => Value::Int(val), Dword64(val) => Value::Dword64(val), Int64(val) => Value::Int64(val), Float(val) => Value::Float(val), Double(val) => Value::Double(val), String(val) => Value::String(val), ResRef(val) => Value::ResRef(val), LocString
random
[ { "content": "/// Возможные представления ключа отображений в форматах данных\n\nenum Key {\n\n /// Ключ отображения является строкой, символом или массивом байт и соответствует\n\n /// метке поля\n\n Label(Label),\n\n /// Ключ отображения является числом и соответствует элементу многоязыковой строки\n\n S...
Rust
src/lib.rs
wangkang/hiredis
10bf22dc35c26e3846a025866993a2f361441d13
extern crate hiredis_sys as ffi; extern crate libc; use libc::{c_char, c_int, size_t}; use std::convert::{From, Into}; use std::ffi::{CStr, CString}; use std::marker::PhantomData; use std::{error, fmt, mem, slice}; macro_rules! raise( ($message:expr) => (return Err(Error::from($message))); ); macro_rules! success( ($context:expr) => (unsafe { if (*$context.raw).err != ffi::REDIS_OK { return Err(Error { kind: ErrorKind::from((*$context.raw).err as isize), message: c_str_to_string!((*$context.raw).errstr.as_ptr() as *const _), }); } }); ); macro_rules! str_to_cstr( ($string:expr) => (match CString::new($string) { Ok(string) => string, _ => raise!("failed to process a string"), }); ); macro_rules! c_str_to_string( ($string:expr, $size:expr) => ({ let slice: &CStr = mem::transmute(slice::from_raw_parts($string as *const c_char, $size as usize + 1)); String::from_utf8_lossy(slice.to_bytes()).into_owned() }); ($string:expr) => ({ String::from_utf8_lossy(CStr::from_ptr($string).to_bytes()).into_owned() }); ); macro_rules! c_str_to_vec_u8( ($string:expr, $size:expr) => ({ let slice: &[u8] = mem::transmute(slice::from_raw_parts($string as *const c_char, $size as usize)); Vec::from(slice) }); ); pub trait AsBytes { fn as_bytes(&self) -> &[u8]; } pub struct Context { raw: *mut ffi::redisContext, phantom: PhantomData<ffi::redisContext>, } #[derive(Debug)] pub struct Error { pub kind: ErrorKind, pub message: String, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ErrorKind { InputOutput = ffi::REDIS_ERR_IO as isize, EndOfFile = ffi::REDIS_ERR_EOF as isize, Protocol = ffi::REDIS_ERR_PROTOCOL as isize, OutOfMemory = ffi::REDIS_ERR_OOM as isize, Other = ffi::REDIS_ERR_OTHER as isize, } #[derive(Debug)] pub enum Reply { Status(String), Integer(i64), Bulk(Vec<u8>), Array(Vec<Reply>), Nil, } pub type Result<T> = std::result::Result<T, Error>; impl<'l> AsBytes for &'l str { #[inline] fn as_bytes(&self) -> &[u8] { (*self).as_bytes() } } impl<'l> AsBytes for &'l [u8] { #[inline] fn as_bytes(&self) -> &[u8] { self } } impl Context { pub fn new(host: &str, port: usize) -> Result<Context> { let context = Context { raw: unsafe { let raw = ffi::redisConnect(str_to_cstr!(host).as_ptr(), port as c_int); if raw.is_null() { raise!("failed to create a context"); } raw }, phantom: PhantomData, }; success!(context); Ok(context) } pub fn command<T: AsBytes>(&mut self, arguments: &[T]) -> Result<Reply> { let argc = arguments.len(); let mut argv: Vec<*const c_char> = Vec::with_capacity(argc); let mut argvlen = Vec::with_capacity(argc); for argument in arguments.iter() { let data = argument.as_bytes(); argv.push(data.as_ptr() as *const _); argvlen.push(data.len() as size_t); } let raw = unsafe { ffi::redisCommandArgv(self.raw, argc as c_int, argv.as_ptr() as *mut *const _, argvlen.as_ptr()) as *mut ffi::redisReply }; success!(self); debug_assert!(!raw.is_null()); unsafe { let reply = process_reply(raw); ffi::freeReplyObject(raw as *mut _); reply } } #[inline] pub fn reconnect(&mut self) -> Result<()> { if unsafe { ffi::redisReconnect(self.raw) } != ffi::REDIS_OK { raise!("failed to reconnect"); } Ok(()) } } impl Drop for Context { #[inline] fn drop(&mut self) { unsafe { ffi::redisFree(self.raw) }; } } impl<T> From<T> for Error where T: Into<String> { #[inline] fn from(message: T) -> Error { Error { kind: ErrorKind::Other, message: message.into() } } } impl fmt::Display for Error { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.message.fmt(formatter) } } impl error::Error for Error { #[inline] fn description(&self) -> &str { &self.message } } impl From<isize> for ErrorKind { #[inline] fn from(code: isize) -> ErrorKind { use ErrorKind::*; match code as c_int { ffi::REDIS_ERR_IO => InputOutput, ffi::REDIS_ERR_EOF => EndOfFile, ffi::REDIS_ERR_PROTOCOL => Protocol, ffi::REDIS_ERR_OOM => OutOfMemory, _ => Other, } } } impl fmt::Display for ErrorKind { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "Hiredis error code {}", *self as isize) } } #[inline] pub fn connect(host: &str, port: usize) -> Result<Context> { Context::new(host, port) } unsafe fn process_reply(raw: *mut ffi::redisReply) -> Result<Reply> { Ok(match (*raw).kind { ffi::REDIS_REPLY_STATUS => { Reply::Status(c_str_to_string!((*raw).string, (*raw).len)) }, ffi::REDIS_REPLY_INTEGER => { Reply::Integer((*raw).integer as i64) }, ffi::REDIS_REPLY_NIL => { Reply::Nil } ffi::REDIS_REPLY_STRING => { Reply::Bulk(c_str_to_vec_u8!((*raw).string, (*raw).len)) }, ffi::REDIS_REPLY_ARRAY => { let count = (*raw).elements as usize; let mut elements = Vec::with_capacity(count); for i in 0..count { elements.push(try!(process_reply(*(*raw).element.offset(i as isize)))); } Reply::Array(elements) }, ffi::REDIS_REPLY_ERROR => { raise!(c_str_to_string!((*raw).string, (*raw).len)); }, _ => { raise!("failed to identify a reply"); }, }) }
extern crate hiredis_sys as ffi; extern crate libc; use libc::{c_char, c_int, size_t}; use std::convert::{From, Into}; use std::ffi::{CStr, CString}; use std::marker::PhantomData; use std::{error, fmt, mem, slice}; macro_rules! raise( ($message:expr) => (return Err(Error::from($message))); ); macro_rules! success( ($context:expr) => (unsafe { if (*$context.raw).err != ffi::REDIS_OK { return Err(Error { kind: ErrorKind::from((*$context.raw).err as isize), message: c_str_to_string!((*$context.raw).errstr.as_ptr() as *const _), }); } }); ); macro_rules! str_to_cstr( ($string:expr) => (match CString::new($string) { Ok(string) => string, _ => raise!("failed to process a string"), }); ); macro_rules! c_str_to_string( ($string:expr, $size:expr) => ({ let slice: &CStr = mem::transmute(slice::from_raw_parts($string as *const c_char, $size as usize + 1)); String::from_utf8_lossy(slice.to_bytes()).into_owned() }); ($string:expr) => ({ String::from_utf8_lossy(CStr::from_ptr($string).to_bytes()).into_owned() }); ); macro_rules! c_str_to_vec_u8( ($string:expr, $size:expr) => ({ let slice: &[u8] = mem::transmute(slice::from_raw_parts($string as *const c_char, $size as usize)); Vec::from(slice) }); ); pub trait AsBytes { fn as_bytes(&self) -> &[u8]; } pub struct Context { raw: *mut ffi::redisContext, phantom: PhantomData<ffi::redisContext>, } #[derive(Debug)] pub struct Error { pub kind: ErrorKind, pub message: String, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ErrorKind { InputOutput = ffi::REDIS_ERR_IO as isize, EndOfFile = ffi::REDIS_ERR_EOF as isize, Protocol = ffi::REDIS_ERR_PROTOCOL as isize, OutOfMemory = ffi::REDIS_ERR_OOM as isize, Other = ffi::REDIS_ERR_OTHER as isize, } #[derive(Debug)] pub enum Reply { Status(String), Integer(i64), Bulk(Vec<u8>), Array(Vec<Reply>), Nil, } pub type Result<T> = std::result::Result<T, Error>; impl<'l> AsBytes for &'l str { #[inline] fn as_bytes(&self) -> &[u8] { (*self).as_bytes() } } impl<'l> AsBytes for &'l [u8] { #[inline] fn as_bytes(&self) -> &[u8] { self } } impl Context { pub fn new(host: &str, port: usize) -> Result<Context> { let context = Context { raw: unsafe { let raw = ffi::redisConnect(str_to_cstr!(host).as_ptr(), port as c_int); if raw.is_null() { raise!("failed to create a context"); } raw }, phantom: PhantomData, }; success!(context); Ok(context) } pub fn command<T: AsBytes>(&mut self, arguments: &[T]) -> Result<Reply> { let argc = arguments.len(); let mut argv: Vec<*const c_char> = Vec::with_capacity(argc); le
#[inline] pub fn reconnect(&mut self) -> Result<()> { if unsafe { ffi::redisReconnect(self.raw) } != ffi::REDIS_OK { raise!("failed to reconnect"); } Ok(()) } } impl Drop for Context { #[inline] fn drop(&mut self) { unsafe { ffi::redisFree(self.raw) }; } } impl<T> From<T> for Error where T: Into<String> { #[inline] fn from(message: T) -> Error { Error { kind: ErrorKind::Other, message: message.into() } } } impl fmt::Display for Error { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.message.fmt(formatter) } } impl error::Error for Error { #[inline] fn description(&self) -> &str { &self.message } } impl From<isize> for ErrorKind { #[inline] fn from(code: isize) -> ErrorKind { use ErrorKind::*; match code as c_int { ffi::REDIS_ERR_IO => InputOutput, ffi::REDIS_ERR_EOF => EndOfFile, ffi::REDIS_ERR_PROTOCOL => Protocol, ffi::REDIS_ERR_OOM => OutOfMemory, _ => Other, } } } impl fmt::Display for ErrorKind { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "Hiredis error code {}", *self as isize) } } #[inline] pub fn connect(host: &str, port: usize) -> Result<Context> { Context::new(host, port) } unsafe fn process_reply(raw: *mut ffi::redisReply) -> Result<Reply> { Ok(match (*raw).kind { ffi::REDIS_REPLY_STATUS => { Reply::Status(c_str_to_string!((*raw).string, (*raw).len)) }, ffi::REDIS_REPLY_INTEGER => { Reply::Integer((*raw).integer as i64) }, ffi::REDIS_REPLY_NIL => { Reply::Nil } ffi::REDIS_REPLY_STRING => { Reply::Bulk(c_str_to_vec_u8!((*raw).string, (*raw).len)) }, ffi::REDIS_REPLY_ARRAY => { let count = (*raw).elements as usize; let mut elements = Vec::with_capacity(count); for i in 0..count { elements.push(try!(process_reply(*(*raw).element.offset(i as isize)))); } Reply::Array(elements) }, ffi::REDIS_REPLY_ERROR => { raise!(c_str_to_string!((*raw).string, (*raw).len)); }, _ => { raise!("failed to identify a reply"); }, }) }
t mut argvlen = Vec::with_capacity(argc); for argument in arguments.iter() { let data = argument.as_bytes(); argv.push(data.as_ptr() as *const _); argvlen.push(data.len() as size_t); } let raw = unsafe { ffi::redisCommandArgv(self.raw, argc as c_int, argv.as_ptr() as *mut *const _, argvlen.as_ptr()) as *mut ffi::redisReply }; success!(self); debug_assert!(!raw.is_null()); unsafe { let reply = process_reply(raw); ffi::freeReplyObject(raw as *mut _); reply } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn push_pop_strings() {\n\n let mut context = ok!(hiredis::connect(\"127.0.0.1\", 6379));\n\n match ok!(context.command(&[\"RPUSH\", \"hiredis-baz\", \"Good news, everyone!\"])) {\n\n Reply::Integer(integer) => assert!(integer > 0),\n\n _ => assert!(false),\n\n }\...
Rust
src/docker_run/http_extra.rs
glotcode/docker-run
d2ee4c820a19ef063e12b115f0d4463c51dca430
use http::{Request, Response}; use http::header; use http::status; use http::header::CONTENT_LENGTH; use http::header::TRANSFER_ENCODING; use http::response; use std::io::{Read, Write}; use serde::Deserialize; use serde::de::DeserializeOwned; use std::io; use std::io::BufReader; use std::io::BufRead; use std::str::FromStr; use std::fmt; const CARRIAGE_RETURN: u8 = 0xD; const LINE_FEED: u8 = 0xA; pub enum Body { Empty(), Bytes(Vec<u8>), } #[derive(Debug)] pub enum Error { WriteRequest(io::Error), ReadResponse(io::Error), ParseResponseHead(ParseError), BadStatus(status::StatusCode, Vec<u8>), ReadChunkedBody(ReadChunkError), ReadBody(io::Error), DeserializeBody(serde_json::Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::WriteRequest(err) => { write!(f, "Failed to send request: {}", err) } Error::ReadResponse(err) => { write!(f, "Failed read response: {}", err) } Error::ParseResponseHead(err) => { write!(f, "Failed parse response head: {}", err) } Error::ReadChunkedBody(err) => { write!(f, "Failed read to chunked response body: {}", err) } Error::ReadBody(err) => { write!(f, "Failed read to response body: {}", err) } Error::BadStatus(status_code, body) => { let msg = String::from_utf8(body.to_vec()) .unwrap_or(format!("{:?}", body)); write!(f, "Unexpected status code {}: {}", status_code, msg) } Error::DeserializeBody(err) => { write!(f, "Failed deserialize response body: {}", err) } } } } pub fn send_request<Stream, ResponseBody>(mut stream: Stream, req: Request<Body>) -> Result<Response<ResponseBody>, Error> where Stream: Read + Write, ResponseBody: DeserializeOwned, { write_request_head(&mut stream, &req) .map_err(Error::WriteRequest)?; write_request_body(&mut stream, &req) .map_err(Error::WriteRequest)?; let mut reader = BufReader::new(stream); let response_head = read_response_head(&mut reader) .map_err(Error::ReadResponse)?; let response_parts = parse_response_head(response_head) .map_err(Error::ParseResponseHead)?; let raw_body = match get_transfer_encoding(&response_parts.headers) { TransferEncoding::Chunked() => { read_chunked_response_body(reader) .map_err(Error::ReadChunkedBody)? } _ => { let content_length = get_content_length(&response_parts.headers); read_response_body(content_length, reader) .map_err(Error::ReadBody)? } }; err_if_false(response_parts.status.is_success(), Error::BadStatus( response_parts.status, raw_body.clone() ))?; let body = serde_json::from_slice(&raw_body) .map_err(Error::DeserializeBody)?; Ok(Response::from_parts(response_parts, body)) } fn read_response_body<R: BufRead>(content_length: usize, mut reader: R) -> Result<Vec<u8>, io::Error> { if content_length > 0 { let mut buffer = vec![0u8; content_length]; reader.read_exact(&mut buffer)?; Ok(buffer) } else { Ok(vec![]) } } #[derive(Debug)] pub enum ReadChunkError { ReadChunkLength(io::Error), ParseChunkLength(std::num::ParseIntError), ReadChunk(io::Error), SkipLineFeed(io::Error), } impl fmt::Display for ReadChunkError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ReadChunkError::ReadChunkLength(err) => { write!(f, "Failed to read chunk length: {}", err) } ReadChunkError::ParseChunkLength(err) => { write!(f, "Failed parse chunk length: {}", err) } ReadChunkError::ReadChunk(err) => { write!(f, "Failed read chunk: {}", err) } ReadChunkError::SkipLineFeed(err) => { write!(f, "Failed read line feed at end of chunk: {}", err) } } } } fn read_chunked_response_body<R: BufRead>(mut reader: R) -> Result<Vec<u8>, ReadChunkError> { let mut body = vec![]; loop { let mut chunk = read_response_chunk(&mut reader)?; if chunk.is_empty() { break } body.append(&mut chunk) } Ok(body) } fn read_response_chunk<R: BufRead>(mut reader: R) -> Result<Vec<u8>, ReadChunkError> { let mut buffer = String::new(); reader.read_line(&mut buffer) .map_err(ReadChunkError::ReadChunkLength)?; let chunk_length = usize::from_str_radix(buffer.trim_end(), 16) .map_err(ReadChunkError::ParseChunkLength)?; let chunk = read_response_body(chunk_length, &mut reader) .map_err(ReadChunkError::ReadChunk)?; let mut void = String::new(); reader.read_line(&mut void) .map_err(ReadChunkError::SkipLineFeed)?; Ok(chunk) } fn get_content_length(headers: &header::HeaderMap<header::HeaderValue>) -> usize { headers.get(CONTENT_LENGTH) .map(|value| { value .to_str() .unwrap_or("") .parse() .unwrap_or(0) }) .unwrap_or(0) } enum TransferEncoding { NoEncoding(), Chunked(), Other(String), } impl TransferEncoding { pub fn from_str(value: &str) -> TransferEncoding { match value { "chunked" => { TransferEncoding::Chunked() } "" => { TransferEncoding::NoEncoding() } other => { TransferEncoding::Other(other.to_string()) } } } } fn get_transfer_encoding(headers: &header::HeaderMap<header::HeaderValue>) -> TransferEncoding { let value = headers.get(TRANSFER_ENCODING) .map(|value| value.to_str().unwrap_or("").to_string()) .unwrap_or_else(|| "".to_string()); TransferEncoding::from_str(&value) } #[derive(Debug)] pub struct EmptyResponse {} impl<'de> Deserialize<'de> for EmptyResponse { fn deserialize<D>(_: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { Ok(EmptyResponse{}) } } pub fn format_request_line<T>(req: &Request<T>) -> String { let path = req.uri() .path_and_query() .map(|x| x.as_str()) .unwrap_or(""); format!("{} {} {:?}", req.method(), path, req.version()) } pub fn format_request_headers<T>(req: &Request<T>) -> String { req.headers() .iter() .map(|(key, value)| format!("{}: {}", key, value.to_str().unwrap_or(""))) .collect::<Vec<String>>() .join("\r\n") } fn write_request_head<T, W: Write>(mut writer: W, req: &Request<T>) -> Result<(), io::Error> { let request_line = format_request_line(&req); write!(writer, "{}\r\n", request_line)?; let headers = format_request_headers(&req); write!(writer, "{}\r\n\r\n", headers) } fn write_request_body<W: Write>(mut writer: W, req: &Request<Body>) -> Result<(), io::Error>{ match req.body() { Body::Empty() => { Ok(()) } Body::Bytes(body) => { writer.write_all(body) } } } fn read_response_head<R: BufRead>(mut reader: R) -> Result<Vec<u8>, io::Error> { let mut response_headers = Vec::new(); for _ in 0..20 { if response_headers.ends_with(&[CARRIAGE_RETURN, LINE_FEED, CARRIAGE_RETURN, LINE_FEED]) { break; } reader.read_until(LINE_FEED, &mut response_headers)?; } Ok(response_headers) } #[derive(Debug)] pub enum ParseError { Parse(httparse::Error), Empty(), Partial(), Response(ResponseError), } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ParseError::Parse(err) => { write!(f, "{}", err) } ParseError::Empty() => { write!(f, "Received empty response") } ParseError::Partial() => { write!(f, "Received partial response") } ParseError::Response(err) => { write!(f, "Invalid response: {}", err) } } } } pub fn parse_response_head(bytes: Vec<u8>) -> Result<response::Parts, ParseError> { let mut headers = [httparse::EMPTY_HEADER; 30]; let mut resp = httparse::Response::new(&mut headers); match resp.parse(&bytes) { Ok(httparse::Status::Complete(_)) => { let parts = to_http_parts(resp) .map_err(ParseError::Response)?; Ok(parts) } Ok(httparse::Status::Partial) => { if bytes.is_empty() { Err(ParseError::Empty()) } else { Err(ParseError::Partial()) } } Err(err) => { Err(ParseError::Parse(err)) } } } #[derive(Debug)] pub enum ResponseError { InvalidBuilder(), HeaderName(header::InvalidHeaderName), HeaderValue(header::InvalidHeaderValue), StatusCode(), Builder(http::Error), } impl fmt::Display for ResponseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ResponseError::InvalidBuilder() => { write!(f, "Invalid response builder") } ResponseError::HeaderName(err) => { write!(f, "Invalid header name: {}", err) } ResponseError::HeaderValue(err) => { write!(f, "Invalid header value: {}", err) } ResponseError::StatusCode() => { write!(f, "Failed to parse status code") } ResponseError::Builder(err) => { write!(f, "Response builder error: {}", err) } } } } fn to_http_parts(parsed: httparse::Response) -> Result<response::Parts, ResponseError> { let mut builder = Response::builder(); let headers = builder.headers_mut() .ok_or(ResponseError::InvalidBuilder())?; for hdr in parsed.headers.iter() { let name = header::HeaderName::from_str(hdr.name) .map_err(ResponseError::HeaderName)?; let value = header::HeaderValue::from_bytes(hdr.value) .map_err(ResponseError::HeaderValue)?; headers.insert(name, value); } let code = parsed.code .ok_or(ResponseError::StatusCode())?; let response = builder.status(code).body(()) .map_err(ResponseError::Builder)?; Ok(response.into_parts().0) } fn err_if_false<E>(value: bool, err: E) -> Result<(), E> { if value { Ok(()) } else { Err(err) } }
use http::{Request, Response}; use http::header; use http::status; use http::header::CONTENT_LENGTH; use http::header::TRANSFER_ENCODING; use http::response; use std::io::{Read, Write}; use serde::Deserialize; use serde::de::DeserializeOwned; use std::io; use std::io::BufReader; use std::io::BufRead; use std::str::FromStr; use std::fmt; const CARRIAGE_RETURN: u8 = 0xD; const LINE_FEED: u8 = 0xA; pub enum Body { Empty(), Bytes(Vec<u8>), } #[derive(Debug)] pub enum Error { WriteRequest(io::Error), ReadResponse(io::Error), ParseResponseHead(ParseError), BadStatus(status::StatusCode, Vec<u8>), ReadChunkedBody(ReadChunkError), ReadBody(io::Error), DeserializeBody(serde_json::Error), } impl fmt::Display for Error {
} pub fn send_request<Stream, ResponseBody>(mut stream: Stream, req: Request<Body>) -> Result<Response<ResponseBody>, Error> where Stream: Read + Write, ResponseBody: DeserializeOwned, { write_request_head(&mut stream, &req) .map_err(Error::WriteRequest)?; write_request_body(&mut stream, &req) .map_err(Error::WriteRequest)?; let mut reader = BufReader::new(stream); let response_head = read_response_head(&mut reader) .map_err(Error::ReadResponse)?; let response_parts = parse_response_head(response_head) .map_err(Error::ParseResponseHead)?; let raw_body = match get_transfer_encoding(&response_parts.headers) { TransferEncoding::Chunked() => { read_chunked_response_body(reader) .map_err(Error::ReadChunkedBody)? } _ => { let content_length = get_content_length(&response_parts.headers); read_response_body(content_length, reader) .map_err(Error::ReadBody)? } }; err_if_false(response_parts.status.is_success(), Error::BadStatus( response_parts.status, raw_body.clone() ))?; let body = serde_json::from_slice(&raw_body) .map_err(Error::DeserializeBody)?; Ok(Response::from_parts(response_parts, body)) } fn read_response_body<R: BufRead>(content_length: usize, mut reader: R) -> Result<Vec<u8>, io::Error> { if content_length > 0 { let mut buffer = vec![0u8; content_length]; reader.read_exact(&mut buffer)?; Ok(buffer) } else { Ok(vec![]) } } #[derive(Debug)] pub enum ReadChunkError { ReadChunkLength(io::Error), ParseChunkLength(std::num::ParseIntError), ReadChunk(io::Error), SkipLineFeed(io::Error), } impl fmt::Display for ReadChunkError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ReadChunkError::ReadChunkLength(err) => { write!(f, "Failed to read chunk length: {}", err) } ReadChunkError::ParseChunkLength(err) => { write!(f, "Failed parse chunk length: {}", err) } ReadChunkError::ReadChunk(err) => { write!(f, "Failed read chunk: {}", err) } ReadChunkError::SkipLineFeed(err) => { write!(f, "Failed read line feed at end of chunk: {}", err) } } } } fn read_chunked_response_body<R: BufRead>(mut reader: R) -> Result<Vec<u8>, ReadChunkError> { let mut body = vec![]; loop { let mut chunk = read_response_chunk(&mut reader)?; if chunk.is_empty() { break } body.append(&mut chunk) } Ok(body) } fn read_response_chunk<R: BufRead>(mut reader: R) -> Result<Vec<u8>, ReadChunkError> { let mut buffer = String::new(); reader.read_line(&mut buffer) .map_err(ReadChunkError::ReadChunkLength)?; let chunk_length = usize::from_str_radix(buffer.trim_end(), 16) .map_err(ReadChunkError::ParseChunkLength)?; let chunk = read_response_body(chunk_length, &mut reader) .map_err(ReadChunkError::ReadChunk)?; let mut void = String::new(); reader.read_line(&mut void) .map_err(ReadChunkError::SkipLineFeed)?; Ok(chunk) } fn get_content_length(headers: &header::HeaderMap<header::HeaderValue>) -> usize { headers.get(CONTENT_LENGTH) .map(|value| { value .to_str() .unwrap_or("") .parse() .unwrap_or(0) }) .unwrap_or(0) } enum TransferEncoding { NoEncoding(), Chunked(), Other(String), } impl TransferEncoding { pub fn from_str(value: &str) -> TransferEncoding { match value { "chunked" => { TransferEncoding::Chunked() } "" => { TransferEncoding::NoEncoding() } other => { TransferEncoding::Other(other.to_string()) } } } } fn get_transfer_encoding(headers: &header::HeaderMap<header::HeaderValue>) -> TransferEncoding { let value = headers.get(TRANSFER_ENCODING) .map(|value| value.to_str().unwrap_or("").to_string()) .unwrap_or_else(|| "".to_string()); TransferEncoding::from_str(&value) } #[derive(Debug)] pub struct EmptyResponse {} impl<'de> Deserialize<'de> for EmptyResponse { fn deserialize<D>(_: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { Ok(EmptyResponse{}) } } pub fn format_request_line<T>(req: &Request<T>) -> String { let path = req.uri() .path_and_query() .map(|x| x.as_str()) .unwrap_or(""); format!("{} {} {:?}", req.method(), path, req.version()) } pub fn format_request_headers<T>(req: &Request<T>) -> String { req.headers() .iter() .map(|(key, value)| format!("{}: {}", key, value.to_str().unwrap_or(""))) .collect::<Vec<String>>() .join("\r\n") } fn write_request_head<T, W: Write>(mut writer: W, req: &Request<T>) -> Result<(), io::Error> { let request_line = format_request_line(&req); write!(writer, "{}\r\n", request_line)?; let headers = format_request_headers(&req); write!(writer, "{}\r\n\r\n", headers) } fn write_request_body<W: Write>(mut writer: W, req: &Request<Body>) -> Result<(), io::Error>{ match req.body() { Body::Empty() => { Ok(()) } Body::Bytes(body) => { writer.write_all(body) } } } fn read_response_head<R: BufRead>(mut reader: R) -> Result<Vec<u8>, io::Error> { let mut response_headers = Vec::new(); for _ in 0..20 { if response_headers.ends_with(&[CARRIAGE_RETURN, LINE_FEED, CARRIAGE_RETURN, LINE_FEED]) { break; } reader.read_until(LINE_FEED, &mut response_headers)?; } Ok(response_headers) } #[derive(Debug)] pub enum ParseError { Parse(httparse::Error), Empty(), Partial(), Response(ResponseError), } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ParseError::Parse(err) => { write!(f, "{}", err) } ParseError::Empty() => { write!(f, "Received empty response") } ParseError::Partial() => { write!(f, "Received partial response") } ParseError::Response(err) => { write!(f, "Invalid response: {}", err) } } } } pub fn parse_response_head(bytes: Vec<u8>) -> Result<response::Parts, ParseError> { let mut headers = [httparse::EMPTY_HEADER; 30]; let mut resp = httparse::Response::new(&mut headers); match resp.parse(&bytes) { Ok(httparse::Status::Complete(_)) => { let parts = to_http_parts(resp) .map_err(ParseError::Response)?; Ok(parts) } Ok(httparse::Status::Partial) => { if bytes.is_empty() { Err(ParseError::Empty()) } else { Err(ParseError::Partial()) } } Err(err) => { Err(ParseError::Parse(err)) } } } #[derive(Debug)] pub enum ResponseError { InvalidBuilder(), HeaderName(header::InvalidHeaderName), HeaderValue(header::InvalidHeaderValue), StatusCode(), Builder(http::Error), } impl fmt::Display for ResponseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ResponseError::InvalidBuilder() => { write!(f, "Invalid response builder") } ResponseError::HeaderName(err) => { write!(f, "Invalid header name: {}", err) } ResponseError::HeaderValue(err) => { write!(f, "Invalid header value: {}", err) } ResponseError::StatusCode() => { write!(f, "Failed to parse status code") } ResponseError::Builder(err) => { write!(f, "Response builder error: {}", err) } } } } fn to_http_parts(parsed: httparse::Response) -> Result<response::Parts, ResponseError> { let mut builder = Response::builder(); let headers = builder.headers_mut() .ok_or(ResponseError::InvalidBuilder())?; for hdr in parsed.headers.iter() { let name = header::HeaderName::from_str(hdr.name) .map_err(ResponseError::HeaderName)?; let value = header::HeaderValue::from_bytes(hdr.value) .map_err(ResponseError::HeaderValue)?; headers.insert(name, value); } let code = parsed.code .ok_or(ResponseError::StatusCode())?; let response = builder.status(code).body(()) .map_err(ResponseError::Builder)?; Ok(response.into_parts().0) } fn err_if_false<E>(value: bool, err: E) -> Result<(), E> { if value { Ok(()) } else { Err(err) } }
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::WriteRequest(err) => { write!(f, "Failed to send request: {}", err) } Error::ReadResponse(err) => { write!(f, "Failed read response: {}", err) } Error::ParseResponseHead(err) => { write!(f, "Failed parse response head: {}", err) } Error::ReadChunkedBody(err) => { write!(f, "Failed read to chunked response body: {}", err) } Error::ReadBody(err) => { write!(f, "Failed read to response body: {}", err) } Error::BadStatus(status_code, body) => { let msg = String::from_utf8(body.to_vec()) .unwrap_or(format!("{:?}", body)); write!(f, "Unexpected status code {}: {}", status_code, msg) } Error::DeserializeBody(err) => { write!(f, "Failed deserialize response body: {}", err) } } }
function_block-full_function
[ { "content": "pub fn remove_container<Stream: Read + Write>(stream: Stream, container_id: &str) -> Result<http::Response<http_extra::EmptyResponse>, Error> {\n\n let req = remove_container_request(container_id)\n\n .map_err(|x| Error::PrepareRequest(PrepareRequestError::Request(x)))?;\n\n\n\n http_...
Rust
src/compute/nullif.rs
abreis/arrow2
982454620d1db7964a4e272b3f74745563b6ba5a
use crate::array::PrimitiveArray; use crate::compute::comparison::primitive_compare_values_op; use crate::datatypes::DataType; use crate::error::{ArrowError, Result}; use crate::{array::Array, types::NativeType}; use super::utils::combine_validities; pub fn nullif_primitive<T: NativeType>( lhs: &PrimitiveArray<T>, rhs: &PrimitiveArray<T>, ) -> Result<PrimitiveArray<T>> { if lhs.data_type() != rhs.data_type() { return Err(ArrowError::InvalidArgumentError( "Arrays must have the same logical type".to_string(), )); } let equal = primitive_compare_values_op(lhs.values(), rhs.values(), |lhs, rhs| lhs != rhs); let equal = equal.into(); let validity = combine_validities(lhs.validity(), &equal); Ok(PrimitiveArray::<T>::from_data( lhs.data_type().clone(), lhs.values_buffer().clone(), validity, )) } pub fn can_nullif(lhs: &DataType, rhs: &DataType) -> bool { if lhs != rhs { return false; }; use DataType::*; matches!( lhs, UInt8 | UInt16 | UInt32 | UInt64 | Int8 | Int16 | Int32 | Int64 | Float32 | Float64 | Time32(_) | Time64(_) | Date32 | Date64 | Timestamp(_, _) | Duration(_) ) } pub fn nullif(lhs: &dyn Array, rhs: &dyn Array) -> Result<Box<dyn Array>> { if lhs.data_type() != rhs.data_type() { return Err(ArrowError::InvalidArgumentError( "Nullif expects arrays of the the same logical type".to_string(), )); } if lhs.len() != rhs.len() { return Err(ArrowError::InvalidArgumentError( "Nullif expects arrays of the the same length".to_string(), )); } use crate::datatypes::DataType::*; match lhs.data_type() { UInt8 => nullif_primitive::<u8>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), UInt16 => nullif_primitive::<u16>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), UInt32 => nullif_primitive::<u32>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), UInt64 => nullif_primitive::<u64>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Int8 => nullif_primitive::<i8>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Int16 => nullif_primitive::<i16>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Int32 | Time32(_) | Date32 => nullif_primitive::<i32>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Int64 | Time64(_) | Date64 | Timestamp(_, _) | Duration(_) => nullif_primitive::<i64>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Float32 => nullif_primitive::<f32>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Float64 => nullif_primitive::<f64>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), other => Err(ArrowError::NotYetImplemented(format!( "Nullif is not implemented for logical datatype {}", other ))), } }
use crate::array::PrimitiveArray; use crate::compute::comparison::primitive_compare_values_op; use crate::datatypes::DataType; use crate::error::{ArrowError, Result}; use crate::{array::Array, types::NativeType}; use super::utils::combine_validities; pub fn nullif_primitive<T: NativeType>( lhs: &PrimitiveArray<T>, rhs: &PrimitiveArray<T>, ) -> Result<PrimitiveArray<T>> { if lhs.data_type() != rhs.data_type() { return Err(ArrowError::InvalidArgumentError( "Arrays must have the same logical type".to_string(), )); } let equal = primitive_compare_values_op(lhs.values(), rhs.values(), |lhs, rhs| lhs != rhs); let equal = equal.into(); let validity = combine_validities(lhs.validity(), &equal); Ok(PrimitiveArray::<T>::from_data( lhs.data_type().clone(), lhs.values_buffer().clone(), validity, )) } pub fn can_nullif(lhs: &DataType, rhs: &DataType) -> bool { if lhs != rhs { return false; }; use DataType::*; matches!( lhs, UInt8 | UInt16 | UInt32 | UInt64 | Int8 | Int16 | Int32 | Int64 | Float32 | Float64 | Time32(_) | Time64(_) | Date32 | Date64 | Timestamp(_, _) | Duration(_) ) }
pub fn nullif(lhs: &dyn Array, rhs: &dyn Array) -> Result<Box<dyn Array>> { if lhs.data_type() != rhs.data_type() { return Err(ArrowError::InvalidArgumentError( "Nullif expects arrays of the the same logical type".to_string(), )); } if lhs.len() != rhs.len() { return Err(ArrowError::InvalidArgumentError( "Nullif expects arrays of the the same length".to_string(), )); } use crate::datatypes::DataType::*; match lhs.data_type() { UInt8 => nullif_primitive::<u8>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), UInt16 => nullif_primitive::<u16>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), UInt32 => nullif_primitive::<u32>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), UInt64 => nullif_primitive::<u64>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Int8 => nullif_primitive::<i8>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Int16 => nullif_primitive::<i16>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Int32 | Time32(_) | Date32 => nullif_primitive::<i32>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Int64 | Time64(_) | Date64 | Timestamp(_, _) | Duration(_) => nullif_primitive::<i64>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Float32 => nullif_primitive::<f32>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), Float64 => nullif_primitive::<f64>( lhs.as_any().downcast_ref().unwrap(), rhs.as_any().downcast_ref().unwrap(), ) .map(|x| Box::new(x) as Box<dyn Array>), other => Err(ArrowError::NotYetImplemented(format!( "Nullif is not implemented for logical datatype {}", other ))), } }
function_block-full_function
[ { "content": "/// Logically compares two [ArrayData].\n\n/// Two arrays are logically equal if and only if:\n\n/// * their data types are equal\n\n/// * their lengths are equal\n\n/// * their null counts are equal\n\n/// * their null bitmaps are equal\n\n/// * each of their items are equal\n\n/// two items are ...
Rust
meilisearch-core/src/update/settings_update.rs
irevoire/MeiliSearch
66c455413695ae8bda7af9e909077b9402d65b2e
use std::{borrow::Cow, collections::{BTreeMap, BTreeSet}}; use heed::Result as ZResult; use fst::{SetBuilder, set::OpBuilder}; use sdset::SetBuf; use meilisearch_schema::Schema; use meilisearch_tokenizer::analyzer::{Analyzer, AnalyzerConfig}; use crate::database::{MainT, UpdateT}; use crate::settings::{UpdateState, SettingsUpdate, RankingRule}; use crate::update::documents_addition::reindex_all_documents; use crate::update::{next_update_id, Update}; use crate::{store, MResult, Error}; pub fn push_settings_update( writer: &mut heed::RwTxn<UpdateT>, updates_store: store::Updates, updates_results_store: store::UpdatesResults, settings: SettingsUpdate, ) -> ZResult<u64> { let last_update_id = next_update_id(writer, updates_store, updates_results_store)?; let update = Update::settings(settings); updates_store.put_update(writer, last_update_id, &update)?; Ok(last_update_id) } pub fn apply_settings_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, settings: SettingsUpdate, ) -> MResult<()> { let mut must_reindex = false; let mut schema = match index.main.schema(writer)? { Some(schema) => schema, None => { match settings.primary_key.clone() { UpdateState::Update(id) => Schema::with_primary_key(&id), _ => return Err(Error::MissingPrimaryKey) } } }; match settings.ranking_rules { UpdateState::Update(v) => { let ranked_field: Vec<&str> = v.iter().filter_map(RankingRule::field).collect(); schema.update_ranked(&ranked_field)?; index.main.put_ranking_rules(writer, &v)?; must_reindex = true; }, UpdateState::Clear => { index.main.delete_ranking_rules(writer)?; schema.clear_ranked(); must_reindex = true; }, UpdateState::Nothing => (), } match settings.distinct_attribute { UpdateState::Update(v) => { let field_id = schema.insert(&v)?; index.main.put_distinct_attribute(writer, field_id)?; }, UpdateState::Clear => { index.main.delete_distinct_attribute(writer)?; }, UpdateState::Nothing => (), } match settings.searchable_attributes.clone() { UpdateState::Update(v) => { if v.iter().any(|e| e == "*") || v.is_empty() { schema.set_all_searchable(); } else { schema.update_searchable(v)?; } must_reindex = true; }, UpdateState::Clear => { schema.set_all_searchable(); must_reindex = true; }, UpdateState::Nothing => (), } match settings.displayed_attributes.clone() { UpdateState::Update(v) => { if v.contains("*") || v.is_empty() { schema.set_all_displayed(); } else { schema.update_displayed(v)? } }, UpdateState::Clear => { schema.set_all_displayed(); }, UpdateState::Nothing => (), } match settings.attributes_for_faceting { UpdateState::Update(attrs) => { apply_attributes_for_faceting_update(writer, index, &mut schema, &attrs)?; must_reindex = true; }, UpdateState::Clear => { index.main.delete_attributes_for_faceting(writer)?; index.facets.clear(writer)?; }, UpdateState::Nothing => (), } index.main.put_schema(writer, &schema)?; match settings.stop_words { UpdateState::Update(stop_words) => { if apply_stop_words_update(writer, index, stop_words)? { must_reindex = true; } }, UpdateState::Clear => { if apply_stop_words_update(writer, index, BTreeSet::new())? { must_reindex = true; } }, UpdateState::Nothing => (), } match settings.synonyms { UpdateState::Update(synonyms) => apply_synonyms_update(writer, index, synonyms)?, UpdateState::Clear => apply_synonyms_update(writer, index, BTreeMap::new())?, UpdateState::Nothing => (), } if must_reindex { reindex_all_documents(writer, index)?; } Ok(()) } fn apply_attributes_for_faceting_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, schema: &mut Schema, attributes: &[String] ) -> MResult<()> { let mut attribute_ids = Vec::new(); for name in attributes { attribute_ids.push(schema.insert(name)?); } let attributes_for_faceting = SetBuf::from_dirty(attribute_ids); index.main.put_attributes_for_faceting(writer, &attributes_for_faceting)?; Ok(()) } pub fn apply_stop_words_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, stop_words: BTreeSet<String>, ) -> MResult<bool> { let mut must_reindex = false; let old_stop_words: BTreeSet<String> = index.main .stop_words_fst(writer)? .stream() .into_strs()? .into_iter() .collect(); let deletion: BTreeSet<String> = old_stop_words.difference(&stop_words).cloned().collect(); let addition: BTreeSet<String> = stop_words.difference(&old_stop_words).cloned().collect(); if !addition.is_empty() { apply_stop_words_addition(writer, index, addition)?; } if !deletion.is_empty() { must_reindex = true; apply_stop_words_deletion(writer, index, deletion)?; } let words_fst = index.main.words_fst(writer)?; if !words_fst.is_empty() { let stop_words = fst::Set::from_iter(stop_words)?; let op = OpBuilder::new() .add(&words_fst) .add(&stop_words) .difference(); let mut builder = fst::SetBuilder::memory(); builder.extend_stream(op)?; let words_fst = builder.into_set(); index.main.put_words_fst(writer, &words_fst)?; index.main.put_stop_words_fst(writer, &stop_words)?; } Ok(must_reindex) } fn apply_stop_words_addition( writer: &mut heed::RwTxn<MainT>, index: &store::Index, addition: BTreeSet<String>, ) -> MResult<()> { let main_store = index.main; let postings_lists_store = index.postings_lists; let mut stop_words_builder = SetBuilder::memory(); for word in addition { stop_words_builder.insert(&word)?; postings_lists_store.del_postings_list(writer, word.as_bytes())?; } let delta_stop_words = stop_words_builder.into_set(); let words_fst = main_store.words_fst(writer)?; if !words_fst.is_empty() { let op = OpBuilder::new() .add(&words_fst) .add(&delta_stop_words) .difference(); let mut word_fst_builder = SetBuilder::memory(); word_fst_builder.extend_stream(op)?; let word_fst = word_fst_builder.into_set(); main_store.put_words_fst(writer, &word_fst)?; } let stop_words_fst = main_store.stop_words_fst(writer)?; let op = OpBuilder::new() .add(&stop_words_fst) .add(&delta_stop_words) .r#union(); let mut stop_words_builder = SetBuilder::memory(); stop_words_builder.extend_stream(op)?; let stop_words_fst = stop_words_builder.into_set(); main_store.put_stop_words_fst(writer, &stop_words_fst)?; Ok(()) } fn apply_stop_words_deletion( writer: &mut heed::RwTxn<MainT>, index: &store::Index, deletion: BTreeSet<String>, ) -> MResult<()> { let mut stop_words_builder = SetBuilder::memory(); for word in deletion { stop_words_builder.insert(&word)?; } let delta_stop_words = stop_words_builder.into_set(); let stop_words_fst = index.main.stop_words_fst(writer)?; let op = OpBuilder::new() .add(&stop_words_fst) .add(&delta_stop_words) .difference(); let mut stop_words_builder = SetBuilder::memory(); stop_words_builder.extend_stream(op)?; let stop_words_fst = stop_words_builder.into_set(); Ok(index.main.put_stop_words_fst(writer, &stop_words_fst)?) } pub fn apply_synonyms_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, synonyms: BTreeMap<String, Vec<String>>, ) -> MResult<()> { let main_store = index.main; let synonyms_store = index.synonyms; let stop_words = index.main.stop_words_fst(writer)?.map_data(Cow::into_owned)?; let analyzer = Analyzer::new(AnalyzerConfig::default_with_stopwords(&stop_words)); fn normalize<T: AsRef<[u8]>>(analyzer: &Analyzer<T>, text: &str) -> String { analyzer.analyze(&text) .tokens() .fold(String::new(), |s, t| s + t.text()) } let synonyms: BTreeMap<String, Vec<String>> = synonyms.into_iter().map( |(word, alternatives)| { let word = normalize(&analyzer, &word); let alternatives = alternatives.into_iter().map(|text| normalize(&analyzer, &text)).collect(); (word, alternatives) }).collect(); let mut synonyms_builder = SetBuilder::memory(); synonyms_store.clear(writer)?; for (word, alternatives) in synonyms { synonyms_builder.insert(&word)?; let alternatives = { let alternatives = SetBuf::from_dirty(alternatives); let mut alternatives_builder = SetBuilder::memory(); alternatives_builder.extend_iter(alternatives)?; alternatives_builder.into_set() }; synonyms_store.put_synonyms(writer, word.as_bytes(), &alternatives)?; } let synonyms_set = synonyms_builder.into_set(); main_store.put_synonyms_fst(writer, &synonyms_set)?; Ok(()) }
use std::{borrow::Cow, collections::{BTreeMap, BTreeSet}}; use heed::Result as ZResult; use fst::{SetBuilder, set::OpBuilder}; use sdset::SetBuf; use meilisearch_schema::Schema; use meilisearch_tokenizer::analyzer::{Analyzer, AnalyzerConfig}; use crate::database::{MainT, UpdateT}; use crate::settings::{UpdateState, SettingsUpdate, RankingRule}; use crate::update::documents_addition::reindex_all_documents; use crate::update::{next_update_id, Update}; use crate::{store, MResult, Error}; pub fn push_settings_update( writer: &mut heed::RwTxn<UpdateT>, updates_store: store::Updates, updates_results_store: store::UpdatesResults, settings: SettingsUpdate, ) -> ZResult<u64> { let last_update_id = next_update_id(writer, updates_store, updates_results_store)?; let update = Update::settings(settings); updates_store.put_update(writer, last_update_id, &update)?; Ok(last_update_id) }
fn apply_attributes_for_faceting_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, schema: &mut Schema, attributes: &[String] ) -> MResult<()> { let mut attribute_ids = Vec::new(); for name in attributes { attribute_ids.push(schema.insert(name)?); } let attributes_for_faceting = SetBuf::from_dirty(attribute_ids); index.main.put_attributes_for_faceting(writer, &attributes_for_faceting)?; Ok(()) } pub fn apply_stop_words_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, stop_words: BTreeSet<String>, ) -> MResult<bool> { let mut must_reindex = false; let old_stop_words: BTreeSet<String> = index.main .stop_words_fst(writer)? .stream() .into_strs()? .into_iter() .collect(); let deletion: BTreeSet<String> = old_stop_words.difference(&stop_words).cloned().collect(); let addition: BTreeSet<String> = stop_words.difference(&old_stop_words).cloned().collect(); if !addition.is_empty() { apply_stop_words_addition(writer, index, addition)?; } if !deletion.is_empty() { must_reindex = true; apply_stop_words_deletion(writer, index, deletion)?; } let words_fst = index.main.words_fst(writer)?; if !words_fst.is_empty() { let stop_words = fst::Set::from_iter(stop_words)?; let op = OpBuilder::new() .add(&words_fst) .add(&stop_words) .difference(); let mut builder = fst::SetBuilder::memory(); builder.extend_stream(op)?; let words_fst = builder.into_set(); index.main.put_words_fst(writer, &words_fst)?; index.main.put_stop_words_fst(writer, &stop_words)?; } Ok(must_reindex) } fn apply_stop_words_addition( writer: &mut heed::RwTxn<MainT>, index: &store::Index, addition: BTreeSet<String>, ) -> MResult<()> { let main_store = index.main; let postings_lists_store = index.postings_lists; let mut stop_words_builder = SetBuilder::memory(); for word in addition { stop_words_builder.insert(&word)?; postings_lists_store.del_postings_list(writer, word.as_bytes())?; } let delta_stop_words = stop_words_builder.into_set(); let words_fst = main_store.words_fst(writer)?; if !words_fst.is_empty() { let op = OpBuilder::new() .add(&words_fst) .add(&delta_stop_words) .difference(); let mut word_fst_builder = SetBuilder::memory(); word_fst_builder.extend_stream(op)?; let word_fst = word_fst_builder.into_set(); main_store.put_words_fst(writer, &word_fst)?; } let stop_words_fst = main_store.stop_words_fst(writer)?; let op = OpBuilder::new() .add(&stop_words_fst) .add(&delta_stop_words) .r#union(); let mut stop_words_builder = SetBuilder::memory(); stop_words_builder.extend_stream(op)?; let stop_words_fst = stop_words_builder.into_set(); main_store.put_stop_words_fst(writer, &stop_words_fst)?; Ok(()) } fn apply_stop_words_deletion( writer: &mut heed::RwTxn<MainT>, index: &store::Index, deletion: BTreeSet<String>, ) -> MResult<()> { let mut stop_words_builder = SetBuilder::memory(); for word in deletion { stop_words_builder.insert(&word)?; } let delta_stop_words = stop_words_builder.into_set(); let stop_words_fst = index.main.stop_words_fst(writer)?; let op = OpBuilder::new() .add(&stop_words_fst) .add(&delta_stop_words) .difference(); let mut stop_words_builder = SetBuilder::memory(); stop_words_builder.extend_stream(op)?; let stop_words_fst = stop_words_builder.into_set(); Ok(index.main.put_stop_words_fst(writer, &stop_words_fst)?) } pub fn apply_synonyms_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, synonyms: BTreeMap<String, Vec<String>>, ) -> MResult<()> { let main_store = index.main; let synonyms_store = index.synonyms; let stop_words = index.main.stop_words_fst(writer)?.map_data(Cow::into_owned)?; let analyzer = Analyzer::new(AnalyzerConfig::default_with_stopwords(&stop_words)); fn normalize<T: AsRef<[u8]>>(analyzer: &Analyzer<T>, text: &str) -> String { analyzer.analyze(&text) .tokens() .fold(String::new(), |s, t| s + t.text()) } let synonyms: BTreeMap<String, Vec<String>> = synonyms.into_iter().map( |(word, alternatives)| { let word = normalize(&analyzer, &word); let alternatives = alternatives.into_iter().map(|text| normalize(&analyzer, &text)).collect(); (word, alternatives) }).collect(); let mut synonyms_builder = SetBuilder::memory(); synonyms_store.clear(writer)?; for (word, alternatives) in synonyms { synonyms_builder.insert(&word)?; let alternatives = { let alternatives = SetBuf::from_dirty(alternatives); let mut alternatives_builder = SetBuilder::memory(); alternatives_builder.extend_iter(alternatives)?; alternatives_builder.into_set() }; synonyms_store.put_synonyms(writer, word.as_bytes(), &alternatives)?; } let synonyms_set = synonyms_builder.into_set(); main_store.put_synonyms_fst(writer, &synonyms_set)?; Ok(()) }
pub fn apply_settings_update( writer: &mut heed::RwTxn<MainT>, index: &store::Index, settings: SettingsUpdate, ) -> MResult<()> { let mut must_reindex = false; let mut schema = match index.main.schema(writer)? { Some(schema) => schema, None => { match settings.primary_key.clone() { UpdateState::Update(id) => Schema::with_primary_key(&id), _ => return Err(Error::MissingPrimaryKey) } } }; match settings.ranking_rules { UpdateState::Update(v) => { let ranked_field: Vec<&str> = v.iter().filter_map(RankingRule::field).collect(); schema.update_ranked(&ranked_field)?; index.main.put_ranking_rules(writer, &v)?; must_reindex = true; }, UpdateState::Clear => { index.main.delete_ranking_rules(writer)?; schema.clear_ranked(); must_reindex = true; }, UpdateState::Nothing => (), } match settings.distinct_attribute { UpdateState::Update(v) => { let field_id = schema.insert(&v)?; index.main.put_distinct_attribute(writer, field_id)?; }, UpdateState::Clear => { index.main.delete_distinct_attribute(writer)?; }, UpdateState::Nothing => (), } match settings.searchable_attributes.clone() { UpdateState::Update(v) => { if v.iter().any(|e| e == "*") || v.is_empty() { schema.set_all_searchable(); } else { schema.update_searchable(v)?; } must_reindex = true; }, UpdateState::Clear => { schema.set_all_searchable(); must_reindex = true; }, UpdateState::Nothing => (), } match settings.displayed_attributes.clone() { UpdateState::Update(v) => { if v.contains("*") || v.is_empty() { schema.set_all_displayed(); } else { schema.update_displayed(v)? } }, UpdateState::Clear => { schema.set_all_displayed(); }, UpdateState::Nothing => (), } match settings.attributes_for_faceting { UpdateState::Update(attrs) => { apply_attributes_for_faceting_update(writer, index, &mut schema, &attrs)?; must_reindex = true; }, UpdateState::Clear => { index.main.delete_attributes_for_faceting(writer)?; index.facets.clear(writer)?; }, UpdateState::Nothing => (), } index.main.put_schema(writer, &schema)?; match settings.stop_words { UpdateState::Update(stop_words) => { if apply_stop_words_update(writer, index, stop_words)? { must_reindex = true; } }, UpdateState::Clear => { if apply_stop_words_update(writer, index, BTreeSet::new())? { must_reindex = true; } }, UpdateState::Nothing => (), } match settings.synonyms { UpdateState::Update(synonyms) => apply_synonyms_update(writer, index, synonyms)?, UpdateState::Clear => apply_synonyms_update(writer, index, BTreeMap::new())?, UpdateState::Nothing => (), } if must_reindex { reindex_all_documents(writer, index)?; } Ok(()) }
function_block-full_function
[]
Rust
2020/day-12/src/main.rs
dstoza/advent-2017
22de531632c1633814ed1d2b9827590af989fb6e
#![deny(clippy::all, clippy::pedantic)] use std::{ env, fs::File, io::{BufRead, BufReader}, }; #[derive(Clone, Copy)] enum Direction { North = 0, East = 1, South = 2, West = 3, } impl Direction { fn from_i32(value: i32) -> Self { match value { 0 => Direction::North, 1 => Direction::East, 2 => Direction::South, 3 => Direction::West, _ => panic!("Unexpected value {}", value), } } } enum Rotation { Right, Left, } enum Mode { Ship, Waypoint, } struct Navigator { mode: Mode, x: i32, y: i32, direction: Direction, waypoint_x: i32, waypoint_y: i32, } impl Navigator { fn new(mode: Mode) -> Self { Self { mode, x: 0, y: 0, direction: Direction::East, waypoint_x: 10, waypoint_y: 1, } } fn translate(&mut self, direction: Direction, amount: i32) { let (x, y) = match self.mode { Mode::Ship => (&mut self.x, &mut self.y), Mode::Waypoint => (&mut self.waypoint_x, &mut self.waypoint_y), }; match direction { Direction::North => { *y += amount; } Direction::East => { *x += amount; } Direction::South => { *y -= amount; } Direction::West => { *x -= amount; } }; } fn rotate_waypoint_clockwise(&mut self) { let (x, y) = (self.waypoint_y, -self.waypoint_x); self.waypoint_x = x; self.waypoint_y = y; } fn turn(&mut self, rotation: &Rotation, amount: i32) { let clockwise_amount = match rotation { Rotation::Right => amount, Rotation::Left => 360 - amount, }; let direction = self.direction as i32 + clockwise_amount / 90; for _ in 0..(clockwise_amount / 90) { self.rotate_waypoint_clockwise(); } self.direction = Direction::from_i32(direction % 4); } fn move_forward(&mut self, amount: i32) { match self.mode { Mode::Ship => self.translate(self.direction, amount), Mode::Waypoint => { self.x += self.waypoint_x * amount; self.y += self.waypoint_y * amount; } } } fn parse_line(&mut self, line: &str) { let amount = line[1..].parse().expect("Failed to parse amount as i32"); match line.as_bytes()[0] { b'N' => self.translate(Direction::North, amount), b'E' => self.translate(Direction::East, amount), b'S' => self.translate(Direction::South, amount), b'W' => self.translate(Direction::West, amount), b'L' => self.turn(&Rotation::Left, amount), b'R' => self.turn(&Rotation::Right, amount), b'F' => self.move_forward(amount), _ => panic!("Unexpected prefix {}", line.as_bytes()[0]), } } fn get_distance(&self) -> i32 { self.x.abs() + self.y.abs() } } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 || args.len() > 3 { return; } let mode = match args[2].as_str() { "ship" => Mode::Ship, "waypoint" => Mode::Waypoint, _ => panic!("Unexpected mode {}", args[2].as_str()), }; let filename = &args[1]; let file = File::open(filename).unwrap_or_else(|_| panic!("Failed to open file {}", filename)); let mut reader = BufReader::new(file); let mut navigator = Navigator::new(mode); let mut line = String::new(); loop { let bytes = reader .read_line(&mut line) .unwrap_or_else(|_| panic!("Failed to read line")); if bytes == 0 { break; } navigator.parse_line(line.trim()); line.clear(); } println!("Distance: {}", navigator.get_distance()); }
#![deny(clippy::all, clippy::pedantic)] use std::{ env, fs::File, io::{BufRead, BufReader}, }; #[derive(Clone, Copy)] enum Direction { North = 0, East = 1, South = 2, West = 3, } impl Direction { fn from_i32(value: i32) -> Self { match value { 0 => Direction::North, 1 => Direction::East, 2 => Direction::South, 3 => Direction::West, _ => panic!("Unexpected value {}", value), } } } enum Rotation { Right, Left, } enum Mode { Ship, Waypoint, } struct Navigator { mode: Mode, x: i32, y: i32, direction: Direction, waypoint_x: i32, waypoint_y: i32, } impl Navigator { fn new(mode: Mode) -> Self { Self { mode, x: 0, y: 0, direction: Direction::East, waypoint_x: 10, waypoint_y: 1, } } fn translate(&mut self, direction: Direction, amount: i32) { let (x, y) = match self.mode { Mode::Ship => (&mut self.x, &mut self.y), Mode::Waypoint => (&mut self.waypoint_x, &mut self.waypoint_y), }; match direction { Direction::North => { *y += amount; } Direction::East => { *x += amount; } Direction::South => { *y -= amount; } Direction::West => { *x -= amount; } }; } fn rotate_waypoint_clockwise(&mut self) { let (x, y) = (self.waypoint_y, -self.waypoint_x); self.waypoint_x = x; self.waypoint_y = y; }
fn move_forward(&mut self, amount: i32) { match self.mode { Mode::Ship => self.translate(self.direction, amount), Mode::Waypoint => { self.x += self.waypoint_x * amount; self.y += self.waypoint_y * amount; } } } fn parse_line(&mut self, line: &str) { let amount = line[1..].parse().expect("Failed to parse amount as i32"); match line.as_bytes()[0] { b'N' => self.translate(Direction::North, amount), b'E' => self.translate(Direction::East, amount), b'S' => self.translate(Direction::South, amount), b'W' => self.translate(Direction::West, amount), b'L' => self.turn(&Rotation::Left, amount), b'R' => self.turn(&Rotation::Right, amount), b'F' => self.move_forward(amount), _ => panic!("Unexpected prefix {}", line.as_bytes()[0]), } } fn get_distance(&self) -> i32 { self.x.abs() + self.y.abs() } } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 || args.len() > 3 { return; } let mode = match args[2].as_str() { "ship" => Mode::Ship, "waypoint" => Mode::Waypoint, _ => panic!("Unexpected mode {}", args[2].as_str()), }; let filename = &args[1]; let file = File::open(filename).unwrap_or_else(|_| panic!("Failed to open file {}", filename)); let mut reader = BufReader::new(file); let mut navigator = Navigator::new(mode); let mut line = String::new(); loop { let bytes = reader .read_line(&mut line) .unwrap_or_else(|_| panic!("Failed to read line")); if bytes == 0 { break; } navigator.parse_line(line.trim()); line.clear(); } println!("Distance: {}", navigator.get_distance()); }
fn turn(&mut self, rotation: &Rotation, amount: i32) { let clockwise_amount = match rotation { Rotation::Right => amount, Rotation::Left => 360 - amount, }; let direction = self.direction as i32 + clockwise_amount / 90; for _ in 0..(clockwise_amount / 90) { self.rotate_waypoint_clockwise(); } self.direction = Direction::from_i32(direction % 4); }
function_block-full_function
[ { "content": "fn roll_die(die: &mut i32) -> i32 {\n\n let roll = *die;\n\n *die = (*die % 100) + 1;\n\n roll\n\n}\n\n\n", "file_path": "2021/day-21/src/main.rs", "rank": 0, "score": 192315.6612448546 }, { "content": "fn get_triangle_value(value: i32) -> i32 {\n\n (value * (value ...
Rust
src/statemachine/mac.rs
nathanwhit/tarpaulin
42dd578e753e4b380d27545704b49239f9f6ea30
#![allow(unused)] #![allow(non_snake_case)] use crate::config::Config; use crate::errors::RunError; use crate::statemachine::*; use log::{debug, trace}; use nix::errno::Errno; use nix::sys::signal::Signal; use nix::sys::wait::*; use nix::unistd::Pid; use nix::Error as NixErr; use std::collections::{HashMap, HashSet}; pub fn create_state_machine<'a>( test: Pid, traces: &'a mut TraceMap, config: &'a Config, ) -> (TestState, MacData<'a>) { let mut data = MacData::new(traces, config); data.parent = test; (TestState::start_state(), data) } pub type UpdateContext = (TestState, TracerAction<ProcessInfo>); #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct ProcessInfo { pid: Pid, signal: Option<Signal>, } impl ProcessInfo { fn new(pid: Pid, signal: Option<Signal>) -> Self { Self { pid, signal } } } impl From<Pid> for ProcessInfo { fn from(pid: Pid) -> Self { ProcessInfo::new(pid, None) } } impl From<&Pid> for ProcessInfo { fn from(pid: &Pid) -> Self { ProcessInfo::new(*pid, None) } } pub struct MacData<'a> { wait_queue: Vec<WaitStatus>, current: Pid, parent: Pid, breakpoints: HashMap<u64, Breakpoint>, traces: &'a mut TraceMap, config: &'a Config, thread_count: isize, } impl<'a> StateData for MacData<'a> { fn start(&mut self) -> Result<Option<TestState>, RunError> { match waitpid(self.current, Some(WaitPidFlag::WNOHANG | WaitPidFlag::WUNTRACED)) { Ok(WaitStatus::StillAlive) => Ok(None), Ok(sig @ WaitStatus::Stopped(_, Signal::SIGTRAP)) => { if let WaitStatus::Stopped(child, _) = sig { self.current = child; } trace!("Caught inferior transitioning to Initialise state"); Ok(Some(TestState::Initialise)) } Ok(_) => Err(RunError::TestRuntime( "Unexpected signal when starting test".to_string(), )), Err(e) => Err(RunError::TestRuntime(format!( "Error when starting test: {}", e ))), } } fn init(&mut self) -> Result<TestState, RunError> { trace_children(self.current)?; for trace in self.traces.all_traces() { if let Some(addr) = trace.address { match Breakpoint::new(self.current, addr) { Ok(bp) => { let _ = self.breakpoints.insert(addr, bp); } Err(e) if e == NixErr::Sys(Errno::EIO) => { return Err(RunError::TestRuntime( "ERROR: Tarpaulin cannot find code addresses \ check that pie is disabled for your linker. \ If linking with gcc try adding -C link-args=-no-pie \ to your rust flags" .to_string(), )); } Err(NixErr::UnsupportedOperation) => { debug!("Instrumentation address clash, ignoring 0x{:x}", addr); } Err(_) => { return Err(RunError::TestRuntime( "Failed to instrument test executable".to_string(), )); } } } } if continue_exec(self.parent, None).is_ok() { trace!("Initialised inferior, transitioning to wait state"); Ok(TestState::wait_state()) } else { Err(RunError::TestRuntime( "Test didn't launch correctly".to_string(), )) } } fn wait(&mut self) -> Result<Option<TestState>, RunError> { let mut result = Ok(None); let mut running = true; while running { let wait = waitpid( Pid::from_raw(-1), Some(WaitPidFlag::WNOHANG), ); match wait { Ok(WaitStatus::StillAlive) => { running = false; } Ok(WaitStatus::Exited(_, _)) => { self.wait_queue.push(wait.unwrap()); result = Ok(Some(TestState::Stopped)); running = false; } Ok(s) => { self.wait_queue.push(s); result = Ok(Some(TestState::Stopped)); } Err(e) => { running = false; result = Err(RunError::TestRuntime(format!( "An error occurred while waiting for response from test: {}", e ))) } } } if !self.wait_queue.is_empty() { trace!("Result queue is {:?}", self.wait_queue); } result } fn stop(&mut self) -> Result<TestState, RunError> { let mut actions = Vec::new(); let mut pcs = HashSet::new(); let mut result = Ok(TestState::wait_state()); let pending = self.wait_queue.clone(); self.wait_queue.clear(); for status in &pending { let state = match status { WaitStatus::Stopped(c, Signal::SIGTRAP) => { self.current = *c; match self.collect_coverage_data(&mut pcs) { Ok(s) => Ok(s), Err(e) => Err(RunError::TestRuntime(format!( "Error when collecting coverage: {}", e ))), } } WaitStatus::Stopped(child, Signal::SIGSTOP) => Ok(( TestState::wait_state(), TracerAction::Continue(child.into()), )), WaitStatus::Stopped(_, Signal::SIGSEGV) => Err(RunError::TestRuntime( "A segfault occurred while executing tests".to_string(), )), WaitStatus::Stopped(child, Signal::SIGILL) => { let pc = current_instruction_pointer(*child).unwrap_or_else(|_| 1) - 1; trace!("SIGILL raised. Child program counter is: 0x{:x}", pc); Err(RunError::TestRuntime(format!( "Error running test - SIGILL raised in {}", child ))) } WaitStatus::Stopped(c, s) => { let sig = if self.config.forward_signals { Some(*s) } else { None }; let info = ProcessInfo::new(*c, sig); Ok((TestState::wait_state(), TracerAction::TryContinue(info))) } WaitStatus::Signaled(c, s, f) => { if let Ok(s) = self.handle_signaled(c, s, *f) { Ok(s) } else { Err(RunError::TestRuntime( "Attempting to handle tarpaulin being signaled".to_string(), )) } } WaitStatus::Exited(child, ec) => { for ref mut value in self.breakpoints.values_mut() { value.thread_killed(*child); } trace!("Exited {:?} parent {:?}", child, self.parent); if child == &self.parent { Ok((TestState::End(*ec), TracerAction::Nothing)) } else { Ok(( TestState::wait_state(), TracerAction::TryContinue(self.parent.into()), )) } } _ => Err(RunError::TestRuntime( "An unexpected signal has been caught by tarpaulin!".to_string(), )), }; match state { Ok((TestState::Waiting { .. }, action)) => { actions.push(action); } Ok((state, action)) => { result = Ok(state); actions.push(action); } Err(e) => result = Err(e), } } let mut continued = false; for a in &actions { match a { TracerAction::TryContinue(t) => { continued = true; let _ = continue_exec(t.pid, t.signal); } TracerAction::Continue(t) => { continued = true; continue_exec(t.pid, t.signal)?; } TracerAction::Step(t) => { continued = true; single_step(t.pid)?; } TracerAction::Detach(t) => { continued = true; detach_child(t.pid)?; } _ => {} } } if !continued { trace!("No action suggested to continue tracee. Attempting a continue"); let _ = continue_exec(self.parent, None); } result } } impl<'a> MacData<'a> { pub fn new(traces: &'a mut TraceMap, config: &'a Config) -> MacData<'a> { MacData { wait_queue: Vec::new(), current: Pid::from_raw(0), parent: Pid::from_raw(0), breakpoints: HashMap::new(), traces, config, thread_count: 0, } } fn handle_ptrace_event( &mut self, child: Pid, sig: Signal, event: i32, ) -> Result<(TestState, TracerAction<ProcessInfo>), RunError> { use nix::libc::*; if sig == Signal::SIGTRAP { match event { PTRACE_EVENT_CLONE => match get_event_data(child) { Ok(t) => { trace!("New thread spawned {}", t); self.thread_count += 1; Ok(( TestState::wait_state(), TracerAction::Continue(child.into()), )) } Err(e) => { trace!("Error in clone event {:?}", e); Err(RunError::TestRuntime( "Error occurred upon test executable thread creation".to_string(), )) } }, PTRACE_EVENT_FORK => { trace!("Caught fork event"); Ok(( TestState::wait_state(), TracerAction::Continue(child.into()), )) } PTRACE_EVENT_EXEC => { trace!("Child execed other process - detaching ptrace"); Ok((TestState::wait_state(), TracerAction::Detach(child.into()))) } PTRACE_EVENT_EXIT => { trace!("Child exiting"); self.thread_count -= 1; Ok(( TestState::wait_state(), TracerAction::TryContinue(child.into()), )) } _ => Err(RunError::TestRuntime(format!( "Unrecognised ptrace event {}", event ))), } } else { trace!("Unexpected signal with ptrace event {}", event); trace!("Signal: {:?}", sig); Err(RunError::TestRuntime("Unexpected signal".to_string())) } } fn collect_coverage_data( &mut self, visited_pcs: &mut HashSet<u64>, ) -> Result<UpdateContext, RunError> { let mut action = None; if let Ok(rip) = current_instruction_pointer(self.current) { let rip = (rip - 1) as u64; trace!("Hit address 0x{:x}", rip); if self.breakpoints.contains_key(&rip) { let bp = &mut self.breakpoints.get_mut(&rip).unwrap(); let updated = if visited_pcs.contains(&rip) { let _ = bp.jump_to(self.current); (true, TracerAction::Continue(self.current.into())) } else { let enable = self.config.count; if let Ok(x) = bp.process(self.current, enable) { x } else { (false, TracerAction::Continue(self.current.into())) } }; if updated.0 { if let Some(ref mut t) = self.traces.get_trace_mut(rip) { if let CoverageStat::Line(ref mut x) = t.stats { trace!("Incrementing hit count for trace"); *x += 1; } } } action = Some(updated.1); } } let action = action.unwrap_or_else(|| TracerAction::Continue(self.current.into())); Ok((TestState::wait_state(), action)) } fn handle_signaled( &mut self, pid: &Pid, sig: &Signal, flag: bool, ) -> Result<UpdateContext, RunError> { match (sig, flag) { (Signal::SIGTRAP, true) => { Ok((TestState::wait_state(), TracerAction::Continue(pid.into()))) } _ => Err(RunError::StateMachine("Unexpected stop".to_string())), } } }
#![allow(unused)] #![allow(non_snake_case)] use crate::config::Config; use crate::errors::RunError; use crate::statemachine::*; use log::{debug, trace}; use nix::errno::Errno; use nix::sys::signal::Signal; use nix::sys::wait::*; use nix::unistd::Pid; use nix::Error as NixErr; use std::collections::{HashMap, HashSet}; pub fn create_state_machine<'a>( test: Pid, traces: &'a mut TraceMap, config: &'a Config, ) -> (TestState, MacData<'a>) { let mut data = MacData::new(traces, config); data.parent = test; (TestState::start_state(), data) } pub type UpdateContext = (TestState, TracerAction<ProcessInfo>); #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct ProcessInfo { pid: Pid, signal: Option<Signal>, } impl ProcessInfo { fn new(pid: Pid, signal: Option<Signal>) -> Self { Self { pid, signal } } } impl From<Pid> for ProcessInfo { fn from(pid: Pid) -> Self { ProcessInfo::new(pid, None) } } impl From<&Pid> for ProcessInfo { fn from(pid: &Pid) -> Self { ProcessInfo::new(*pid, None) } } pub struct MacData<'a> { wait_queue: Vec<WaitStatus>, current: Pid, parent: Pid, breakpoints: HashMap<u64, Breakpoint>, traces: &'a mut TraceMap, config: &'a Config, thread_count: isize, } impl<'a> StateData for MacData<'a> { fn start(&mut self) -> Result<Option<TestState>, RunError> { match waitpid(self.current, Some(WaitPidFlag::WNOHANG | WaitPidFlag::WUNTRACED)) { Ok(WaitStatus::StillAlive) => Ok(None), Ok(sig @ WaitStatus::Stopped(_, Signal::SIGTRAP)) => { if let WaitStatus::Stopped(child, _) = sig { self.current = child; } trace!("Caught inferior transitioning to Initialise state"); Ok(Some(TestState::Initialise)) } Ok(_) => Err(RunError::TestRuntime( "Unexpected signal when starting test".to_string(), )), Err(e) => Err(RunError::TestRuntime(format!( "Error when starting test: {}", e ))), } } fn init(&mut self) -> Result<TestState, RunError> { trace_children(self.current)?; for trace in self.traces.all_traces() { if let Some(addr) = trace.address { match Breakpoint::new(self.current, addr) { Ok(bp) => { let _ = self.breakpoints.insert(addr, bp); } Err(e) if e == NixErr::Sys(Errno::EIO) => { return Err(RunError::TestRuntime( "ERROR: Tarpaulin cannot find code addresses \ check that pie is disabled for your linker. \ If linking with gcc try adding -C link-args=-no-pie \ to your rust flags" .to_string(), )); } Err(NixErr::UnsupportedOperation) => { debug!("Instrumentation address clash, ignoring 0x{:x}", addr); } Err(_) => { return Err(RunError::TestRuntime( "Failed to instrument test executable".to_string(), )); } } } } if continue_exec(self.parent, None).is_ok() { trace!("Initialised inferior, transitioning to wait state"); Ok(TestState::wait_state()) } else { Err(RunError::TestRuntime( "Test didn't launch correctly".to_string(), )) } } fn wait(&mut self) -> Result<Option<TestState>, RunError> { let mut result = Ok(None); let mut running = true; while running { let wait = waitpid( Pid::from_raw(-1), Some(WaitPidFlag::WNOHANG), ); match wait { Ok(WaitStatus::StillAlive) => { running = false; } Ok(WaitStatus::Exited(_, _)) => { self.wait_queue.push(wait.unwrap()); result = Ok(Some(TestState::Stopped)); running = false; } Ok(s) => { self.wait_queue.push(s); result = Ok(Some(TestState::Stopped)); } Err(e) => { running = false; result = Err(RunError::TestRuntime(format!( "An error occurred while waiting for response from test: {}", e ))) } } } if !self.wait_queue.is_empty() { trace!("Result queue is {:?}", self.wait_queue); } result }
} impl<'a> MacData<'a> { pub fn new(traces: &'a mut TraceMap, config: &'a Config) -> MacData<'a> { MacData { wait_queue: Vec::new(), current: Pid::from_raw(0), parent: Pid::from_raw(0), breakpoints: HashMap::new(), traces, config, thread_count: 0, } } fn handle_ptrace_event( &mut self, child: Pid, sig: Signal, event: i32, ) -> Result<(TestState, TracerAction<ProcessInfo>), RunError> { use nix::libc::*; if sig == Signal::SIGTRAP { match event { PTRACE_EVENT_CLONE => match get_event_data(child) { Ok(t) => { trace!("New thread spawned {}", t); self.thread_count += 1; Ok(( TestState::wait_state(), TracerAction::Continue(child.into()), )) } Err(e) => { trace!("Error in clone event {:?}", e); Err(RunError::TestRuntime( "Error occurred upon test executable thread creation".to_string(), )) } }, PTRACE_EVENT_FORK => { trace!("Caught fork event"); Ok(( TestState::wait_state(), TracerAction::Continue(child.into()), )) } PTRACE_EVENT_EXEC => { trace!("Child execed other process - detaching ptrace"); Ok((TestState::wait_state(), TracerAction::Detach(child.into()))) } PTRACE_EVENT_EXIT => { trace!("Child exiting"); self.thread_count -= 1; Ok(( TestState::wait_state(), TracerAction::TryContinue(child.into()), )) } _ => Err(RunError::TestRuntime(format!( "Unrecognised ptrace event {}", event ))), } } else { trace!("Unexpected signal with ptrace event {}", event); trace!("Signal: {:?}", sig); Err(RunError::TestRuntime("Unexpected signal".to_string())) } } fn collect_coverage_data( &mut self, visited_pcs: &mut HashSet<u64>, ) -> Result<UpdateContext, RunError> { let mut action = None; if let Ok(rip) = current_instruction_pointer(self.current) { let rip = (rip - 1) as u64; trace!("Hit address 0x{:x}", rip); if self.breakpoints.contains_key(&rip) { let bp = &mut self.breakpoints.get_mut(&rip).unwrap(); let updated = if visited_pcs.contains(&rip) { let _ = bp.jump_to(self.current); (true, TracerAction::Continue(self.current.into())) } else { let enable = self.config.count; if let Ok(x) = bp.process(self.current, enable) { x } else { (false, TracerAction::Continue(self.current.into())) } }; if updated.0 { if let Some(ref mut t) = self.traces.get_trace_mut(rip) { if let CoverageStat::Line(ref mut x) = t.stats { trace!("Incrementing hit count for trace"); *x += 1; } } } action = Some(updated.1); } } let action = action.unwrap_or_else(|| TracerAction::Continue(self.current.into())); Ok((TestState::wait_state(), action)) } fn handle_signaled( &mut self, pid: &Pid, sig: &Signal, flag: bool, ) -> Result<UpdateContext, RunError> { match (sig, flag) { (Signal::SIGTRAP, true) => { Ok((TestState::wait_state(), TracerAction::Continue(pid.into()))) } _ => Err(RunError::StateMachine("Unexpected stop".to_string())), } } }
fn stop(&mut self) -> Result<TestState, RunError> { let mut actions = Vec::new(); let mut pcs = HashSet::new(); let mut result = Ok(TestState::wait_state()); let pending = self.wait_queue.clone(); self.wait_queue.clear(); for status in &pending { let state = match status { WaitStatus::Stopped(c, Signal::SIGTRAP) => { self.current = *c; match self.collect_coverage_data(&mut pcs) { Ok(s) => Ok(s), Err(e) => Err(RunError::TestRuntime(format!( "Error when collecting coverage: {}", e ))), } } WaitStatus::Stopped(child, Signal::SIGSTOP) => Ok(( TestState::wait_state(), TracerAction::Continue(child.into()), )), WaitStatus::Stopped(_, Signal::SIGSEGV) => Err(RunError::TestRuntime( "A segfault occurred while executing tests".to_string(), )), WaitStatus::Stopped(child, Signal::SIGILL) => { let pc = current_instruction_pointer(*child).unwrap_or_else(|_| 1) - 1; trace!("SIGILL raised. Child program counter is: 0x{:x}", pc); Err(RunError::TestRuntime(format!( "Error running test - SIGILL raised in {}", child ))) } WaitStatus::Stopped(c, s) => { let sig = if self.config.forward_signals { Some(*s) } else { None }; let info = ProcessInfo::new(*c, sig); Ok((TestState::wait_state(), TracerAction::TryContinue(info))) } WaitStatus::Signaled(c, s, f) => { if let Ok(s) = self.handle_signaled(c, s, *f) { Ok(s) } else { Err(RunError::TestRuntime( "Attempting to handle tarpaulin being signaled".to_string(), )) } } WaitStatus::Exited(child, ec) => { for ref mut value in self.breakpoints.values_mut() { value.thread_killed(*child); } trace!("Exited {:?} parent {:?}", child, self.parent); if child == &self.parent { Ok((TestState::End(*ec), TracerAction::Nothing)) } else { Ok(( TestState::wait_state(), TracerAction::TryContinue(self.parent.into()), )) } } _ => Err(RunError::TestRuntime( "An unexpected signal has been caught by tarpaulin!".to_string(), )), }; match state { Ok((TestState::Waiting { .. }, action)) => { actions.push(action); } Ok((state, action)) => { result = Ok(state); actions.push(action); } Err(e) => result = Err(e), } } let mut continued = false; for a in &actions { match a { TracerAction::TryContinue(t) => { continued = true; let _ = continue_exec(t.pid, t.signal); } TracerAction::Continue(t) => { continued = true; continue_exec(t.pid, t.signal)?; } TracerAction::Step(t) => { continued = true; single_step(t.pid)?; } TracerAction::Detach(t) => { continued = true; detach_child(t.pid)?; } _ => {} } } if !continued { trace!("No action suggested to continue tracee. Attempting a continue"); let _ = continue_exec(self.parent, None); } result }
function_block-full_function
[ { "content": "/// Launches tarpaulin with the given configuration.\n\npub fn launch_tarpaulin(config: &Config) -> Result<(TraceMap, i32), RunError> {\n\n setup_environment(&config);\n\n cargo::core::enable_nightly_features();\n\n let cwd = match config.manifest.parent() {\n\n Some(p) => p.to_pat...
Rust
tests/read_write_pdbs.rs
douweschulte/pdbtbx
4495b3af56d88b72f27e5d9f17848bcbdec34381
use pdbtbx::*; use std::path::Path; use std::time::Instant; use std::{env, fs}; #[test] fn run_pdbs() { let current_dir = env::current_dir().unwrap(); let pdb_dir = current_dir.as_path().join(Path::new("example-pdbs")); let dump_dir = current_dir .as_path() .join(Path::new("dump")) .into_os_string() .into_string() .unwrap() + &String::from(std::path::MAIN_SEPARATOR); let _ = fs::create_dir(dump_dir.clone()); println!("{:?}", pdb_dir); save_invalid_name(); save_pdb_strict(); save_mmcif_strict(); for entry in fs::read_dir(pdb_dir).unwrap() { let entry = entry.unwrap(); let path = entry.path(); let metadata = fs::metadata(&path).unwrap(); if metadata.is_file() { do_something( &path.clone().into_os_string().into_string().unwrap(), &dump_dir, &path .file_stem() .unwrap() .to_os_string() .into_string() .unwrap(), ); } } } fn do_something(file: &str, folder: &str, name: &str) { println!("Working on file: {}", file); let now = Instant::now(); let (pdb, errors) = open(file, StrictnessLevel::Loose).unwrap(); let time = now.elapsed(); for error in errors { println!("{}", error); } println!( "Found {} atoms, in {} residues, in {} chains, in {} models it all took {} ms", pdb.total_atom_count(), pdb.total_residue_count(), pdb.total_chain_count(), pdb.model_count(), time.as_millis() ); assert!(pdb.total_atom_count() != 0, "No atoms found"); println!("PDB parsed"); let mut avg = 0.0; let mut total_back = 0; let mut avg_back = 0.0; let mut total_side = 0; let mut avg_side = 0.0; println!("Set values"); for hierarchy in pdb.atoms_with_hierarchy() { avg += hierarchy.atom().b_factor(); if hierarchy.is_backbone() { total_back += 1; avg_back += hierarchy.atom().b_factor(); } else { total_side += 1; avg_side += hierarchy.atom().b_factor(); } } println!("Counted for averages"); avg /= (total_back + total_side) as f64; avg_back /= total_back as f64; avg_side /= total_side as f64; println!("Found averages"); println!( "Average B factor: Total: {:.3}, Backbone: {:.3}, Sidechains: {:.3}", avg, avg_back, avg_side ); if validate_pdb(&pdb) .iter() .all(|a| !a.fails(StrictnessLevel::Medium)) { save( &pdb, &(folder.to_string() + name + ".pdb"), StrictnessLevel::Loose, ) .expect("PDB resave not successful"); let (_saved_pdb, _) = open( &(folder.to_string() + name + ".pdb"), StrictnessLevel::Loose, ) .expect("PDB reparse not successful"); } save( &pdb, &(folder.to_string() + name + ".cif"), StrictnessLevel::Loose, ) .expect("mmCIF resave not successful"); let (_saved_mmcif, _) = open( &(folder.to_string() + name + ".cif"), StrictnessLevel::Loose, ) .expect("mmCIF reparse not successful"); } fn save_invalid_name() { let name = env::current_dir() .unwrap() .as_path() .join(Path::new("dump")) .join(Path::new("save_test.name")) .into_os_string() .into_string() .unwrap(); let res = save(&PDB::new(), &name, StrictnessLevel::Loose); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.len(), 1); assert_eq!(err[0].short_description(), "Incorrect extension") } fn save_pdb_strict() { let name = env::current_dir() .unwrap() .as_path() .join(Path::new("dump")) .join(Path::new("save_test.pdb")) .into_os_string() .into_string() .unwrap(); let atom = Atom::new(false, 0, "H", 0.0, 0.0, 0.0, 0.0, 0.0, "H", 0).unwrap(); let mut model = Model::new(0); model.add_atom(atom, "A", (0, None), ("LYS", None)); let mut pdb = PDB::new(); pdb.add_model(model); let res = save(&pdb, &name, StrictnessLevel::Strict); assert!(res.is_ok()); let (_pdb, errors) = crate::open(&name, StrictnessLevel::Strict).unwrap(); assert_eq!(errors.len(), 0); } fn save_mmcif_strict() { let name = env::current_dir() .unwrap() .as_path() .join(Path::new("dump")) .join(Path::new("save_test.cif")) .into_os_string() .into_string() .unwrap(); let atom = Atom::new(false, 0, "H", 0.0, 0.0, 0.0, 0.0, 0.0, "H", 0).unwrap(); let mut model = Model::new(0); model.add_atom(atom, "A", (0, None), ("LYS", None)); let mut pdb = PDB::new(); pdb.add_model(model); let res = save(&pdb, &name, StrictnessLevel::Strict); println!("{:?}", res); assert!(res.is_ok()); let (_pdb, errors) = crate::open(&name, StrictnessLevel::Strict).unwrap(); assert_eq!(errors.len(), 0); }
use pdbtbx::*; use std::path::Path; use std::time::Instant; use std::{env, fs}; #[test] fn run_pdbs() { let current_dir = env::current_dir().unwrap(); let pdb_dir = current_dir.as_path().join(Path::new("example-pdbs")); let dump_dir = current_dir .as_path() .join(Path::new("dump")) .into_os_string() .into_string() .unwrap() + &String::from(std::path::MAIN_SEPARATOR); let _ = fs::create_dir(dump_dir.clone()); println!("{:?}", pdb_dir); save_invalid_name(); save_pdb_strict(); save_mmcif_strict(); for entry in fs::read_dir(pdb_dir).unwrap() { let entry = entry.unwrap(); let path = entry.path(); let metadata = fs::metadata(&path).unwrap(); if metadata.is_file() { do_something( &path.clone().into_os_string().into_string().unwrap(), &dump_dir, &path .file_stem() .unwrap() .to_os_string() .into_string() .unwrap(), ); } } } fn do_something(file: &str, folder: &str, name: &str) { println!("Working on file: {}", file); let now = Instant::now(); let (pdb, errors) = open(file, StrictnessLevel::Loose).unwrap(); let time = now.elapsed(); for error in errors { println!("{}", error); } println!( "Found {} atoms, in {} residues, in {} chains, in {} models it all took {} ms", pdb.total_atom_count(), pdb.total_residue_count(), pdb.total_chain_count(), pdb.model_count(), time.as_millis() ); assert!(pdb.total_atom_count() != 0, "No atoms found"); println!("PDB parsed"); let mut avg = 0.0; let mut total_back = 0; let mut avg_back = 0.0; let mut total_side = 0; let mut avg_side = 0.0; println!("Set values"); for hierarchy in pdb.atoms_with_hierarchy() { avg += hierarchy.atom().b_factor(); if hierarchy.is_backbone() { total_back += 1; avg_back += hierarchy.atom().b_factor(); } else { total_side += 1; avg_side += hierarchy.atom().b_factor(); } } println!("Counted for averages"); avg /= (total_back + total_side) as f64; avg_back /= total_back as f64; avg_side /= total_side as f64; println!("Found averages"); println!( "Average B factor: Total: {:.3}, Backbone: {:.3}, Sidechains: {:.3}", avg, avg_back, avg_side ); if validate_pdb(&pdb) .iter() .all(|a| !a.fails(StrictnessLevel::Medium)) { save( &pdb, &(folder.to_string() + name + ".pdb"), StrictnessLevel::Loose, ) .expect("PDB resave not successful"); let (_saved_pdb, _) = open( &(folder.to_string() + name + ".pdb"), StrictnessLevel::Loose, ) .expect("PDB reparse not successful"); } save( &pdb, &(folder.to_string() + name + ".cif"), StrictnessLevel::Loose, ) .expect("mmCIF resave not successful"); let (_saved_mmcif, _) = open( &(folder.to_string() + name + ".cif"), StrictnessLevel::Loose, ) .expect("mmCIF reparse not successful"); } fn save_invalid_name() { let name = env::current_dir() .unwrap() .as_path() .join(Path::new("dump")) .join(Path::new("save_test.name")) .into_os_string() .into_string() .unwrap(); let res = save(&PDB::new(), &name, StrictnessLevel::Loose); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.len(), 1); assert_eq!(err[0].short_description(), "Incorrect extension") } fn save_pdb_strict() { let name = env::current_dir() .unwrap() .as_path() .join(Path::new("dump")) .join(Path::new("save_test.pdb")) .into_os_string() .into_string() .unwrap(); let atom = Atom::new(false, 0, "H", 0.0, 0.0, 0.0, 0.0, 0.0, "H", 0).unwrap(); let mut model = Model::new(0); model.add_atom(atom, "A", (0, None), ("LYS", None)); let mut pdb = PDB::new(); pdb.add_model(model); let res = save(&pdb, &name, StrictnessLevel::Strict); assert!(res.is_ok()); let (_pdb, errors) = crate::open(&name, StrictnessLevel::Strict).unwrap(); assert_eq!(errors.len(), 0); } fn save_mmcif_strict() { let name = env::current_dir() .unwrap() .
as_path() .join(Path::new("dump")) .join(Path::new("save_test.cif")) .into_os_string() .into_string() .unwrap(); let atom = Atom::new(false, 0, "H", 0.0, 0.0, 0.0, 0.0, 0.0, "H", 0).unwrap(); let mut model = Model::new(0); model.add_atom(atom, "A", (0, None), ("LYS", None)); let mut pdb = PDB::new(); pdb.add_model(model); let res = save(&pdb, &name, StrictnessLevel::Strict); println!("{:?}", res); assert!(res.is_ok()); let (_pdb, errors) = crate::open(&name, StrictnessLevel::Strict).unwrap(); assert_eq!(errors.len(), 0); }
function_block-function_prefix_line
[ { "content": "/// Parse a loop containing atomic data\n\nfn parse_atoms(input: &Loop, pdb: &mut PDB) -> Option<Vec<PDBError>> {\n\n /// These are the columns needed to fill out the PDB correctly\n\n const COLUMNS: &[&str] = &[\n\n \"atom_site.group_PDB\",\n\n \"atom_site.label_atom_id\",\n\n...
Rust
lib/llvm-backend/src/platform/unix.rs
spacemeshos/wasmer
31365510edd73878916e1aba2dd79f415b8c6891
use super::common::round_up_to_page_size; use crate::structs::{LLVMResult, MemProtect}; use libc::{ c_void, mmap, mprotect, munmap, siginfo_t, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_READ, PROT_WRITE, }; use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, SIGBUS, SIGSEGV}; use std::ptr; #[allow(clippy::cast_ptr_alignment)] #[cfg(target_os = "macos")] pub unsafe fn visit_fde(addr: *mut u8, size: usize, visitor: extern "C" fn(*mut u8)) { unsafe fn process_fde(entry: *mut u8, visitor: extern "C" fn(*mut u8)) -> *mut u8 { let mut p = entry; let length = (p as *const u32).read_unaligned(); p = p.add(4); let offset = (p as *const u32).read_unaligned(); if offset != 0 { visitor(entry); } p.add(length as usize) } let mut p = addr; let end = p.add(size); loop { if p >= end { break; } p = process_fde(p, visitor); } } #[cfg(not(target_os = "macos"))] pub unsafe fn visit_fde(addr: *mut u8, _size: usize, visitor: extern "C" fn(*mut u8)) { visitor(addr); } extern "C" { #[cfg_attr(nightly, unwind(allowed))] fn throw_trap(ty: i32) -> !; } pub unsafe fn install_signal_handler() { let sa = SigAction::new( SigHandler::SigAction(signal_trap_handler), SaFlags::SA_ONSTACK | SaFlags::SA_SIGINFO, SigSet::empty(), ); sigaction(SIGSEGV, &sa).unwrap(); sigaction(SIGBUS, &sa).unwrap(); } #[cfg_attr(nightly, unwind(allowed))] extern "C" fn signal_trap_handler( _signum: ::nix::libc::c_int, _siginfo: *mut siginfo_t, _ucontext: *mut c_void, ) { unsafe { throw_trap(2); } } pub unsafe fn alloc_memory( size: usize, protect: MemProtect, ptr_out: &mut *mut u8, size_out: &mut usize, ) -> LLVMResult { let size = round_up_to_page_size(size); let ptr = mmap( ptr::null_mut(), size, match protect { MemProtect::NONE => PROT_NONE, MemProtect::READ => PROT_READ, MemProtect::READ_WRITE => PROT_READ | PROT_WRITE, MemProtect::READ_EXECUTE => PROT_READ | PROT_EXEC, }, MAP_PRIVATE | MAP_ANON, -1, 0, ); if ptr as isize == -1 { return LLVMResult::ALLOCATE_FAILURE; } *ptr_out = ptr as _; *size_out = size; LLVMResult::OK } pub unsafe fn protect_memory(ptr: *mut u8, size: usize, protect: MemProtect) -> LLVMResult { let res = mprotect( ptr as _, round_up_to_page_size(size), match protect { MemProtect::NONE => PROT_NONE, MemProtect::READ => PROT_READ, MemProtect::READ_WRITE => PROT_READ | PROT_WRITE, MemProtect::READ_EXECUTE => PROT_READ | PROT_EXEC, }, ); if res == 0 { LLVMResult::OK } else { LLVMResult::PROTECT_FAILURE } } pub unsafe fn dealloc_memory(ptr: *mut u8, size: usize) -> LLVMResult { let res = munmap(ptr as _, round_up_to_page_size(size)); if res == 0 { LLVMResult::OK } else { LLVMResult::DEALLOC_FAILURE } }
use super::common::round_up_to_page_size; use crate::structs::{LLVMResult, MemProtect}; use libc::{ c_void, mmap, mprotect, munmap, siginfo_t, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_READ, PROT_WRITE, }; use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, SIGBUS, SIGSEGV}; use std::ptr; #[allow(clippy::cast_ptr_alignment)] #[cfg(target_os = "macos")] pub unsafe fn visit_fde(addr: *mut u8, size: usize, visitor: extern "C" fn(*mut u8)) { unsafe fn process_fde(entry: *mut u8, visitor: extern "C" fn(*mut u8)) -> *mut u8 { let mut p = entry; let length = (p as *const u32).read_unaligned(); p = p.add(4); let offset = (p as *const u32).read_unaligned(); if offset != 0 { visitor(entry); } p.add(length as usize) } let
res == 0 { LLVMResult::OK } else { LLVMResult::PROTECT_FAILURE } } pub unsafe fn dealloc_memory(ptr: *mut u8, size: usize) -> LLVMResult { let res = munmap(ptr as _, round_up_to_page_size(size)); if res == 0 { LLVMResult::OK } else { LLVMResult::DEALLOC_FAILURE } }
mut p = addr; let end = p.add(size); loop { if p >= end { break; } p = process_fde(p, visitor); } } #[cfg(not(target_os = "macos"))] pub unsafe fn visit_fde(addr: *mut u8, _size: usize, visitor: extern "C" fn(*mut u8)) { visitor(addr); } extern "C" { #[cfg_attr(nightly, unwind(allowed))] fn throw_trap(ty: i32) -> !; } pub unsafe fn install_signal_handler() { let sa = SigAction::new( SigHandler::SigAction(signal_trap_handler), SaFlags::SA_ONSTACK | SaFlags::SA_SIGINFO, SigSet::empty(), ); sigaction(SIGSEGV, &sa).unwrap(); sigaction(SIGBUS, &sa).unwrap(); } #[cfg_attr(nightly, unwind(allowed))] extern "C" fn signal_trap_handler( _signum: ::nix::libc::c_int, _siginfo: *mut siginfo_t, _ucontext: *mut c_void, ) { unsafe { throw_trap(2); } } pub unsafe fn alloc_memory( size: usize, protect: MemProtect, ptr_out: &mut *mut u8, size_out: &mut usize, ) -> LLVMResult { let size = round_up_to_page_size(size); let ptr = mmap( ptr::null_mut(), size, match protect { MemProtect::NONE => PROT_NONE, MemProtect::READ => PROT_READ, MemProtect::READ_WRITE => PROT_READ | PROT_WRITE, MemProtect::READ_EXECUTE => PROT_READ | PROT_EXEC, }, MAP_PRIVATE | MAP_ANON, -1, 0, ); if ptr as isize == -1 { return LLVMResult::ALLOCATE_FAILURE; } *ptr_out = ptr as _; *size_out = size; LLVMResult::OK } pub unsafe fn protect_memory(ptr: *mut u8, size: usize, protect: MemProtect) -> LLVMResult { let res = mprotect( ptr as _, round_up_to_page_size(size), match protect { MemProtect::NONE => PROT_NONE, MemProtect::READ => PROT_READ, MemProtect::READ_WRITE => PROT_READ | PROT_WRITE, MemProtect::READ_EXECUTE => PROT_READ | PROT_EXEC, }, ); if
random
[ { "content": "type Trampoline = unsafe extern \"C\" fn(*mut Ctx, NonNull<Func>, *const u64, *mut u64);\n", "file_path": "lib/win-exception-handler/src/exception_handling.rs", "rank": 0, "score": 336851.1212825576 }, { "content": "pub fn round_up_to_page_size(size: usize) -> usize {\n\n (s...
Rust
datafusion/src/physical_plan/file_format/json.rs
andts/arrow-datafusion
1c39f5ce865e3e1225b4895196073be560a93e82
use async_trait::async_trait; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::physical_plan::{ DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics, }; use arrow::{datatypes::SchemaRef, json}; use std::any::Any; use std::sync::Arc; use super::file_stream::{BatchIter, FileStream}; use super::PhysicalPlanConfig; #[derive(Debug, Clone)] pub struct NdJsonExec { base_config: PhysicalPlanConfig, projected_statistics: Statistics, projected_schema: SchemaRef, } impl NdJsonExec { pub fn new(base_config: PhysicalPlanConfig) -> Self { let (projected_schema, projected_statistics) = base_config.project(); Self { base_config, projected_schema, projected_statistics, } } } #[async_trait] impl ExecutionPlan for NdJsonExec { fn as_any(&self) -> &dyn Any { self } fn schema(&self) -> SchemaRef { self.projected_schema.clone() } fn output_partitioning(&self) -> Partitioning { Partitioning::UnknownPartitioning(self.base_config.file_groups.len()) } fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> { Vec::new() } fn with_new_children( &self, children: Vec<Arc<dyn ExecutionPlan>>, ) -> Result<Arc<dyn ExecutionPlan>> { if children.is_empty() { Ok(Arc::new(self.clone()) as Arc<dyn ExecutionPlan>) } else { Err(DataFusionError::Internal(format!( "Children cannot be replaced in {:?}", self ))) } } async fn execute( &self, partition: usize, _runtime: Arc<RuntimeEnv>, ) -> Result<SendableRecordBatchStream> { let proj = self.base_config.projected_file_column_names(); let batch_size = self.base_config.batch_size; let file_schema = Arc::clone(&self.base_config.file_schema); let fun = move |file, _remaining: &Option<usize>| { Box::new(json::Reader::new( file, Arc::clone(&file_schema), batch_size, proj.clone(), )) as BatchIter }; Ok(Box::pin(FileStream::new( Arc::clone(&self.base_config.object_store), self.base_config.file_groups[partition].clone(), fun, Arc::clone(&self.projected_schema), self.base_config.limit, self.base_config.table_partition_cols.clone(), ))) } fn fmt_as( &self, t: DisplayFormatType, f: &mut std::fmt::Formatter, ) -> std::fmt::Result { match t { DisplayFormatType::Default => { write!( f, "JsonExec: batch_size={}, limit={:?}, files={}", self.base_config.batch_size, self.base_config.limit, super::FileGroupsDisplay(&self.base_config.file_groups), ) } } } fn statistics(&self) -> Statistics { self.projected_statistics.clone() } } #[cfg(test)] mod tests { use futures::StreamExt; use crate::datasource::{ file_format::{json::JsonFormat, FileFormat}, object_store::local::{ local_object_reader_stream, local_unpartitioned_file, LocalFileSystem, }, }; use super::*; const TEST_DATA_BASE: &str = "tests/jsons"; async fn infer_schema(path: String) -> Result<SchemaRef> { JsonFormat::default() .infer_schema(local_object_reader_stream(vec![path])) .await } #[tokio::test] async fn nd_json_exec_file_without_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); use arrow::datatypes::DataType; let path = format!("{}/1.json", TEST_DATA_BASE); let exec = NdJsonExec::new(PhysicalPlanConfig { object_store: Arc::new(LocalFileSystem {}), file_groups: vec![vec![local_unpartitioned_file(path.clone())]], file_schema: infer_schema(path).await?, statistics: Statistics::default(), projection: None, batch_size: 1024, limit: Some(3), table_partition_cols: vec![], }); let inferred_schema = exec.schema(); assert_eq!(inferred_schema.fields().len(), 4); inferred_schema.field_with_name("a").unwrap(); inferred_schema.field_with_name("b").unwrap(); inferred_schema.field_with_name("c").unwrap(); inferred_schema.field_with_name("d").unwrap(); assert_eq!( inferred_schema.field_with_name("a").unwrap().data_type(), &DataType::Int64 ); assert!(matches!( inferred_schema.field_with_name("b").unwrap().data_type(), DataType::List(_) )); assert_eq!( inferred_schema.field_with_name("d").unwrap().data_type(), &DataType::Utf8 ); let mut it = exec.execute(0, runtime).await?; let batch = it.next().await.unwrap()?; assert_eq!(batch.num_rows(), 3); let values = batch .column(0) .as_any() .downcast_ref::<arrow::array::Int64Array>() .unwrap(); assert_eq!(values.value(0), 1); assert_eq!(values.value(1), -10); assert_eq!(values.value(2), 2); Ok(()) } #[tokio::test] async fn nd_json_exec_file_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let path = format!("{}/1.json", TEST_DATA_BASE); let exec = NdJsonExec::new(PhysicalPlanConfig { object_store: Arc::new(LocalFileSystem {}), file_groups: vec![vec![local_unpartitioned_file(path.clone())]], file_schema: infer_schema(path).await?, statistics: Statistics::default(), projection: Some(vec![0, 2]), batch_size: 1024, limit: None, table_partition_cols: vec![], }); let inferred_schema = exec.schema(); assert_eq!(inferred_schema.fields().len(), 2); inferred_schema.field_with_name("a").unwrap(); inferred_schema.field_with_name("b").unwrap_err(); inferred_schema.field_with_name("c").unwrap(); inferred_schema.field_with_name("d").unwrap_err(); let mut it = exec.execute(0, runtime).await?; let batch = it.next().await.unwrap()?; assert_eq!(batch.num_rows(), 4); let values = batch .column(0) .as_any() .downcast_ref::<arrow::array::Int64Array>() .unwrap(); assert_eq!(values.value(0), 1); assert_eq!(values.value(1), -10); assert_eq!(values.value(2), 2); Ok(()) } }
use async_trait::async_trait; use crate::error::{DataFusionError, Result}; use crate::execution::runtime_env::RuntimeEnv; use crate::physical_plan::{ DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics, }; use arrow::{datatypes::SchemaRef, json}; use std::any::Any; use std::sync::Arc; use super::file_stream::{BatchIter, FileStream}; use super::PhysicalPlanConfig; #[derive(Debug, Clone)] pub struct NdJsonExec { base_config: PhysicalPlanConfig, projected_statistics: Statistics, projected_schema: SchemaRef, } impl NdJsonExec { pub fn new(base_config: PhysicalPlanConfig) -> Self { let (projected_schema, projected_statistics) = base_config.project(); Self { base_config, projected_schema, projected_statistics, } } } #[async_trait] impl ExecutionPlan for NdJsonExec { fn as_any(&self) -> &dyn Any { self } fn schema(&self) -> SchemaRef { self.projected_schema.clone() } fn output_partitioning(&self) -> Partitioning { Partitioning::UnknownPartitioning(self.base_config.file_groups.len()) } fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> { Vec::new() } fn with_new_children( &self, children: Vec<Arc<dyn ExecutionPlan>>, ) -> Result<Arc<dyn ExecutionPlan>> { if children.is_empty() { Ok(Arc::new(self.clone()) as Arc<dyn ExecutionPlan>) } else {
} } async fn execute( &self, partition: usize, _runtime: Arc<RuntimeEnv>, ) -> Result<SendableRecordBatchStream> { let proj = self.base_config.projected_file_column_names(); let batch_size = self.base_config.batch_size; let file_schema = Arc::clone(&self.base_config.file_schema); let fun = move |file, _remaining: &Option<usize>| { Box::new(json::Reader::new( file, Arc::clone(&file_schema), batch_size, proj.clone(), )) as BatchIter }; Ok(Box::pin(FileStream::new( Arc::clone(&self.base_config.object_store), self.base_config.file_groups[partition].clone(), fun, Arc::clone(&self.projected_schema), self.base_config.limit, self.base_config.table_partition_cols.clone(), ))) } fn fmt_as( &self, t: DisplayFormatType, f: &mut std::fmt::Formatter, ) -> std::fmt::Result { match t { DisplayFormatType::Default => { write!( f, "JsonExec: batch_size={}, limit={:?}, files={}", self.base_config.batch_size, self.base_config.limit, super::FileGroupsDisplay(&self.base_config.file_groups), ) } } } fn statistics(&self) -> Statistics { self.projected_statistics.clone() } } #[cfg(test)] mod tests { use futures::StreamExt; use crate::datasource::{ file_format::{json::JsonFormat, FileFormat}, object_store::local::{ local_object_reader_stream, local_unpartitioned_file, LocalFileSystem, }, }; use super::*; const TEST_DATA_BASE: &str = "tests/jsons"; async fn infer_schema(path: String) -> Result<SchemaRef> { JsonFormat::default() .infer_schema(local_object_reader_stream(vec![path])) .await } #[tokio::test] async fn nd_json_exec_file_without_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); use arrow::datatypes::DataType; let path = format!("{}/1.json", TEST_DATA_BASE); let exec = NdJsonExec::new(PhysicalPlanConfig { object_store: Arc::new(LocalFileSystem {}), file_groups: vec![vec![local_unpartitioned_file(path.clone())]], file_schema: infer_schema(path).await?, statistics: Statistics::default(), projection: None, batch_size: 1024, limit: Some(3), table_partition_cols: vec![], }); let inferred_schema = exec.schema(); assert_eq!(inferred_schema.fields().len(), 4); inferred_schema.field_with_name("a").unwrap(); inferred_schema.field_with_name("b").unwrap(); inferred_schema.field_with_name("c").unwrap(); inferred_schema.field_with_name("d").unwrap(); assert_eq!( inferred_schema.field_with_name("a").unwrap().data_type(), &DataType::Int64 ); assert!(matches!( inferred_schema.field_with_name("b").unwrap().data_type(), DataType::List(_) )); assert_eq!( inferred_schema.field_with_name("d").unwrap().data_type(), &DataType::Utf8 ); let mut it = exec.execute(0, runtime).await?; let batch = it.next().await.unwrap()?; assert_eq!(batch.num_rows(), 3); let values = batch .column(0) .as_any() .downcast_ref::<arrow::array::Int64Array>() .unwrap(); assert_eq!(values.value(0), 1); assert_eq!(values.value(1), -10); assert_eq!(values.value(2), 2); Ok(()) } #[tokio::test] async fn nd_json_exec_file_projection() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); let path = format!("{}/1.json", TEST_DATA_BASE); let exec = NdJsonExec::new(PhysicalPlanConfig { object_store: Arc::new(LocalFileSystem {}), file_groups: vec![vec![local_unpartitioned_file(path.clone())]], file_schema: infer_schema(path).await?, statistics: Statistics::default(), projection: Some(vec![0, 2]), batch_size: 1024, limit: None, table_partition_cols: vec![], }); let inferred_schema = exec.schema(); assert_eq!(inferred_schema.fields().len(), 2); inferred_schema.field_with_name("a").unwrap(); inferred_schema.field_with_name("b").unwrap_err(); inferred_schema.field_with_name("c").unwrap(); inferred_schema.field_with_name("d").unwrap_err(); let mut it = exec.execute(0, runtime).await?; let batch = it.next().await.unwrap()?; assert_eq!(batch.num_rows(), 4); let values = batch .column(0) .as_any() .downcast_ref::<arrow::array::Int64Array>() .unwrap(); assert_eq!(values.value(0), 1); assert_eq!(values.value(1), -10); assert_eq!(values.value(2), 2); Ok(()) } }
Err(DataFusionError::Internal(format!( "Children cannot be replaced in {:?}", self )))
call_expression
[]
Rust
language/vm/vm-runtime/src/loaded_data/loaded_module.rs
end-o/libra
38d2a1ed3fde793784b2dba978ee349099cdecfe
use crate::loaded_data::function::FunctionDef; use bytecode_verifier::VerifiedModule; use libra_types::{ identifier::Identifier, vm_error::{StatusCode, VMStatus}, }; use std::{collections::HashMap, sync::RwLock}; use vm::{ access::ModuleAccess, errors::VMResult, file_format::{ CompiledModule, FieldDefinitionIndex, FunctionDefinitionIndex, StructDefinitionIndex, StructFieldInformation, TableIndex, }, internals::ModuleIndex, }; use vm_runtime_types::loaded_data::struct_def::StructDef; #[derive(Debug, Eq, PartialEq)] pub struct LoadedModule { module: VerifiedModule, #[allow(dead_code)] pub struct_defs_table: HashMap<Identifier, StructDefinitionIndex>, #[allow(dead_code)] pub field_defs_table: HashMap<Identifier, FieldDefinitionIndex>, pub function_defs_table: HashMap<Identifier, FunctionDefinitionIndex>, pub function_defs: Vec<FunctionDef>, pub field_offsets: Vec<TableIndex>, cache: LoadedModuleCache, } impl ModuleAccess for LoadedModule { fn as_module(&self) -> &CompiledModule { &self.module.as_inner() } } #[derive(Debug)] struct LoadedModuleCache { struct_defs: Vec<RwLock<Option<StructDef>>>, } impl PartialEq for LoadedModuleCache { fn eq(&self, _other: &Self) -> bool { true } } impl Eq for LoadedModuleCache {} impl LoadedModule { pub fn new(module: VerifiedModule) -> Self { let mut struct_defs_table = HashMap::new(); let mut field_defs_table = HashMap::new(); let mut function_defs_table = HashMap::new(); let mut function_defs = vec![]; let struct_defs = module .struct_defs() .iter() .map(|_| RwLock::new(None)) .collect(); let cache = LoadedModuleCache { struct_defs }; let mut field_offsets: Vec<TableIndex> = module.field_defs().iter().map(|_| 0).collect(); for (idx, struct_def) in module.struct_defs().iter().enumerate() { let name = module .identifier_at(module.struct_handle_at(struct_def.struct_handle).name) .into(); let sd_idx = StructDefinitionIndex::new(idx as TableIndex); struct_defs_table.insert(name, sd_idx); if let StructFieldInformation::Declared { field_count, fields, } = &struct_def.field_information { for i in 0..*field_count { let field_index = fields.into_index(); assume!(field_index <= usize::max_value() - (i as usize)); field_offsets[field_index + (i as usize)] = i; } } } for (idx, field_def) in module.field_defs().iter().enumerate() { let name = module.identifier_at(field_def.name).into(); let fd_idx = FieldDefinitionIndex::new(idx as TableIndex); field_defs_table.insert(name, fd_idx); } for (idx, function_def) in module.function_defs().iter().enumerate() { let name = module .identifier_at(module.function_handle_at(function_def.function).name) .into(); let fd_idx = FunctionDefinitionIndex::new(idx as TableIndex); function_defs_table.insert(name, fd_idx); assume!(function_defs.len() < usize::max_value()); function_defs.push(FunctionDef::new(&module, fd_idx)); } LoadedModule { module, struct_defs_table, field_defs_table, function_defs_table, function_defs, field_offsets, cache, } } pub fn cached_struct_def_at(&self, idx: StructDefinitionIndex) -> Option<StructDef> { let cached = self.cache.struct_defs[idx.into_index()] .read() .expect("lock poisoned"); cached.clone() } pub fn cache_struct_def(&self, idx: StructDefinitionIndex, def: StructDef) { let mut cached = self.cache.struct_defs[idx.into_index()] .write() .expect("lock poisoned"); cached.replace(def); } pub fn get_field_offset(&self, idx: FieldDefinitionIndex) -> VMResult<TableIndex> { self.field_offsets .get(idx.into_index()) .cloned() .ok_or_else(|| VMStatus::new(StatusCode::LINKER_ERROR)) } } #[test] fn assert_thread_safe() { fn assert_send<T: Send>() {}; fn assert_sync<T: Sync>() {}; assert_send::<LoadedModule>(); assert_sync::<LoadedModule>(); }
use crate::loaded_data::function::FunctionDef; use bytecode_verifier::VerifiedModule; use libra_types::{ identifier::Identifier, vm_error::{StatusCode, VMStatus}, }; use std::{collections::HashMap, sync::RwLock}; use vm::{ access::ModuleAccess, errors::VMResult, file_format::{ CompiledModule, FieldDefinitionIndex, FunctionDefinitionIndex, StructDefinitionIndex, StructFieldInformation, TableIndex, }, internals::ModuleIndex, }; use vm_runtime_types::loaded_data::struct_def::StructDef; #[derive(Debug, Eq, PartialEq)] pub struct LoadedModule { module: VerifiedModule, #[allow(dead_code)] pub struct_defs_table: HashMap<Identifier, StructDefinitionIndex>, #[allow(dead_code)] pub field_defs_table: HashMap<Identifier, FieldDefinitionIndex>, pub function_defs_table: HashMap<Identifier, FunctionDefinitionIndex>, pub function_defs: Vec<FunctionDef>, pub field_offsets: Vec<TableIndex>, cache: LoadedModuleCache, } impl ModuleAccess for LoadedModule { fn as_module(&self) -> &CompiledModule { &self.module.as_inner() } } #[derive(Debug)] struct LoadedModuleCache { struct_defs: Vec<RwLock<Option<StructDef>>>, } impl PartialEq for LoadedModuleCache { fn eq(&self, _other: &Self) -> bool { true } } impl Eq for LoadedModuleCache {} impl LoadedModule { pub fn new(module: VerifiedModule) -> Self { let mut struct_defs_table = HashMap::new(); let mut field_defs_table = HashMap::new(); let mut function_defs_table = HashMap::new(); let mut function_defs = vec![]; let struct_defs = module .struct_defs() .iter() .map(|_| RwLock::new(None)) .collect(); let cache = LoadedModuleCache { struct_defs }; let mut field_offsets: Vec<TableIndex> = module.field_defs().iter().map(|_| 0).collect(); for (idx, struct_def) in module.struct_defs().iter().enumerate() { let name = module .identifier_at(module.struct_handle_at(struct_def.struct_handle).name) .into(); let sd_idx = StructDefinitionIndex::new(idx as TableIndex); struct_defs_table.insert(name, sd_idx);
} for (idx, field_def) in module.field_defs().iter().enumerate() { let name = module.identifier_at(field_def.name).into(); let fd_idx = FieldDefinitionIndex::new(idx as TableIndex); field_defs_table.insert(name, fd_idx); } for (idx, function_def) in module.function_defs().iter().enumerate() { let name = module .identifier_at(module.function_handle_at(function_def.function).name) .into(); let fd_idx = FunctionDefinitionIndex::new(idx as TableIndex); function_defs_table.insert(name, fd_idx); assume!(function_defs.len() < usize::max_value()); function_defs.push(FunctionDef::new(&module, fd_idx)); } LoadedModule { module, struct_defs_table, field_defs_table, function_defs_table, function_defs, field_offsets, cache, } } pub fn cached_struct_def_at(&self, idx: StructDefinitionIndex) -> Option<StructDef> { let cached = self.cache.struct_defs[idx.into_index()] .read() .expect("lock poisoned"); cached.clone() } pub fn cache_struct_def(&self, idx: StructDefinitionIndex, def: StructDef) { let mut cached = self.cache.struct_defs[idx.into_index()] .write() .expect("lock poisoned"); cached.replace(def); } pub fn get_field_offset(&self, idx: FieldDefinitionIndex) -> VMResult<TableIndex> { self.field_offsets .get(idx.into_index()) .cloned() .ok_or_else(|| VMStatus::new(StatusCode::LINKER_ERROR)) } } #[test] fn assert_thread_safe() { fn assert_send<T: Send>() {}; fn assert_sync<T: Sync>() {}; assert_send::<LoadedModule>(); assert_sync::<LoadedModule>(); }
if let StructFieldInformation::Declared { field_count, fields, } = &struct_def.field_information { for i in 0..*field_count { let field_index = fields.into_index(); assume!(field_index <= usize::max_value() - (i as usize)); field_offsets[field_index + (i as usize)] = i; } }
if_condition
[ { "content": "/// Get the StructTag for a StructDefinition defined in a published module.\n\npub fn resource_storage_key(module: &impl ModuleAccess, idx: StructDefinitionIndex) -> StructTag {\n\n let resource = module.struct_def_at(idx);\n\n let res_handle = module.struct_handle_at(resource.struct_handle)...
Rust
src/serialization/v2.rs
duncandean/macaroon
601ca1d8d76a93c6e4deae9f8d3f4bf0b2d7a67c
use caveat::{Caveat, CaveatBuilder}; use error::MacaroonError; use serialization::macaroon_builder::MacaroonBuilder; use ByteString; use Macaroon; use Result; const EOS: u8 = 0; const LOCATION: u8 = 1; const IDENTIFIER: u8 = 2; const VID: u8 = 4; const SIGNATURE: u8 = 6; const VARINT_PACK_SIZE: usize = 128; fn varint_size(size: usize) -> Vec<u8> { let mut buffer: Vec<u8> = Vec::new(); let mut my_size: usize = size; while my_size >= VARINT_PACK_SIZE { buffer.push(((my_size & (VARINT_PACK_SIZE - 1)) | VARINT_PACK_SIZE) as u8); my_size >>= 7; } buffer.push(my_size as u8); buffer } fn serialize_field(tag: u8, value: &[u8], buffer: &mut Vec<u8>) { buffer.push(tag); buffer.extend(varint_size(value.len())); buffer.extend(value); } pub fn serialize(macaroon: &Macaroon) -> Result<Vec<u8>> { let mut buffer: Vec<u8> = Vec::new(); buffer.push(2); if let Some(ref location) = macaroon.location() { serialize_field(LOCATION, &location.as_bytes().to_vec(), &mut buffer); }; serialize_field(IDENTIFIER, &macaroon.identifier().0, &mut buffer); buffer.push(EOS); for c in macaroon.caveats() { match c { Caveat::FirstParty(fp) => { serialize_field(IDENTIFIER, &fp.predicate().0, &mut buffer); buffer.push(EOS); } Caveat::ThirdParty(tp) => { serialize_field(LOCATION, tp.location().as_bytes(), &mut buffer); serialize_field(IDENTIFIER, &tp.id().0, &mut buffer); serialize_field(VID, &tp.verifier_id().0, &mut buffer); buffer.push(EOS); } } } buffer.push(EOS); serialize_field(SIGNATURE, &macaroon.signature(), &mut buffer); Ok(buffer) } struct Deserializer<'r> { data: &'r [u8], index: usize, } impl<'r> Deserializer<'r> { pub fn new(data: &[u8]) -> Deserializer { Deserializer { data, index: 0 } } fn get_byte(&mut self) -> Result<u8> { if self.index > self.data.len() - 1 { return Err(MacaroonError::DeserializationError(String::from( "Buffer overrun", ))); } let byte = self.data[self.index]; self.index += 1; Ok(byte) } pub fn get_tag(&mut self) -> Result<u8> { self.get_byte() } pub fn get_eos(&mut self) -> Result<u8> { let eos = self.get_byte()?; match eos { EOS => Ok(eos), _ => Err(MacaroonError::DeserializationError(String::from( "Expected EOS", ))), } } pub fn get_field(&mut self) -> Result<Vec<u8>> { let size: usize = self.get_field_size()?; if size + self.index > self.data.len() { return Err(MacaroonError::DeserializationError(String::from( "Unexpected end of \ field", ))); } let field: Vec<u8> = self.data[self.index..self.index + size].to_vec(); self.index += size; Ok(field) } fn get_field_size(&mut self) -> Result<usize> { let mut size: usize = 0; let mut shift: usize = 0; let mut byte: u8; while shift <= 63 { byte = self.get_byte()?; if byte & 128 != 0 { size |= ((byte & 127) << shift) as usize; } else { size |= (byte << shift) as usize; return Ok(size); } shift += 7; } Err(MacaroonError::DeserializationError(String::from( "Error in field size", ))) } } pub fn deserialize(data: &[u8]) -> Result<Macaroon> { let mut builder: MacaroonBuilder = MacaroonBuilder::new(); let mut deserializer: Deserializer = Deserializer::new(data); if deserializer.get_byte()? != 2 { return Err(MacaroonError::DeserializationError(String::from( "Wrong version number", ))); } let mut tag: u8 = deserializer.get_tag()?; match tag { LOCATION => builder.set_location(&String::from_utf8(deserializer.get_field()?)?), IDENTIFIER => builder.set_identifier(ByteString(deserializer.get_field()?)), _ => { return Err(MacaroonError::DeserializationError(String::from( "Identifier not found", ))) } } if builder.has_location() { tag = deserializer.get_tag()?; match tag { IDENTIFIER => { builder.set_identifier(ByteString(deserializer.get_field()?)); } _ => { return Err(MacaroonError::DeserializationError(String::from( "Identifier not \ found", ))) } } } deserializer.get_eos()?; tag = deserializer.get_tag()?; while tag != EOS { let mut caveat_builder: CaveatBuilder = CaveatBuilder::new(); match tag { LOCATION => { let field: Vec<u8> = deserializer.get_field()?; caveat_builder.add_location(String::from_utf8(field)?); } IDENTIFIER => caveat_builder.add_id(ByteString(deserializer.get_field()?)), _ => { return Err(MacaroonError::DeserializationError(String::from( "Caveat identifier \ not found", ))) } } if caveat_builder.has_location() { tag = deserializer.get_tag()?; match tag { IDENTIFIER => { let field: Vec<u8> = deserializer.get_field()?; caveat_builder.add_id(ByteString(field)); } _ => { return Err(MacaroonError::DeserializationError(String::from( "Caveat identifier \ not found", ))) } } } tag = deserializer.get_tag()?; match tag { VID => { let field: Vec<u8> = deserializer.get_field()?; caveat_builder.add_verifier_id(ByteString(field)); builder.add_caveat(caveat_builder.build()?); deserializer.get_eos()?; tag = deserializer.get_tag()?; } EOS => { builder.add_caveat(caveat_builder.build()?); tag = deserializer.get_tag()?; } _ => { return Err(MacaroonError::DeserializationError( "Unexpected caveat tag found".into(), )) } } } tag = deserializer.get_tag()?; if tag == SIGNATURE { let sig: Vec<u8> = deserializer.get_field()?; if sig.len() != 32 { return Err(MacaroonError::DeserializationError( "Bad signature length".into(), )); } builder.set_signature(&sig); } else { return Err(MacaroonError::DeserializationError( "Unexpected tag found".into(), )); } Ok(builder.build()?) } #[cfg(test)] mod tests { use caveat; use caveat::Caveat; use serialization::macaroon_builder::MacaroonBuilder; use ByteString; use Macaroon; use MacaroonKey; #[test] fn test_deserialize() { const SERIALIZED: &str = "AgETaHR0cDovL2V4YW1wbGUub3JnLwIFa2V5aWQAAhRhY2NvdW50ID0gMzczNTkyODU1OQACDHVzZXIgPSBhbGljZQAABiBL6WfNHqDGsmuvakqU7psFsViG2guoXoxCqTyNDhJe_A=="; const SIGNATURE: [u8; 32] = [ 75, 233, 103, 205, 30, 160, 198, 178, 107, 175, 106, 74, 148, 238, 155, 5, 177, 88, 134, 218, 11, 168, 94, 140, 66, 169, 60, 141, 14, 18, 94, 252, ]; let serialized: Vec<u8> = base64::decode_config(SERIALIZED, base64::URL_SAFE).unwrap(); let macaroon = super::deserialize(&serialized).unwrap(); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!(ByteString::from("keyid"), macaroon.identifier()); assert_eq!(2, macaroon.caveats().len()); let predicate = match &macaroon.caveats()[0] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("account = 3735928559"), predicate); let predicate = match &macaroon.caveats()[1] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("user = alice"), predicate); assert_eq!(MacaroonKey::from(SIGNATURE), macaroon.signature()); } #[test] fn test_serialize() { const SERIALIZED: &str = "AgETaHR0cDovL2V4YW1wbGUub3JnLwIFa2V5aWQAAhRhY2NvdW50ID0gMzczNTkyODU1OQACDHVzZXIgPSBhbGljZQAABiBL6WfNHqDGsmuvakqU7psFsViG2guoXoxCqTyNDhJe_A=="; const SIGNATURE: [u8; 32] = [ 75, 233, 103, 205, 30, 160, 198, 178, 107, 175, 106, 74, 148, 238, 155, 5, 177, 88, 134, 218, 11, 168, 94, 140, 66, 169, 60, 141, 14, 18, 94, 252, ]; let mut builder = MacaroonBuilder::new(); builder.add_caveat(caveat::new_first_party("account = 3735928559".into())); builder.add_caveat(caveat::new_first_party("user = alice".into())); builder.set_location("http://example.org/"); builder.set_identifier("keyid".into()); builder.set_signature(&SIGNATURE); let serialized = super::serialize(&builder.build().unwrap()).unwrap(); assert_eq!( base64::decode_config(SERIALIZED, base64::URL_SAFE).unwrap(), serialized ); } #[test] fn test_serialize_deserialize() { let mut macaroon = Macaroon::create(Some("http://example.org/".into()), &"key".into(), "keyid".into()).unwrap(); macaroon.add_first_party_caveat("account = 3735928559".into()); macaroon.add_first_party_caveat("user = alice".into()); macaroon.add_third_party_caveat( "https://auth.mybank.com", &"caveat key".into(), "caveat".into(), ); let serialized = super::serialize(&macaroon).unwrap(); macaroon = super::deserialize(&serialized).unwrap(); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!(ByteString::from("keyid"), macaroon.identifier()); assert_eq!(3, macaroon.caveats().len()); let predicate = match &macaroon.caveats()[0] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("account = 3735928559"), predicate); let predicate = match &macaroon.caveats()[1] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("user = alice"), predicate); let id = match &macaroon.caveats()[2] { Caveat::ThirdParty(tp) => tp.id(), _ => ByteString::default(), }; assert_eq!(ByteString::from("caveat"), id); let location = match &macaroon.caveats()[2] { Caveat::ThirdParty(tp) => tp.location(), _ => String::default(), }; assert_eq!("https://auth.mybank.com", location); } }
use caveat::{Caveat, CaveatBuilder}; use error::MacaroonError; use serialization::macaroon_builder::MacaroonBuilder; use ByteString; use Macaroon; use Result; const EOS: u8 = 0; const LOCATION: u8 = 1; const IDENTIFIER: u8 = 2; const VID: u8 = 4; const SIGNATURE: u8 = 6; const VARINT_PACK_SIZE: usize = 128; fn varint_size(size: usize) -> Vec<u8> { let mut buffer: Vec<u8> = Vec::new(); let mut my_size: usize = size; while my_size >= VARINT_PACK_SIZE { buffer.push(((my_size & (VARINT_PACK_SIZE - 1)) | VARINT_PACK_SIZE) as u8); my_size >>= 7; } buffer.push(my_size as u8); buffer } fn serialize_field(tag: u8, value: &[u8], buffer: &mut Vec<u8>) { buffer.push(tag); buffer.extend(varint_size(value.len())); buffer.extend(value); } pub fn serialize(macaroon: &Macaroon) -> Result<Vec<u8>> { let mut buffer: Vec<u8> = Vec::new(); buffer.push(2); if let Some(ref location) = macaroon.location() { serialize_field(LOCATION, &location.as_bytes().to_vec(), &mut buffer); }; serialize_field(IDENTIFIER, &macaroon.identifier().0, &mut buffer); buffer.push(EOS); for c in macaroon.caveats() { match c { Caveat::FirstParty(fp) => { serialize_field(IDENTIFIER, &fp.predicate().0, &mut buffer); buffer.push(EOS); } Caveat::ThirdParty(tp) => { serialize_field(LOCATION, tp.location().as_bytes(), &mut buffer); serialize_field(IDENTIFIER, &tp.id().0, &mut buffer); serialize_field(VID, &tp.verifier_id().0, &mut buffer); buffer.push(EOS); } } } buffer.push(EOS); serialize_field(SIGNATURE, &macaroon.signature(), &mut buffer); Ok(buffer) } struct Deserializer<'r> { data: &'r [u8], index: usize, } impl<'r> Deserializer<'r> { pub fn new(data: &[u8]) -> Deserializer { Deserializer { data, index: 0 } } fn get_byte(&mut self) -> Result<u8> { if self.index > self.data.len() - 1 { return Err(MacaroonError::DeserializationError(String::from( "Buffer overrun", ))); } let byte = self.data[self.index]; self.index += 1; Ok(byte) } pub fn get_tag(&mut self) -> Result<u8> { self.get_byte() } pub fn get_eos(&mut self) -> Result<u8> { let eos = self.get_byte()?; match eos { EOS => Ok(eos), _ => Err(MacaroonError::DeserializationError(String::from( "Expected EOS", ))), } } pub fn get_field(&mut self) -> Result<Vec<u8>> { let size: usize = self.get_field_size()?; if size + self.index > self.data.len() { return Err(MacaroonError::DeserializationError(String::from( "Unexpected end of \ field", ))); } let field: Vec<u8> = self.data[self.index..self.index + size].to_vec(); self.index += size; Ok(field) } fn get_field_size(&mut self) -> Result<usize> { let mut size: usize = 0; let mut shift: usize = 0; let mut byte: u8; while shift <= 63 { byte = self.get_byte()?; if byte & 128 != 0 { size |= ((byte & 127) << shift) as usize; } else { size |= (byte << shift) as usize; return Ok(size); } shift += 7; } Err(MacaroonError::DeserializationError(String::from( "Error in field size", ))) } } pub fn deserialize(data: &[u8]) -> Result<Macaroon> { let mut builder: MacaroonBuilder = MacaroonBuilder::new(); let mut deserializer: Deserializer = Deserializer::new(data); if deserializer.get_byte()? != 2 { return Err(MacaroonError::DeserializationError(String::from( "Wrong version number", ))); } let mut tag: u8 = deserializer.get_tag()?; match tag { LOCATION => builder.set_location(&String::from_utf8(deserializer.get_field()?)?), IDENTIFIER => builder.set_identifier(ByteString(deserializer.get_field()?)), _ => { return Err(MacaroonError::DeserializationError(String::from( "Identifier not found", ))) } } if builder.has_location() { tag = deserializer.get_tag()?; match tag { IDENTIFIER => { builder.set_identifier(ByteString(deserializer.get_field()?)); } _ => { return Err(MacaroonError::DeserializationError(String::from( "Identifier not \ found", ))) } } } deserializer.get_eos()?; tag = deserializer.get_tag()?; while tag != EOS { let mut caveat_builder: CaveatBuilder = CaveatBuilder::new(); match tag { LOCATION => { let field: Vec<u8> = deserializer.get_field()?; caveat_builder.add_location(String::from_utf8(field)?); } IDENTIFIER => caveat_builder.add_id(ByteString(deserializer.get_field()?)), _ => { return Err(MacaroonError::DeserializationError(String::from( "Caveat identifier \ not found", ))) } } if caveat_builder.has_location() { tag = deserializer.get_tag()?; match tag { IDENTIFIER => { let field: Vec<u8> = deserializer.get_field()?; caveat_builder.add_id(ByteString(field)); } _ => { return Err(MacaroonError::DeserializationError(String::from( "Caveat identifier \ not found", ))) } } } tag = deserializer.get_tag()?; match tag { VID => { let field: Vec<u8> = deserializer.get_field()?; caveat_builder.add_verifier_id(ByteString(field)); builder.add_caveat(caveat_builder.build()?); deserializer.get_eos()?; tag = deserializer.get_tag()?; } EOS => { builder.add_caveat(caveat_builder.build()?); tag = deserializer.get_tag()?; } _ => { return Err(MacaroonError::DeserializationError( "Unexpected caveat tag found".into(), )) } } } tag = deserializer.get_tag()?; if tag == SIGNATURE { let sig: Vec<u8> = deserializer.get_field()?; if sig.len() != 32 { return Err(MacaroonError::DeserializationError( "Bad signature length".into(), )); } builder.set_signature(&sig); } else { return Err(MacaroonError::DeserializationError( "Unexpected tag found".into(), )); } Ok(builder.build()?) } #[cfg(test)] mod tests { use caveat; use caveat::Caveat; use serialization::macaroon_builder::MacaroonBuilder; use ByteString; use Macaroon; use MacaroonKey; #[test] fn test_deserialize() { const SERIALIZED: &str = "AgETaHR0cDovL2V4YW1wbGUub3JnLwIFa2V5aWQAAhRhY2NvdW50ID0gMzczNTkyODU1OQACDHVzZXIgPSBhbGljZQAABiBL6WfNHqDGsmuvakqU7psFsViG2guoXoxCqTyNDhJe_A=="; const SIGNATURE: [u8; 32] = [ 75, 233, 103, 205, 30, 160, 198, 178, 107, 175, 106, 74, 148, 238, 155, 5, 177, 88, 134, 218, 11, 168, 94, 140, 66, 169, 60, 141, 14, 18, 94, 252, ]; let serialized: Vec<u8> = base64::decode_config(SERIALIZED, base64::URL_SAFE).unwrap(); let macaroon = super::deserialize(&serialized).unwrap(); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!(ByteString::from("keyid"), macaroon.identifier()); assert_eq!(2, macaroon.caveats().len()); let predicate = match &macaroon.caveats()[0] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("account = 3735928559"), predicate); let predicate = match &macaroon.caveats()[1] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("user = alice"), predicate); assert_eq!(MacaroonKey::from(SIGNATURE), macaroon.signature()); } #[test] fn test_serialize() { const SERIALIZED: &str = "AgETaHR0cDovL2V4YW1wbGUub3JnLwIFa2V5aWQAAhRhY2NvdW50ID0gMzczNTkyODU1OQACDHVzZXIgPSBhbGljZQAABiBL6WfNHqDGsmuvakqU7psFsViG2guoXoxCqTyNDhJe_A=="; const SIGNATURE: [u8; 32] = [ 75, 233, 103, 205, 30, 160, 198, 178, 107, 175, 106, 74, 148, 238, 155, 5, 177, 88, 134, 218, 11, 168, 94, 140, 66, 169, 60, 141, 14, 18, 94, 252, ]; let mut builder = MacaroonBuilder::new(); builder.add_caveat(caveat::new_first_party("account = 3735928559".into())); builder.add_caveat(caveat::new_first_party("user = alice".into())); builder.set_location("http://example.org/"); builder.set_identifier("keyid".into()); builder.set_signature(&SIGNATURE); let serialized = super::serialize(&builder.build().unwrap()).unwrap(); assert_eq!( base64::decode_config(SERIALIZED, base64::URL_SAFE).unwrap(), serialized ); } #[test]
}
fn test_serialize_deserialize() { let mut macaroon = Macaroon::create(Some("http://example.org/".into()), &"key".into(), "keyid".into()).unwrap(); macaroon.add_first_party_caveat("account = 3735928559".into()); macaroon.add_first_party_caveat("user = alice".into()); macaroon.add_third_party_caveat( "https://auth.mybank.com", &"caveat key".into(), "caveat".into(), ); let serialized = super::serialize(&macaroon).unwrap(); macaroon = super::deserialize(&serialized).unwrap(); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!(ByteString::from("keyid"), macaroon.identifier()); assert_eq!(3, macaroon.caveats().len()); let predicate = match &macaroon.caveats()[0] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("account = 3735928559"), predicate); let predicate = match &macaroon.caveats()[1] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("user = alice"), predicate); let id = match &macaroon.caveats()[2] { Caveat::ThirdParty(tp) => tp.id(), _ => ByteString::default(), }; assert_eq!(ByteString::from("caveat"), id); let location = match &macaroon.caveats()[2] { Caveat::ThirdParty(tp) => tp.location(), _ => String::default(), }; assert_eq!("https://auth.mybank.com", location); }
function_block-full_function
[ { "content": "pub fn deserialize(data: &[u8]) -> Result<Macaroon> {\n\n let v2j: Serialization = serde_json::from_slice(data)?;\n\n Macaroon::from_json(v2j)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::super::Format;\n\n use ByteString;\n\n use Caveat;\n\n use Macaroon;\n\n use Ma...
Rust
src/main.rs
tcr/rager
b664f0a93c2a773d232b30f9827813d57a32d5f7
#[macro_use] extern crate structopt; extern crate termion; extern crate ransid; extern crate failure; extern crate libc; extern crate crossbeam_channel; use std::path::PathBuf; use structopt::StructOpt; use failure::Error; use termion::event::*; use termion::scroll; use termion::input::{TermRead, MouseTerminal}; use termion::raw::IntoRawMode; use termion::terminal_size; use termion::screen::*; use std::io::{Write, stdout, stdin, Stdout}; use crossbeam_channel::unbounded; use std::fs::File; use std::io::BufReader; use termion::raw::RawTerminal; enum RagerEvent { Line(Vec<u8>), ScrollDown, ScrollUp, Quit, EndInput, Home, End, PageUp, PageDown, } #[derive(Copy, Clone)] struct RagerChar(char, bool, bool, bool, bool, ransid::color::Color); struct Buffer(usize, usize, RagerChar, Vec<Vec<RagerChar>>); impl Buffer { fn new(width: usize, height: usize, default: RagerChar) -> Buffer { Buffer( width, height, default, (0..height).map(|_| vec![default; width]).collect::<Vec<_>>(), ) } fn expand_vertical(&mut self) { let width = self.0; self.1 += 1; self.3.push(vec![self.2; width]); } fn set(&mut self, x: usize, y: usize, val: RagerChar) { if y >= self.height() { for _ in 0..(y - self.height() + 1) { self.expand_vertical(); } } self.3[y][x] = val; } fn get(&self, x: usize, y: usize) -> RagerChar { self.3[y][x] } fn width(&self) -> usize { self.0 } fn height(&self) -> usize { self.1 } } #[derive(Debug, StructOpt)] #[structopt(name = "rager", about = "A pager, like more or less.", author = "")] struct Opt { #[structopt(parse(from_os_str))] input: Option<PathBuf>, } fn main() { let opt = Opt::from_args(); run(opt.input).expect("Program error"); } fn run( input_file: Option<PathBuf>, ) -> Result<(), Error> { let stdin = stdin(); let input = if !termion::is_tty(&stdin) { unsafe { use std::os::unix::io::*; let tty = File::open("/dev/tty").unwrap(); let stdin_fd = libc::dup(0); let ret = File::from_raw_fd(stdin_fd); libc::dup2(tty.as_raw_fd(), 0); ::std::mem::forget(tty); Some(ret) } } else if let Some(input_file) = input_file { let file = File::open(input_file)?; Some(file) } else { eprintln!("Expected 'rager <input>' or input over stdin."); ::std::process::exit(1); }; let mut screen = MouseTerminal::from(AlternateScreen::from(stdout().into_raw_mode().unwrap())); write!(screen, "{}", termion::cursor::Hide).unwrap(); write!(screen, "{}", termion::clear::All).unwrap(); screen.flush().unwrap(); let (screen_width, screen_height) = terminal_size().unwrap(); let screen_width = screen_width as usize; let screen_height = screen_height as usize; type MyTerminal = MouseTerminal<AlternateScreen<RawTerminal<Stdout>>>; let (tx, rx) = unbounded(); let actor = ::std::thread::spawn({ move || { let mut console = ransid::Console::new(screen_width, 32767); let mut matrix = Buffer::new(screen_width, screen_height, RagerChar(' ', false, false, false, false, ransid::color::Color::Ansi(0))); fn write_char(screen: &mut MyTerminal, c: RagerChar, x: usize, y: usize) { let _ = write!(screen, "{}{}{}{}{}{}{}{}", termion::cursor::Goto((x as u16) + 1, (y as u16) + 1), if c.1 { format!("{}", termion::style::Bold) } else { format!("") }, if c.2 { format!("{}", termion::style::Underline) } else { format!("") }, if c.3 { format!("{}", termion::style::Italic) } else { format!("") }, if c.4 { format!("{}", termion::style::CrossedOut) } else { format!("") }, match c.5 { ransid::color::Color::Ansi(c) => format!("{}", termion::color::Fg(termion::color::AnsiValue(c))), ransid::color::Color::TrueColor(r, g, b) => format!("{}", termion::color::Fg(termion::color::Rgb(r, g, b))), }, c.0, termion::style::Reset, ); } fn write_row(screen: &mut MyTerminal, buffer: &Buffer, row: usize, dest_row: usize) { let matrix_width = buffer.width() as usize; for x in 0..matrix_width { write_char(screen, buffer.get(x, row), x, dest_row); } } let redraw_from = |screen: &mut MyTerminal, buffer: &Buffer, row: usize| { for y in 0..screen_height { write_row(screen, buffer, row + y, y); } }; let update = |screen: &mut MyTerminal, matrix: &mut Buffer, c, x, y, bold, underlined, italic, strikethrough, color| { let c = RagerChar(c, bold, underlined, italic, strikethrough, color); matrix.set(x, y, c); if y < (screen_height as usize) { write_char(screen, c, x, y); } }; let mut scroll: usize = 0; while let Ok(event) = rx.recv() { match event { RagerEvent::Home => { scroll = 0; redraw_from(&mut screen, &mut matrix, scroll); } RagerEvent::End => { scroll = matrix.height() - screen_height; redraw_from(&mut screen, &mut matrix, scroll); } RagerEvent::PageUp => { scroll = if scroll <= screen_height { 0 } else { scroll - screen_height }; redraw_from(&mut screen, &mut matrix, scroll); } RagerEvent::PageDown => { let last_row = matrix.height() - screen_height; let next_row = scroll + screen_height; scroll = if next_row >= last_row { last_row } else { next_row }; redraw_from(&mut screen, &mut matrix, scroll); } RagerEvent::Line(line) => { unsafe { let screen: &'static mut MyTerminal = ::std::mem::transmute(&mut screen); let matrix: &'static mut Buffer = ::std::mem::transmute(&mut matrix); console.write(&line, move |event| { use ransid::Event; match event { Event::Char { x, y, c, bold, underlined, italic, strikethrough, color, } => { update(screen, matrix, c, x, y, bold, underlined, italic, strikethrough, color); }, _ => {}, } }); } } RagerEvent::EndInput => { } RagerEvent::ScrollDown => { if scroll > 0 { write!(screen, "{}", scroll::Down(1)).unwrap(); scroll -= 1; let matrix_width = matrix.width() as usize; for x in 0..matrix_width { write_char(&mut screen, matrix.get(x, scroll), x, 0); } } } RagerEvent::ScrollUp => { if scroll + (screen_height as usize) < matrix.height() - 1 { write!(screen, "{}", scroll::Up(1)).unwrap(); scroll += 1; let matrix_width = matrix.width() as usize; let matrix_height = matrix.height() as usize; for x in 0..matrix_width { write_char(&mut screen, matrix.get(x, scroll + screen_height as usize), x, matrix_height); } } } RagerEvent::Quit => break, } screen.flush().unwrap(); } write!(screen, "{}", termion::cursor::Show).unwrap(); screen.flush().unwrap(); } }); if input.is_some() { ::std::thread::spawn({ let tx = tx.clone(); let mut input = BufReader::new(input.unwrap()); let mut buf = String::new(); move || { while let Ok(len) = ::std::io::BufRead::read_line(&mut input, &mut buf) { if len == 0 { break; } let _ = tx.send(RagerEvent::Line(buf.as_bytes().to_owned())); buf.clear(); } let _ = tx.send(RagerEvent::EndInput); } }); } for c in stdin.events() { match c.unwrap() { Event::Key(Key::Char('q')) | Event::Key(Key::Ctrl('c')) => break, Event::Mouse(MouseEvent::Press(MouseButton::WheelDown, _, _)) | Event::Key(Key::Down) => { let _ = tx.send(RagerEvent::ScrollUp); } Event::Mouse(MouseEvent::Press(MouseButton::WheelUp, _, _)) | Event::Key(Key::Up) => { let _ = tx.send(RagerEvent::ScrollDown); } Event::Key(Key::Home) => { let _ = tx.send(RagerEvent::Home); } Event::Key(Key::End) => { let _ = tx.send(RagerEvent::End); } Event::Key(Key::PageUp) => { let _ = tx.send(RagerEvent::PageUp); } Event::Key(Key::PageDown) => { let _ = tx.send(RagerEvent::PageDown); } _ => {}, } } let _ = tx.send(RagerEvent::Quit); let _ = actor.join(); Ok(()) }
#[macro_use] extern crate structopt; extern crate termion; extern crate ransid; extern crate failure; extern crate libc; extern crate crossbeam_channel; use std::path::PathBuf; use structopt::StructOpt; use failure::Error; use termion::event::*; use termion::scroll; use termion::input::{TermRead, MouseTerminal}; use termion::raw::IntoRawMode; use termion::terminal_size; use termion::screen::*; use std::io::{Write, stdout, stdin, Stdout}; use crossbeam_channel::unbounded; use std::fs::File; use std::io::BufReader; use termion::raw::RawTerminal; enum RagerEvent { Line(Vec<u8>), ScrollDown, ScrollUp, Quit, EndInput, Home, End, PageUp, PageDown, } #[derive(Copy, Clone)] struct RagerChar(char, bool, bool, bool, bool, ransid::color::Color); struct Buffer(usize, usize, RagerChar, Vec<Vec<RagerChar>>); impl Buffer { fn new(width: usize, height: usize, default: RagerChar) -> Buffer { Buffer( width, height, default, (0..height).map(|_| vec![default; width]).collect::<Vec<_>>(), ) } fn expand_vertical(&mut self) { let width = self.0; self.1 += 1; self.3.push(vec![self.2; width]); }
fn get(&self, x: usize, y: usize) -> RagerChar { self.3[y][x] } fn width(&self) -> usize { self.0 } fn height(&self) -> usize { self.1 } } #[derive(Debug, StructOpt)] #[structopt(name = "rager", about = "A pager, like more or less.", author = "")] struct Opt { #[structopt(parse(from_os_str))] input: Option<PathBuf>, } fn main() { let opt = Opt::from_args(); run(opt.input).expect("Program error"); } fn run( input_file: Option<PathBuf>, ) -> Result<(), Error> { let stdin = stdin(); let input = if !termion::is_tty(&stdin) { unsafe { use std::os::unix::io::*; let tty = File::open("/dev/tty").unwrap(); let stdin_fd = libc::dup(0); let ret = File::from_raw_fd(stdin_fd); libc::dup2(tty.as_raw_fd(), 0); ::std::mem::forget(tty); Some(ret) } } else if let Some(input_file) = input_file { let file = File::open(input_file)?; Some(file) } else { eprintln!("Expected 'rager <input>' or input over stdin."); ::std::process::exit(1); }; let mut screen = MouseTerminal::from(AlternateScreen::from(stdout().into_raw_mode().unwrap())); write!(screen, "{}", termion::cursor::Hide).unwrap(); write!(screen, "{}", termion::clear::All).unwrap(); screen.flush().unwrap(); let (screen_width, screen_height) = terminal_size().unwrap(); let screen_width = screen_width as usize; let screen_height = screen_height as usize; type MyTerminal = MouseTerminal<AlternateScreen<RawTerminal<Stdout>>>; let (tx, rx) = unbounded(); let actor = ::std::thread::spawn({ move || { let mut console = ransid::Console::new(screen_width, 32767); let mut matrix = Buffer::new(screen_width, screen_height, RagerChar(' ', false, false, false, false, ransid::color::Color::Ansi(0))); fn write_char(screen: &mut MyTerminal, c: RagerChar, x: usize, y: usize) { let _ = write!(screen, "{}{}{}{}{}{}{}{}", termion::cursor::Goto((x as u16) + 1, (y as u16) + 1), if c.1 { format!("{}", termion::style::Bold) } else { format!("") }, if c.2 { format!("{}", termion::style::Underline) } else { format!("") }, if c.3 { format!("{}", termion::style::Italic) } else { format!("") }, if c.4 { format!("{}", termion::style::CrossedOut) } else { format!("") }, match c.5 { ransid::color::Color::Ansi(c) => format!("{}", termion::color::Fg(termion::color::AnsiValue(c))), ransid::color::Color::TrueColor(r, g, b) => format!("{}", termion::color::Fg(termion::color::Rgb(r, g, b))), }, c.0, termion::style::Reset, ); } fn write_row(screen: &mut MyTerminal, buffer: &Buffer, row: usize, dest_row: usize) { let matrix_width = buffer.width() as usize; for x in 0..matrix_width { write_char(screen, buffer.get(x, row), x, dest_row); } } let redraw_from = |screen: &mut MyTerminal, buffer: &Buffer, row: usize| { for y in 0..screen_height { write_row(screen, buffer, row + y, y); } }; let update = |screen: &mut MyTerminal, matrix: &mut Buffer, c, x, y, bold, underlined, italic, strikethrough, color| { let c = RagerChar(c, bold, underlined, italic, strikethrough, color); matrix.set(x, y, c); if y < (screen_height as usize) { write_char(screen, c, x, y); } }; let mut scroll: usize = 0; while let Ok(event) = rx.recv() { match event { RagerEvent::Home => { scroll = 0; redraw_from(&mut screen, &mut matrix, scroll); } RagerEvent::End => { scroll = matrix.height() - screen_height; redraw_from(&mut screen, &mut matrix, scroll); } RagerEvent::PageUp => { scroll = if scroll <= screen_height { 0 } else { scroll - screen_height }; redraw_from(&mut screen, &mut matrix, scroll); } RagerEvent::PageDown => { let last_row = matrix.height() - screen_height; let next_row = scroll + screen_height; scroll = if next_row >= last_row { last_row } else { next_row }; redraw_from(&mut screen, &mut matrix, scroll); } RagerEvent::Line(line) => { unsafe { let screen: &'static mut MyTerminal = ::std::mem::transmute(&mut screen); let matrix: &'static mut Buffer = ::std::mem::transmute(&mut matrix); console.write(&line, move |event| { use ransid::Event; match event { Event::Char { x, y, c, bold, underlined, italic, strikethrough, color, } => { update(screen, matrix, c, x, y, bold, underlined, italic, strikethrough, color); }, _ => {}, } }); } } RagerEvent::EndInput => { } RagerEvent::ScrollDown => { if scroll > 0 { write!(screen, "{}", scroll::Down(1)).unwrap(); scroll -= 1; let matrix_width = matrix.width() as usize; for x in 0..matrix_width { write_char(&mut screen, matrix.get(x, scroll), x, 0); } } } RagerEvent::ScrollUp => { if scroll + (screen_height as usize) < matrix.height() - 1 { write!(screen, "{}", scroll::Up(1)).unwrap(); scroll += 1; let matrix_width = matrix.width() as usize; let matrix_height = matrix.height() as usize; for x in 0..matrix_width { write_char(&mut screen, matrix.get(x, scroll + screen_height as usize), x, matrix_height); } } } RagerEvent::Quit => break, } screen.flush().unwrap(); } write!(screen, "{}", termion::cursor::Show).unwrap(); screen.flush().unwrap(); } }); if input.is_some() { ::std::thread::spawn({ let tx = tx.clone(); let mut input = BufReader::new(input.unwrap()); let mut buf = String::new(); move || { while let Ok(len) = ::std::io::BufRead::read_line(&mut input, &mut buf) { if len == 0 { break; } let _ = tx.send(RagerEvent::Line(buf.as_bytes().to_owned())); buf.clear(); } let _ = tx.send(RagerEvent::EndInput); } }); } for c in stdin.events() { match c.unwrap() { Event::Key(Key::Char('q')) | Event::Key(Key::Ctrl('c')) => break, Event::Mouse(MouseEvent::Press(MouseButton::WheelDown, _, _)) | Event::Key(Key::Down) => { let _ = tx.send(RagerEvent::ScrollUp); } Event::Mouse(MouseEvent::Press(MouseButton::WheelUp, _, _)) | Event::Key(Key::Up) => { let _ = tx.send(RagerEvent::ScrollDown); } Event::Key(Key::Home) => { let _ = tx.send(RagerEvent::Home); } Event::Key(Key::End) => { let _ = tx.send(RagerEvent::End); } Event::Key(Key::PageUp) => { let _ = tx.send(RagerEvent::PageUp); } Event::Key(Key::PageDown) => { let _ = tx.send(RagerEvent::PageDown); } _ => {}, } } let _ = tx.send(RagerEvent::Quit); let _ = actor.join(); Ok(()) }
fn set(&mut self, x: usize, y: usize, val: RagerChar) { if y >= self.height() { for _ in 0..(y - self.height() + 1) { self.expand_vertical(); } } self.3[y][x] = val; }
function_block-full_function
[ { "content": "# rager 🎉\n\n\n\n[![](http://meritbadge.herokuapp.com/rager)](https://crates.io/crates/rager)\n\n\n\nA terminal Pager written in Rust. Like more or less.\n\n\n\n* Supports any `xterm`-supporting terminal thanks to Termion.\n\n* Support mouse scrolling (or up/down keys)\n\n* Supports content over ...
Rust
src/function.rs
eisterman/RustaCUDA
4f78c255c9e017c47e21af72a9dd8710f3b571e1
use crate::context::{CacheConfig, SharedMemoryConfig}; use crate::error::{CudaResult, ToResult}; use crate::module::Module; use cuda_sys::cuda::{self, CUfunction}; use std::marker::PhantomData; use std::mem::transmute; #[derive(Debug, Clone, PartialEq, Eq)] pub struct GridSize { pub x: u32, pub y: u32, pub z: u32, } impl GridSize { #[inline] pub fn x(x: u32) -> GridSize { GridSize { x, y: 1, z: 1 } } #[inline] pub fn xy(x: u32, y: u32) -> GridSize { GridSize { x, y, z: 1 } } #[inline] pub fn xyz(x: u32, y: u32, z: u32) -> GridSize { GridSize { x, y, z } } } impl From<u32> for GridSize { fn from(x: u32) -> GridSize { GridSize::x(x) } } impl From<(u32, u32)> for GridSize { fn from((x, y): (u32, u32)) -> GridSize { GridSize::xy(x, y) } } impl From<(u32, u32, u32)> for GridSize { fn from((x, y, z): (u32, u32, u32)) -> GridSize { GridSize::xyz(x, y, z) } } impl<'a> From<&'a GridSize> for GridSize { fn from(other: &GridSize) -> GridSize { other.clone() } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct BlockSize { pub x: u32, pub y: u32, pub z: u32, } impl BlockSize { #[inline] pub fn x(x: u32) -> BlockSize { BlockSize { x, y: 1, z: 1 } } #[inline] pub fn xy(x: u32, y: u32) -> BlockSize { BlockSize { x, y, z: 1 } } #[inline] pub fn xyz(x: u32, y: u32, z: u32) -> BlockSize { BlockSize { x, y, z } } } impl From<u32> for BlockSize { fn from(x: u32) -> BlockSize { BlockSize::x(x) } } impl From<(u32, u32)> for BlockSize { fn from((x, y): (u32, u32)) -> BlockSize { BlockSize::xy(x, y) } } impl From<(u32, u32, u32)> for BlockSize { fn from((x, y, z): (u32, u32, u32)) -> BlockSize { BlockSize::xyz(x, y, z) } } impl<'a> From<&'a BlockSize> for BlockSize { fn from(other: &BlockSize) -> BlockSize { other.clone() } } #[repr(u32)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum FunctionAttribute { MaxThreadsPerBlock = 0, SharedMemorySizeBytes = 1, ConstSizeBytes = 2, LocalSizeBytes = 3, NumRegisters = 4, PtxVersion = 5, BinaryVersion = 6, CacheModeCa = 7, #[doc(hidden)] __Nonexhaustive = 8, } #[derive(Debug)] pub struct Function<'a> { inner: CUfunction, module: PhantomData<&'a Module>, } impl<'a> Function<'a> { pub(crate) fn new(inner: CUfunction, _module: &Module) -> Function { Function { inner, module: PhantomData, } } pub fn get_attribute(&self, attr: FunctionAttribute) -> CudaResult<i32> { unsafe { let mut val = 0i32; cuda::cuFuncGetAttribute( &mut val as *mut i32, ::std::mem::transmute(attr), self.inner, ) .to_result()?; Ok(val) } } pub fn set_cache_config(&mut self, config: CacheConfig) -> CudaResult<()> { unsafe { cuda::cuFuncSetCacheConfig(self.inner, transmute(config)).to_result() } } pub fn set_shared_memory_config(&mut self, cfg: SharedMemoryConfig) -> CudaResult<()> { unsafe { cuda::cuFuncSetSharedMemConfig(self.inner, transmute(cfg)).to_result() } } pub(crate) fn to_inner(&self) -> CUfunction { self.inner } } #[macro_export] macro_rules! launch { ($module:ident . $function:ident <<<$grid:expr, $block:expr, $shared:expr, $stream:ident>>>( $( $arg:expr),* )) => { { let name = std::ffi::CString::new(stringify!($function)).unwrap(); let function = $module.get_function(&name); match function { Ok(f) => launch!(f<<<$grid, $block, $shared, $stream>>>( $($arg),* ) ), Err(e) => Err(e), } } }; ($function:ident <<<$grid:expr, $block:expr, $shared:expr, $stream:ident>>>( $( $arg:expr),* )) => { { fn assert_impl_devicecopy<T: $crate::memory::DeviceCopy>(_val: T) {}; if false { $( assert_impl_devicecopy($arg); )* }; $stream.launch(&$function, $grid, $block, $shared, &[ $( &$arg as *const _ as *mut ::std::ffi::c_void, )* ] ) } }; } #[cfg(test)] mod test { use super::*; use crate::memory::CopyDestination; use crate::memory::DeviceBuffer; use crate::quick_init; use crate::stream::{Stream, StreamFlags}; use std::error::Error; use std::ffi::CString; #[test] fn test_launch() -> Result<(), Box<dyn Error>> { let _context = quick_init(); let ptx_text = CString::new(include_str!("../resources/add.ptx"))?; let module = Module::load_from_string(&ptx_text)?; unsafe { let mut in_x = DeviceBuffer::from_slice(&[2.0f32; 128])?; let mut in_y = DeviceBuffer::from_slice(&[1.0f32; 128])?; let mut out: DeviceBuffer<f32> = DeviceBuffer::uninitialized(128)?; let stream = Stream::new(StreamFlags::NON_BLOCKING, None)?; launch!(module.sum<<<1, 128, 0, stream>>>(in_x.as_device_ptr(), in_y.as_device_ptr(), out.as_device_ptr(), out.len()))?; stream.synchronize()?; let mut out_host = [0f32; 128]; out.copy_to(&mut out_host[..])?; for x in out_host.iter() { assert_eq!(3, *x as u32); } } Ok(()) } }
use crate::context::{CacheConfig, SharedMemoryConfig}; use crate::error::{CudaResult, ToResult}; use crate::module::Module; use cuda_sys::cuda::{self, CUfunction}; use std::marker::PhantomData; use std::mem::transmute; #[derive(Debug, Clone, PartialEq, Eq)] pub struct GridSize { pub x: u32, pub y: u32, pub z: u32, } impl GridSize { #[inline] pub fn x(x: u32) -> GridSize { GridSize { x, y: 1, z: 1 } } #[inline] pub fn xy(x: u32, y: u32) -> GridSize { GridSize { x, y, z: 1 } } #[inline] pub fn xyz(x: u32, y: u32, z: u32) -> GridSize { GridSize { x, y, z } } } impl From<u32> for GridSize { fn from(x: u32) -> GridSize { GridSize::x(x) } } impl From<(u32, u32)> for GridSize { fn from((x, y): (u32, u32)) -> GridSize { GridSize::xy(x, y) } } impl From<(u32, u32, u32)> for GridSize { fn from((x, y, z): (u32, u32, u32)) -> GridSize { GridSize::xyz(x, y, z) } } impl<'a> From<&'a GridSize> for GridSize { fn from(other: &GridSize) -> GridSize { other.clone() } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct BlockSize { pub x: u32, pub y: u32, pub z: u32, } impl BlockSize { #[inline] pub fn x(x: u32) -> BlockSize { BlockSize { x, y: 1, z: 1 } } #[inline] pub fn xy(x: u32, y: u32) -> BlockSize { BlockSize { x, y, z: 1 } } #[inline] pub fn xyz(x: u32, y: u32, z: u32) -> BlockSize { BlockSize { x, y, z } } } impl From<u32> for BlockSize { fn from(x: u32) -> BlockSize { BlockSize::x(x) } } impl From<(u32, u32)> for BlockSize { fn from((x, y): (u32, u32)) -> BlockSize { BlockSize::xy(x, y) } } impl From<(u32, u32, u32)> for BlockSize { fn from((x, y, z): (u32, u32, u32)) -> BlockSize { BlockSize::xyz(x, y, z) } } impl<'a> From<&'a BlockSize> for BlockSize { fn from(other: &BlockSize) -> BlockSize { other.clone() } } #[repr(u32)]
.to_result()?; Ok(val) } } pub fn set_cache_config(&mut self, config: CacheConfig) -> CudaResult<()> { unsafe { cuda::cuFuncSetCacheConfig(self.inner, transmute(config)).to_result() } } pub fn set_shared_memory_config(&mut self, cfg: SharedMemoryConfig) -> CudaResult<()> { unsafe { cuda::cuFuncSetSharedMemConfig(self.inner, transmute(cfg)).to_result() } } pub(crate) fn to_inner(&self) -> CUfunction { self.inner } } #[macro_export] macro_rules! launch { ($module:ident . $function:ident <<<$grid:expr, $block:expr, $shared:expr, $stream:ident>>>( $( $arg:expr),* )) => { { let name = std::ffi::CString::new(stringify!($function)).unwrap(); let function = $module.get_function(&name); match function { Ok(f) => launch!(f<<<$grid, $block, $shared, $stream>>>( $($arg),* ) ), Err(e) => Err(e), } } }; ($function:ident <<<$grid:expr, $block:expr, $shared:expr, $stream:ident>>>( $( $arg:expr),* )) => { { fn assert_impl_devicecopy<T: $crate::memory::DeviceCopy>(_val: T) {}; if false { $( assert_impl_devicecopy($arg); )* }; $stream.launch(&$function, $grid, $block, $shared, &[ $( &$arg as *const _ as *mut ::std::ffi::c_void, )* ] ) } }; } #[cfg(test)] mod test { use super::*; use crate::memory::CopyDestination; use crate::memory::DeviceBuffer; use crate::quick_init; use crate::stream::{Stream, StreamFlags}; use std::error::Error; use std::ffi::CString; #[test] fn test_launch() -> Result<(), Box<dyn Error>> { let _context = quick_init(); let ptx_text = CString::new(include_str!("../resources/add.ptx"))?; let module = Module::load_from_string(&ptx_text)?; unsafe { let mut in_x = DeviceBuffer::from_slice(&[2.0f32; 128])?; let mut in_y = DeviceBuffer::from_slice(&[1.0f32; 128])?; let mut out: DeviceBuffer<f32> = DeviceBuffer::uninitialized(128)?; let stream = Stream::new(StreamFlags::NON_BLOCKING, None)?; launch!(module.sum<<<1, 128, 0, stream>>>(in_x.as_device_ptr(), in_y.as_device_ptr(), out.as_device_ptr(), out.len()))?; stream.synchronize()?; let mut out_host = [0f32; 128]; out.copy_to(&mut out_host[..])?; for x in out_host.iter() { assert_eq!(3, *x as u32); } } Ok(()) } }
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum FunctionAttribute { MaxThreadsPerBlock = 0, SharedMemorySizeBytes = 1, ConstSizeBytes = 2, LocalSizeBytes = 3, NumRegisters = 4, PtxVersion = 5, BinaryVersion = 6, CacheModeCa = 7, #[doc(hidden)] __Nonexhaustive = 8, } #[derive(Debug)] pub struct Function<'a> { inner: CUfunction, module: PhantomData<&'a Module>, } impl<'a> Function<'a> { pub(crate) fn new(inner: CUfunction, _module: &Module) -> Function { Function { inner, module: PhantomData, } } pub fn get_attribute(&self, attr: FunctionAttribute) -> CudaResult<i32> { unsafe { let mut val = 0i32; cuda::cuFuncGetAttribute( &mut val as *mut i32, ::std::mem::transmute(attr), self.inner, )
random
[ { "content": "/// Shortcut for initializing the CUDA Driver API and creating a CUDA context with default settings\n\n/// for the first device.\n\n///\n\n/// This is useful for testing or just setting up a basic CUDA context quickly. Users with more\n\n/// complex needs (multiple devices, custom flags, etc.) sho...
Rust
src/client/options/test.rs
judy2k/mongo-rust-driver
f39251fce6ede7ad712cca26e00f0b09fef6e085
use bson::{Bson, Document}; use pretty_assertions::assert_eq; use serde::Deserialize; use crate::{ client::options::{ClientOptions, StreamAddress}, error::ErrorKind, selection_criteria::{ReadPreference, SelectionCriteria}, test::run_spec_test, RUNTIME, }; #[derive(Debug, Deserialize)] struct TestFile { pub tests: Vec<TestCase>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct TestCase { pub description: String, pub uri: String, pub valid: bool, pub warning: Option<bool>, pub hosts: Option<Vec<Document>>, pub auth: Option<Document>, pub options: Option<Document>, } fn document_from_client_options(mut options: ClientOptions) -> Document { let mut doc = Document::new(); if let Some(s) = options.app_name.take() { doc.insert("appname", s); } if let Some(mechanism) = options .credential .get_or_insert_with(Default::default) .mechanism .take() { doc.insert("authmechanism", mechanism.as_str().to_string()); } if let Some(d) = options .credential .get_or_insert_with(Default::default) .mechanism_properties .take() { doc.insert("authmechanismproperties", d); } if let Some(s) = options .credential .get_or_insert_with(Default::default) .source .take() { doc.insert("authsource", s); } if let Some(i) = options.connect_timeout.take() { doc.insert("connecttimeoutms", i.as_millis() as i64); } if let Some(b) = options.direct_connection.take() { doc.insert("directconnection", b); } if let Some(i) = options.heartbeat_freq.take() { doc.insert("heartbeatfrequencyms", i.as_millis() as i64); } if let Some(i) = options.local_threshold.take() { doc.insert("localthresholdms", i.as_millis() as i64); } if let Some(i) = options.max_idle_time.take() { doc.insert("maxidletimems", i.as_millis() as i64); } if let Some(s) = options.repl_set_name.take() { doc.insert("replicaset", s); } if let Some(SelectionCriteria::ReadPreference(read_pref)) = options.selection_criteria.take() { let (level, tag_sets, max_staleness) = match read_pref { ReadPreference::Primary => ("primary", None, None), ReadPreference::PrimaryPreferred { tag_sets, max_staleness, } => ("primaryPreferred", tag_sets, max_staleness), ReadPreference::Secondary { tag_sets, max_staleness, } => ("secondary", tag_sets, max_staleness), ReadPreference::SecondaryPreferred { tag_sets, max_staleness, } => ("secondaryPreferred", tag_sets, max_staleness), ReadPreference::Nearest { tag_sets, max_staleness, } => ("nearest", tag_sets, max_staleness), }; doc.insert("readpreference", level); if let Some(tag_sets) = tag_sets { let tags: Vec<Bson> = tag_sets .into_iter() .map(|tag_set| { let mut tag_set: Vec<_> = tag_set.into_iter().collect(); tag_set.sort(); Bson::Document(tag_set.into_iter().map(|(k, v)| (k, v.into())).collect()) }) .collect(); doc.insert("readpreferencetags", tags); } if let Some(i) = max_staleness { doc.insert("maxstalenessseconds", i.as_secs() as i64); } } if let Some(b) = options.retry_reads.take() { doc.insert("retryreads", b); } if let Some(b) = options.retry_writes.take() { doc.insert("retrywrites", b); } if let Some(i) = options.server_selection_timeout.take() { doc.insert("serverselectiontimeoutms", i.as_millis() as i64); } if let Some(i) = options.socket_timeout.take() { doc.insert("sockettimeoutms", i.as_millis() as i64); } if let Some(mut opt) = options.tls_options() { let ca_file_path = opt.ca_file_path.take(); let cert_key_file_path = opt.cert_key_file_path.take(); let allow_invalid_certificates = opt.allow_invalid_certificates.take(); if let Some(s) = ca_file_path { doc.insert("tls", true); doc.insert("tlscafile", s); } if let Some(s) = cert_key_file_path { doc.insert("tlscertificatekeyfile", s); } if let Some(b) = allow_invalid_certificates { doc.insert("tlsallowinvalidcertificates", b); } } if let Some(vec) = options.compressors.take() { doc.insert( "compressors", Bson::Array(vec.into_iter().map(Bson::String).collect()), ); } if let Some(s) = options.read_concern.take() { doc.insert("readconcernlevel", s.as_str()); } if let Some(i_or_s) = options .write_concern .get_or_insert_with(Default::default) .w .take() { doc.insert("w", i_or_s.to_bson()); } if let Some(i) = options .write_concern .get_or_insert_with(Default::default) .w_timeout .take() { doc.insert("wtimeoutms", i.as_millis() as i64); } if let Some(b) = options .write_concern .get_or_insert_with(Default::default) .journal .take() { doc.insert("journal", b); } if let Some(i) = options.zlib_compression.take() { doc.insert("zlibcompressionlevel", i64::from(i)); } doc } fn run_test(test_file: TestFile) { for mut test_case in test_file.tests { if test_case.description.contains("ipv6") || test_case.description.contains("IP literal") || test_case .description .contains("tlsCertificateKeyFilePassword") || test_case.description.contains("tlsAllowInvalidHostnames") || test_case.description.contains("single-threaded") || test_case.description.contains("serverSelectionTryOnce") || test_case.description.contains("Unix") || test_case.description.contains("relative path") { continue; } let warning = test_case.warning.take().unwrap_or(false); if test_case.valid && !warning { let mut is_unsupported_host_type = false; if let Some(mut json_hosts) = test_case.hosts.take() { is_unsupported_host_type = json_hosts.iter_mut().any(|h_json| { match h_json.remove("type").as_ref().and_then(Bson::as_str) { Some("ip_literal") | Some("unix") => true, _ => false, } }); if !is_unsupported_host_type { let options = RUNTIME .block_on(ClientOptions::parse(&test_case.uri)) .unwrap(); let hosts: Vec<_> = options .hosts .into_iter() .map(StreamAddress::into_document) .collect(); assert_eq!(hosts, json_hosts); } } if !is_unsupported_host_type { let options = RUNTIME .block_on(ClientOptions::parse(&test_case.uri)) .expect(&test_case.description); let mut options_doc = document_from_client_options(options); if let Some(json_options) = test_case.options { let mut json_options: Document = json_options .into_iter() .filter_map(|(k, v)| { if let Bson::Null = v { None } else { Some((k.to_lowercase(), v)) } }) .collect(); if !json_options.contains_key("tlsallowinvalidcertificates") { if let Some(val) = json_options.remove("tlsinsecure") { json_options .insert("tlsallowinvalidcertificates", !val.as_bool().unwrap()); } } options_doc = options_doc .into_iter() .filter(|(ref key, _)| json_options.contains_key(key)) .collect(); assert_eq!(options_doc, json_options, "{}", test_case.description) } if let Some(json_auth) = test_case.auth { let json_auth: Document = json_auth .into_iter() .filter_map(|(k, v)| { if let Bson::Null = v { None } else { Some((k.to_lowercase(), v)) } }) .collect(); let options = RUNTIME .block_on(ClientOptions::parse(&test_case.uri)) .unwrap(); let mut expected_auth = options.credential.unwrap_or_default().into_document(); expected_auth = expected_auth .into_iter() .filter(|(ref key, _)| json_auth.contains_key(key)) .collect(); assert_eq!(expected_auth, json_auth); } } } else { let expected_type = if warning { "warning" } else { "error" }; match RUNTIME .block_on(ClientOptions::parse(&test_case.uri)) .as_ref() .map_err(|e| e.as_ref()) { Ok(_) => panic!("expected {}", expected_type), Err(ErrorKind::ArgumentError { .. }) => {} Err(e) => panic!("expected ArgumentError, but got {:?}", e), } } } } #[cfg_attr(feature = "tokio-runtime", tokio::test(core_threads = 2))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn run_uri_options_spec_tests() { run_spec_test(&["uri-options"], run_test); } #[cfg_attr(feature = "tokio-runtime", tokio::test(core_threads = 2))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn run_connection_string_spec_tests() { run_spec_test(&["connection-string"], run_test); }
use bson::{Bson, Document}; use pretty_assertions::assert_eq; use serde::Deserialize; use crate::{ client::options::{ClientOptions, StreamAddress}, error::ErrorKind, selection_criteria::{ReadPreference, SelectionCriteria}, test::run_spec_test, RUNTIME, }; #[derive(Debug, Deserialize)] struct TestFile { pub tests: Vec<TestCase>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct TestCase { pub description: String, pub uri: String, pub valid: bool, pub warning: Option<bool>, pub hosts: Option<Vec<Document>>, pub auth: Option<Document>, pub options: Option<Document>, } fn document_from_client_options(mut options: ClientOptions) -> Document { let mut doc = Document::new(); if let Some(s) = options.app_name.take() { doc.insert("appname", s); } if let Some(mechanism) = options .credential .get_or_insert_with(Default::default) .mechanism .take() { doc.insert("authmechanism", mechanism.as_str().to_string()); } if let Some(d) = options .credential .get_or_insert_with(Default::default) .mechanism_properties .take() { doc.insert("authmechanismproperties", d); } if let Some(s) = options .credential .get_or_insert_with(Default::default) .source .take() { doc.insert("authsource", s); } if let Some(i) = options.connect_timeout.take() { doc.insert("connecttimeoutms", i.as_millis() as i64); } if let Some(b) = options.direct_connection.take() { doc.insert("directconnection", b); } if let Some(i) = options.heartbeat_freq.take() { doc.insert("heartbeatfrequencyms", i.as_millis() as i64); } if let Some(i) = options.local_threshold.take() { doc.insert("localthresholdms", i.as_millis() as i64); } if let Some(i) = options.max_idle_time.take() { doc.insert("maxidletimems", i.as_millis() as i64); } if let Some(s) = options.repl_set_name.take() { doc.insert("replicaset", s); } if let Some(SelectionCriteria::ReadPreference(read_pref)) = options.selection_criteria.take() { let (level, tag_sets, max_staleness) = match read_pref { ReadPreference::Primary => ("primary", None, None), ReadPreference::PrimaryPreferred { tag_sets, max_staleness, } => ("primaryPreferred", tag_sets, max_staleness), ReadPreference::Secondary { tag_sets, max_staleness, } => ("secondary", tag_sets, max_staleness), ReadPreference::SecondaryPreferred { tag_sets, max_staleness, } => ("secondaryPreferred", tag_sets, max_staleness), ReadPreference::Nearest { tag_sets, max_staleness, } => ("nearest", tag_sets, max_staleness), }; doc.insert("readpreference", level); if let Some(tag_sets) = tag_sets { let tags: Vec<Bson> = tag_sets .into_iter() .map(|tag_set| { let mut tag_set: Vec<_> = tag_set.into_iter().collect(); tag_set.sort(); Bson::Document(tag_set.into_iter().map(|(k, v)| (k, v.into())).collect()) }) .collect(); doc.insert("re
.block_on(ClientOptions::parse(&test_case.uri)) .unwrap(); let hosts: Vec<_> = options .hosts .into_iter() .map(StreamAddress::into_document) .collect(); assert_eq!(hosts, json_hosts); } } if !is_unsupported_host_type { let options = RUNTIME .block_on(ClientOptions::parse(&test_case.uri)) .expect(&test_case.description); let mut options_doc = document_from_client_options(options); if let Some(json_options) = test_case.options { let mut json_options: Document = json_options .into_iter() .filter_map(|(k, v)| { if let Bson::Null = v { None } else { Some((k.to_lowercase(), v)) } }) .collect(); if !json_options.contains_key("tlsallowinvalidcertificates") { if let Some(val) = json_options.remove("tlsinsecure") { json_options .insert("tlsallowinvalidcertificates", !val.as_bool().unwrap()); } } options_doc = options_doc .into_iter() .filter(|(ref key, _)| json_options.contains_key(key)) .collect(); assert_eq!(options_doc, json_options, "{}", test_case.description) } if let Some(json_auth) = test_case.auth { let json_auth: Document = json_auth .into_iter() .filter_map(|(k, v)| { if let Bson::Null = v { None } else { Some((k.to_lowercase(), v)) } }) .collect(); let options = RUNTIME .block_on(ClientOptions::parse(&test_case.uri)) .unwrap(); let mut expected_auth = options.credential.unwrap_or_default().into_document(); expected_auth = expected_auth .into_iter() .filter(|(ref key, _)| json_auth.contains_key(key)) .collect(); assert_eq!(expected_auth, json_auth); } } } else { let expected_type = if warning { "warning" } else { "error" }; match RUNTIME .block_on(ClientOptions::parse(&test_case.uri)) .as_ref() .map_err(|e| e.as_ref()) { Ok(_) => panic!("expected {}", expected_type), Err(ErrorKind::ArgumentError { .. }) => {} Err(e) => panic!("expected ArgumentError, but got {:?}", e), } } } } #[cfg_attr(feature = "tokio-runtime", tokio::test(core_threads = 2))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn run_uri_options_spec_tests() { run_spec_test(&["uri-options"], run_test); } #[cfg_attr(feature = "tokio-runtime", tokio::test(core_threads = 2))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn run_connection_string_spec_tests() { run_spec_test(&["connection-string"], run_test); }
adpreferencetags", tags); } if let Some(i) = max_staleness { doc.insert("maxstalenessseconds", i.as_secs() as i64); } } if let Some(b) = options.retry_reads.take() { doc.insert("retryreads", b); } if let Some(b) = options.retry_writes.take() { doc.insert("retrywrites", b); } if let Some(i) = options.server_selection_timeout.take() { doc.insert("serverselectiontimeoutms", i.as_millis() as i64); } if let Some(i) = options.socket_timeout.take() { doc.insert("sockettimeoutms", i.as_millis() as i64); } if let Some(mut opt) = options.tls_options() { let ca_file_path = opt.ca_file_path.take(); let cert_key_file_path = opt.cert_key_file_path.take(); let allow_invalid_certificates = opt.allow_invalid_certificates.take(); if let Some(s) = ca_file_path { doc.insert("tls", true); doc.insert("tlscafile", s); } if let Some(s) = cert_key_file_path { doc.insert("tlscertificatekeyfile", s); } if let Some(b) = allow_invalid_certificates { doc.insert("tlsallowinvalidcertificates", b); } } if let Some(vec) = options.compressors.take() { doc.insert( "compressors", Bson::Array(vec.into_iter().map(Bson::String).collect()), ); } if let Some(s) = options.read_concern.take() { doc.insert("readconcernlevel", s.as_str()); } if let Some(i_or_s) = options .write_concern .get_or_insert_with(Default::default) .w .take() { doc.insert("w", i_or_s.to_bson()); } if let Some(i) = options .write_concern .get_or_insert_with(Default::default) .w_timeout .take() { doc.insert("wtimeoutms", i.as_millis() as i64); } if let Some(b) = options .write_concern .get_or_insert_with(Default::default) .journal .take() { doc.insert("journal", b); } if let Some(i) = options.zlib_compression.take() { doc.insert("zlibcompressionlevel", i64::from(i)); } doc } fn run_test(test_file: TestFile) { for mut test_case in test_file.tests { if test_case.description.contains("ipv6") || test_case.description.contains("IP literal") || test_case .description .contains("tlsCertificateKeyFilePassword") || test_case.description.contains("tlsAllowInvalidHostnames") || test_case.description.contains("single-threaded") || test_case.description.contains("serverSelectionTryOnce") || test_case.description.contains("Unix") || test_case.description.contains("relative path") { continue; } let warning = test_case.warning.take().unwrap_or(false); if test_case.valid && !warning { let mut is_unsupported_host_type = false; if let Some(mut json_hosts) = test_case.hosts.take() { is_unsupported_host_type = json_hosts.iter_mut().any(|h_json| { match h_json.remove("type").as_ref().and_then(Bson::as_str) { Some("ip_literal") | Some("unix") => true, _ => false, } }); if !is_unsupported_host_type { let options = RUNTIME
random
[ { "content": "fn parse_i64_ext_json(doc: &Document) -> Option<i64> {\n\n let number_string = doc.get(\"$numberLong\").and_then(Bson::as_str)?;\n\n number_string.parse::<i64>().ok()\n\n}\n\n\n", "file_path": "src/test/util/matchable.rs", "rank": 0, "score": 304714.2147247278 }, { "conte...
Rust
tremor-pipeline/src/op/runtime/tremor.rs
0xd34b33f/tremor-runtime
73af8033509e224e4cbf078559f27bec4c12cf3d
use crate::op::prelude::*; use crate::FN_REGISTRY; use simd_json::borrowed::Value; use tremor_script::highlighter::Dumb as DumbHighlighter; use tremor_script::path::load as load_module_path; use tremor_script::prelude::*; use tremor_script::{self, AggrType, EventContext, Return, Script}; op!(TremorFactory(node) { if let Some(map) = &node.config { let config: Config = Config::new(map)?; match tremor_script::Script::parse( &load_module_path(), "<operator>", config.script.clone(), &*FN_REGISTRY.lock()?) { Ok(runtime) => Ok(Box::new(Tremor { runtime, config, id: node.id.clone().to_string(), })), Err(e) => { let mut h = DumbHighlighter::new(); if let Err(e) = tremor_script::Script::format_error_from_script(&config.script, &mut h, &e) { error!("{}", e.to_string()); } else { error!("{}", h.to_string()); }; Err(e.error().into()) } } } else { Err(ErrorKind::MissingOpConfig(node.id.clone().to_string()).into()) } }); #[derive(Debug, Clone, Deserialize)] struct Config { script: String, } impl ConfigImpl for Config {} #[derive(Debug)] pub struct Tremor { config: Config, runtime: Script, id: String, } impl Operator for Tremor { fn on_event( &mut self, _in_port: &str, state: &mut Value<'static>, mut event: Event, ) -> Result<Vec<(Cow<'static, str>, Event)>> { let out_port = { let context = EventContext::new(event.ingest_ns, event.origin_uri); let (unwind_event, event_meta) = event.data.parts(); let value = self.runtime.run( &context, AggrType::Emit, unwind_event, state, event_meta, ); event.origin_uri = context.origin_uri; match value { Ok(Return::EmitEvent { port }) => port.map_or_else(|| "out".into(), Cow::Owned), Ok(Return::Emit { value, port }) => { *unwind_event = value; port.map_or_else(|| "out".into(), Cow::Owned) } Ok(Return::Drop) => return Ok(vec![]), Err(ref e) => { let mut o = Value::from(hashmap! { "error".into() => Value::from(self.runtime.format_error(&e)), }); std::mem::swap(&mut o, unwind_event); if let Some(error) = unwind_event.as_object_mut() { error.insert("event".into(), o); } else { unreachable!(); }; "error".into() } } }; Ok(vec![(out_port, event)]) } } #[cfg(test)] mod test { use super::*; use crate::FN_REGISTRY; use simd_json::json; use tremor_script::path::ModulePath; #[test] fn mutate() { let config = Config { script: r#"match event.a of case 1 => let event.snot = "badger" end; event;"# .to_string(), }; let runtime = Script::parse( &ModulePath { mounts: vec![] }, "<test>", config.script.clone(), &*FN_REGISTRY.lock().expect("could not claim lock"), ) .expect("failed to parse script"); let mut op = Tremor { config, runtime, id: "badger".into(), }; let event = Event { origin_uri: None, is_batch: false, id: 1, ingest_ns: 1, data: Value::from(json!({"a": 1})).into(), kind: None, }; let mut state = Value::null(); let (out, event) = op .on_event("in", &mut state, event) .expect("failed to run pipeline") .pop() .expect("no event returned"); assert_eq!("out", out); assert_eq!( *event.data.suffix().value(), Value::from(json!({"snot": "badger", "a": 1})) ) } #[test] pub fn test_how_it_handles_errors() { let config = Config { script: r#"match this is invalid code so no match case"#.to_string(), }; let _runtime = Script::parse( &ModulePath { mounts: vec![] }, "<test>", config.script, &*FN_REGISTRY.lock().expect("could not claim lock"), ); } }
use crate::op::prelude::*; use crate::FN_REGISTRY; use simd_json::borrowed::Value; use tremor_script::highlighter::Dumb as DumbHighlighter; use tremor_script::path::load as load_module_path; use tremor_script::prelude::*; use tremor_script::{self, AggrType, EventContext, Return, Script}; op!(TremorFactory(node) { if let Some(map) = &node.config { let config: Config = Config::new(map)?; match tremor_script::Script::parse( &load_module_path(), "<operator>", config.script.clone(), &*FN_REGISTRY.lock()?) { Ok(runtime) => Ok(Box::new(Tremor { runtime, config, id: node.id.clone().to_string(), })), Err(e) => { let mut h = DumbHighlighter::new(); if let Err(e) = tremor_script::Script::format_error_from_script(&config.script, &mut h, &e) { error!("{}", e.to_string()); } else { error!("{}", h.to_string()); }; Err(e.error().into()) } } } else { Err(ErrorKind::MissingOpConfig(node
t_eq!("out", out); assert_eq!( *event.data.suffix().value(), Value::from(json!({"snot": "badger", "a": 1})) ) } #[test] pub fn test_how_it_handles_errors() { let config = Config { script: r#"match this is invalid code so no match case"#.to_string(), }; let _runtime = Script::parse( &ModulePath { mounts: vec![] }, "<test>", config.script, &*FN_REGISTRY.lock().expect("could not claim lock"), ); } }
.id.clone().to_string()).into()) } }); #[derive(Debug, Clone, Deserialize)] struct Config { script: String, } impl ConfigImpl for Config {} #[derive(Debug)] pub struct Tremor { config: Config, runtime: Script, id: String, } impl Operator for Tremor { fn on_event( &mut self, _in_port: &str, state: &mut Value<'static>, mut event: Event, ) -> Result<Vec<(Cow<'static, str>, Event)>> { let out_port = { let context = EventContext::new(event.ingest_ns, event.origin_uri); let (unwind_event, event_meta) = event.data.parts(); let value = self.runtime.run( &context, AggrType::Emit, unwind_event, state, event_meta, ); event.origin_uri = context.origin_uri; match value { Ok(Return::EmitEvent { port }) => port.map_or_else(|| "out".into(), Cow::Owned), Ok(Return::Emit { value, port }) => { *unwind_event = value; port.map_or_else(|| "out".into(), Cow::Owned) } Ok(Return::Drop) => return Ok(vec![]), Err(ref e) => { let mut o = Value::from(hashmap! { "error".into() => Value::from(self.runtime.format_error(&e)), }); std::mem::swap(&mut o, unwind_event); if let Some(error) = unwind_event.as_object_mut() { error.insert("event".into(), o); } else { unreachable!(); }; "error".into() } } }; Ok(vec![(out_port, event)]) } } #[cfg(test)] mod test { use super::*; use crate::FN_REGISTRY; use simd_json::json; use tremor_script::path::ModulePath; #[test] fn mutate() { let config = Config { script: r#"match event.a of case 1 => let event.snot = "badger" end; event;"# .to_string(), }; let runtime = Script::parse( &ModulePath { mounts: vec![] }, "<test>", config.script.clone(), &*FN_REGISTRY.lock().expect("could not claim lock"), ) .expect("failed to parse script"); let mut op = Tremor { config, runtime, id: "badger".into(), }; let event = Event { origin_uri: None, is_batch: false, id: 1, ingest_ns: 1, data: Value::from(json!({"a": 1})).into(), kind: None, }; let mut state = Value::null(); let (out, event) = op .on_event("in", &mut state, event) .expect("failed to run pipeline") .pop() .expect("no event returned"); asser
random
[]
Rust
node/src/components/rpc_server/rpcs/docs.rs
sacherjj/casper-node
2569ebd51923d0353542c93c5d47480246170cbb
#![allow(clippy::field_reassign_with_default)] use futures::{future::BoxFuture, FutureExt}; use http::Response; use hyper::Body; use once_cell::sync::Lazy; use schemars::{ gen::{SchemaGenerator, SchemaSettings}, schema::Schema, JsonSchema, Map, MapEntry, }; use semver::Version; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use warp_json_rpc::Builder; use super::{ account::PutDeploy, chain::{GetBlock, GetBlockTransfers, GetStateRootHash}, info::{GetDeploy, GetPeers, GetStatus}, state::{GetAuctionInfo, GetBalance, GetItem}, Error, ReactorEventT, RpcWithOptionalParams, RpcWithParams, RpcWithoutParams, RpcWithoutParamsExt, }; use crate::{effect::EffectBuilder, rpcs::chain::GetEraInfoBySwitchBlock}; pub(crate) static DOCS_EXAMPLE_PROTOCOL_VERSION: Lazy<Version> = Lazy::new(|| Version::new(1, 1, 2)); const DEFINITIONS_PATH: &str = "#/components/schemas/"; static OPEN_RPC_SCHEMA: Lazy<OpenRpcSchema> = Lazy::new(|| { let contact = OpenRpcContactField { name: "CasperLabs".to_string(), url: "https://casperlabs.io".to_string(), }; let license = OpenRpcLicenseField { name: "CasperLabs Open Source License Version 1.0".to_string(), url: "https://raw.githubusercontent.com/CasperLabs/casper-node/master/LICENSE".to_string(), }; let info = OpenRpcInfoField { version: DOCS_EXAMPLE_PROTOCOL_VERSION.to_string(), title: "Client API of Casper Node".to_string(), description: "This describes the JSON-RPC 2.0 API of a node on the Casper network." .to_string(), contact, license, }; let server = OpenRpcServerEntry { name: "any Casper Network node".to_string(), url: "http://IP:PORT/rpc/".to_string(), }; let mut schema = OpenRpcSchema { openrpc: "1.0.0-rc1".to_string(), info, servers: vec![server], methods: vec![], components: Components { schemas: Map::new(), }, }; schema.push_with_params::<PutDeploy>("receives a Deploy to be executed by the network"); schema.push_with_params::<GetDeploy>("returns a Deploy from the network"); schema.push_without_params::<GetPeers>("returns a list of peers connected to the node"); schema.push_without_params::<GetStatus>("returns the current status of the node"); schema.push_with_optional_params::<GetBlock>("returns a Block from the network"); schema.push_with_optional_params::<GetBlockTransfers>( "returns all transfers for a Block from the network", ); schema.push_with_optional_params::<GetStateRootHash>( "returns a state root hash at a given Block", ); schema.push_with_params::<GetItem>("returns a stored value from the network"); schema.push_with_params::<GetBalance>("returns a purse's balance from the network"); schema.push_with_optional_params::<GetEraInfoBySwitchBlock>( "returns an EraInfo from the network", ); schema.push_without_params::<GetAuctionInfo>( "returns the bids and validators as of the most recently added Block", ); schema }); static LIST_RPCS_RESULT: Lazy<ListRpcsResult> = Lazy::new(|| ListRpcsResult { api_version: DOCS_EXAMPLE_PROTOCOL_VERSION.clone(), name: "OpenRPC Schema".to_string(), schema: OPEN_RPC_SCHEMA.clone(), }); pub trait DocExample { fn doc_example() -> &'static Self; } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcSchema { openrpc: String, info: OpenRpcInfoField, servers: Vec<OpenRpcServerEntry>, methods: Vec<Method>, components: Components, } impl OpenRpcSchema { fn new_generator() -> SchemaGenerator { let settings = SchemaSettings::default().with(|settings| { settings.definitions_path = DEFINITIONS_PATH.to_string(); }); settings.into_generator() } fn push_with_params<T: RpcWithParams>(&mut self, summary: &str) { let mut generator = Self::new_generator(); let params_schema = T::RequestParams::json_schema(&mut generator); let params = Self::make_params(params_schema); let result_schema = T::ResponseResult::json_schema(&mut generator); let result = ResponseResult { name: format!("{}_result", T::METHOD), schema: result_schema, }; let examples = vec![Example::from_rpc_with_params::<T>()]; let method = Method { name: T::METHOD.to_string(), summary: summary.to_string(), params, result, examples, }; self.methods.push(method); self.update_schemas::<T::RequestParams>(); self.update_schemas::<T::ResponseResult>(); } fn push_without_params<T: RpcWithoutParams>(&mut self, summary: &str) { let mut generator = Self::new_generator(); let result_schema = T::ResponseResult::json_schema(&mut generator); let result = ResponseResult { name: format!("{}_result", T::METHOD), schema: result_schema, }; let examples = vec![Example::from_rpc_without_params::<T>()]; let method = Method { name: T::METHOD.to_string(), summary: summary.to_string(), params: vec![], result, examples, }; self.methods.push(method); self.update_schemas::<T::ResponseResult>(); } fn push_with_optional_params<T: RpcWithOptionalParams>(&mut self, summary: &str) { let mut generator = Self::new_generator(); let params_schema = T::OptionalRequestParams::json_schema(&mut generator); let params = Self::make_params(params_schema); let result_schema = T::ResponseResult::json_schema(&mut generator); let result = ResponseResult { name: format!("{}_result", T::METHOD), schema: result_schema, }; let examples = vec![Example::from_rpc_with_optional_params::<T>()]; let method = Method { name: T::METHOD.to_string(), summary: summary.to_string(), params, result, examples, }; self.methods.push(method); self.update_schemas::<T::OptionalRequestParams>(); self.update_schemas::<T::ResponseResult>(); } fn make_params(schema: Schema) -> Vec<SchemaParam> { let schema_object = schema.into_object().object.expect("should be object"); let mut required_params = schema_object .properties .iter() .filter(|(name, _)| schema_object.required.contains(*name)) .map(|(name, schema)| SchemaParam { name: name.clone(), schema: schema.clone(), required: true, }) .collect::<Vec<_>>(); let optional_params = schema_object .properties .iter() .filter(|(name, _)| !schema_object.required.contains(*name)) .map(|(name, schema)| SchemaParam { name: name.clone(), schema: schema.clone(), required: false, }) .collect::<Vec<_>>(); required_params.extend(optional_params); required_params } fn update_schemas<S: JsonSchema>(&mut self) { let generator = Self::new_generator(); let mut root_schema = generator.into_root_schema_for::<S>(); for (key, value) in root_schema.definitions.drain(..) { match self.components.schemas.entry(key) { MapEntry::Occupied(current_value) => { assert_eq!( current_value.get().clone().into_object().metadata, value.into_object().metadata ) } MapEntry::Vacant(vacant) => { let _ = vacant.insert(value); } } } } } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcInfoField { version: String, title: String, description: String, contact: OpenRpcContactField, license: OpenRpcLicenseField, } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcContactField { name: String, url: String, } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcLicenseField { name: String, url: String, } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcServerEntry { name: String, url: String, } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct Method { name: String, summary: String, params: Vec<SchemaParam>, result: ResponseResult, examples: Vec<Example>, } #[derive(Clone, Serialize, Deserialize, Debug)] struct SchemaParam { name: String, schema: Schema, required: bool, } #[derive(Clone, Serialize, Deserialize, Debug)] struct ResponseResult { name: String, schema: Schema, } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct Example { name: String, params: Vec<ExampleParam>, result: ExampleResult, } impl Example { fn new(method_name: &str, maybe_params_obj: Option<Value>, result_value: Value) -> Self { let params = match maybe_params_obj { Some(params_obj) => params_obj .as_object() .unwrap() .iter() .map(|(name, value)| ExampleParam { name: name.clone(), value: value.clone(), }) .collect(), None => vec![], }; Example { name: format!("{}_example", method_name), params, result: ExampleResult { name: format!("{}_example_result", method_name), value: result_value, }, } } fn from_rpc_with_params<T: RpcWithParams>() -> Self { Self::new( T::METHOD, Some(json!(T::RequestParams::doc_example())), json!(T::ResponseResult::doc_example()), ) } fn from_rpc_without_params<T: RpcWithoutParams>() -> Self { Self::new(T::METHOD, None, json!(T::ResponseResult::doc_example())) } fn from_rpc_with_optional_params<T: RpcWithOptionalParams>() -> Self { Self::new( T::METHOD, Some(json!(T::OptionalRequestParams::doc_example())), json!(T::ResponseResult::doc_example()), ) } } #[derive(Clone, Serialize, Deserialize, Debug)] struct ExampleParam { name: String, value: Value, } #[derive(Clone, Serialize, Deserialize, Debug)] struct ExampleResult { name: String, value: Value, } #[derive(Clone, Serialize, Deserialize, Debug)] struct Components { schemas: Map<String, Schema>, } #[derive(Clone, Serialize, Deserialize, JsonSchema, Debug)] #[serde(deny_unknown_fields)] pub struct ListRpcsResult { #[schemars(with = "String")] api_version: Version, name: String, #[schemars(skip)] schema: OpenRpcSchema, } impl DocExample for ListRpcsResult { fn doc_example() -> &'static Self { &*LIST_RPCS_RESULT } } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct ListRpcs {} impl RpcWithoutParams for ListRpcs { const METHOD: &'static str = "rpc.discover"; type ResponseResult = ListRpcsResult; } impl RpcWithoutParamsExt for ListRpcs { fn handle_request<REv: ReactorEventT>( _effect_builder: EffectBuilder<REv>, response_builder: Builder, _api_version: Version, ) -> BoxFuture<'static, Result<Response<Body>, Error>> { async move { Ok(response_builder.success(ListRpcsResult::doc_example().clone())?) }.boxed() } } #[cfg(test)] mod tests { use crate::{types::Chainspec, utils::Loadable}; use super::*; #[test] fn check_docs_example_version() { let chainspec = Chainspec::from_resources("production"); assert_eq!( *DOCS_EXAMPLE_PROTOCOL_VERSION, chainspec.protocol_config.version, "DOCS_EXAMPLE_VERSION needs to be updated to match the [protocol.version] in \ 'resources/production/chainspec.toml'" ); } }
#![allow(clippy::field_reassign_with_default)] use futures::{future::BoxFuture, FutureExt}; use http::Response; use hyper::Body; use once_cell::sync::Lazy; use schemars::{ gen::{SchemaGenerator, SchemaSettings}, schema::Schema, JsonSchema, Map, MapEntry, }; use semver::Version; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use warp_json_rpc::Builder; use super::{ account::PutDeploy, chain::{GetBlock, GetBlockTransfers, GetStateRootHash}, info::{GetDeploy, GetPeers, GetStatus}, state::{GetAuctionInfo, GetBalance, GetItem}, Error, ReactorEventT, RpcWithOptionalParams, RpcWithParams, RpcWithoutParams, RpcWithoutParamsExt, }; use crate::{effect::EffectBuilder, rpcs::chain::GetEraInfoBySwitchBlock}; pub(crate) static DOCS_EXAMPLE_PROTOCOL_VERSION: Lazy<Version> = Lazy::new(|| Version::new(1, 1, 2)); const DEFINITIONS_PATH: &str = "#/components/schemas/"; static OPEN_RPC_SCHEMA: Lazy<OpenRpcSchema> = Lazy::new(|| { let contact = OpenRpcContactField { name: "CasperLabs".to_string(), url: "https://casperlabs.io".to_string(), }; let license = OpenRpcLicenseField { name: "CasperLabs Open Source License Version 1.0".to_string(), url: "https://raw.githubusercontent.com/CasperLabs/casper-node/master/LICENSE".to_string(), }; let info = OpenRpcInfoField { version: DOCS_EXAMPLE_PROTOCOL_VERSION.to_string(), title: "Client API of Casper Node".to_string(), description: "This describes the JSON-RPC 2.0 API of a node on the Casper network." .to_string(), contact, license, }; let server = OpenRpcServerEntry { name: "any Casper Network node".to_string(), url: "http://IP:PORT/rpc/".to_string(), }; let mut schema = OpenRpcSchema { openrpc: "1.0.0-rc1".to_string(), info, servers: vec![server], methods: vec![], components: Components { schemas: Map::new(), }, }; schema.push_with_params::<PutDeploy>("receives a Deploy to be executed by the network"); schema.push_with_params::<GetDeploy>("returns a Deploy from the network"); schema.push_without_params::<GetPeers>("returns a list of peers connected to the node"); schema.push_without_params::<GetStatus>("returns the current status of the node"); schema.push_with_optional_params::<GetBlock>("returns a Block from the network"); schema.push_with_optional_params::<GetBlockTransfers>( "returns all transfers for a Block from the network", ); schema.push_with_optional_params::<GetStateRootHash>( "returns a state root hash at a given Block", ); schema.push_with_params::<GetItem>("returns a stored value from the network"); schema.push_with_params::<GetBalance>("returns a purse's balance from the network"); schema.push_with_optional_params::<GetEraInfoBySwitchBlock>( "returns an EraInfo from the network", ); schema.push_without_params::<GetAuctionInfo>( "returns the bids and validators as of the most recently added Block", ); schema }); static LIST_RPCS_RESULT: Lazy<ListRpcsResult> = Lazy::new(|| ListRpcsResult { api_version: DOCS_EXAMPLE_PROTOCOL_VERSION.clone(), name: "OpenRPC Schema".to_string(), schema: OPEN_RPC_SCHEMA.clone(), }); pub trait DocExample { fn doc_example() -> &'static Self; } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcSchema { openrpc: String, info: OpenRpcInfoField, servers: Vec<OpenRpcServerEntry>, methods: Vec<Method>, components: Components, } impl OpenRpcSchema { fn new_generator() -> SchemaGenerator { let settings = SchemaSettings::default().with(|settings| { settings.definitions_path = DEFINITIONS_PATH.to_string(); }); settings.into_generator() } fn push_with_params<T: RpcWithParams>(&mut self, summary: &str) { let mut generator = Self::new_generator(); let params_schema = T::RequestParams::json_schema(&mut generator); let params = Self::make_params(params_schema); let result_schema = T::ResponseResult::json_schema(&mut generator); let result = ResponseResult { name: format!("{}_result", T::METHOD), schema: result_schema, }; let examples = vec![Example::from_rpc_with_params::<T>()]; let method = Method { name: T::METHOD.to_string(), summary: summary.to_string(), params, result, examples, }; self.methods.push(method); self.update_schemas::<T::RequestParams>(); self.update_schemas::<T::ResponseResult>(); } fn push_without_params<T: RpcWithoutParams>(&mut self, summary: &str) { let mut generator = Self::new_generator(); let result_schema = T::ResponseResult::json_schema(&mut generator); let result = ResponseResult { name: format!("{}_result", T::METHOD), schema: result_schema, }; let examples = vec![Example::from_rpc_without_params::<T>()]; let method = Method { name: T::METHOD.to_string(), summary: summary.to_string(), params: vec![], result, examples, }; self.methods.push(method); self.update_schemas::<T::ResponseResult>(); } fn push_with_optional_params<T: RpcWithOptionalParams>(&mut self, summary: &str) { let mut generator = Self::new_generator(); let params_schema = T::OptionalRequestParams::json_schema(&mut generator); let params = Self::make_params(params_schema); let result_schema = T::ResponseResult::json_schema(&mut generator); let result = ResponseResult { name: format!("{}_result", T::METHOD), schema: result_schema, }; let examples = vec![Example::from_rpc_with_optional_params::<T>()]; let method = Method { name: T::METHOD.to_string(), summary: summary.to_string(), params, result, examples, }; self.methods.push(method); self.update_schemas::<T::OptionalRequestParams>(); self.update_schemas::<T::ResponseResult>(); } fn make_params(schema: Schema) -> Vec<SchemaParam> { let schema_object = schema.into_object().object.expect("should be object"); let mut required_params = schema_object .properties .iter() .filter(|(name, _)| schema_object.required.contains(*name)) .map(|(name, schema)| SchemaParam { name: name.clone(), schema: schema.clone(), required: true, }) .collect::<Vec<_>>(); let optional_params = schema_object .properties .iter() .filter(|(name, _)| !schema_object.required.contains(*name)) .map(|(name, schema)| SchemaParam { name: name.clone(), schema: schema.clone(), required: false, }) .collect::<Vec<_>>(); required_params.extend(optional_params); required_params } fn update_schemas<S: JsonSchema>(&mut self) { let generator = Self::new_generator(); let mut root_schema = generator.into_root_schema_for::<S>(); for (key, value) in root_schema.definitions.drain(..) { match self.components.schemas.entry(key) { MapEntry::Occupied(current_value) => { assert_eq!( current_value.get().clone().into_object().metadata, value.into_object().metadata ) } MapEntry::Vacant(vacant) => { let _ = vacant.insert(value); } } } } } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcInfoField { version: String, title: String, description: String, contact: OpenRpcContactField, license: OpenRpcLicenseField, } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcContactField { name: String, url: String, } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcLicenseField { name: String, url: String, } #[derive(Clone, Serialize, Deserialize, Debug)] struct OpenRpcServerEntry { name: String, url: String, } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct Method { name: String, summary: String, params: Vec<SchemaParam>, result: ResponseResult, examples: Vec<Example>, } #[derive(Clone, Serialize, Deserialize, Debug)] struct SchemaParam { name: String, schema: Schema, required: bool, } #[derive(Clone, Serialize, Deserialize, Debug)] struct ResponseResult { name: String, schema: Schema, } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct Example { name: String, params: Vec<ExampleParam>, result: ExampleResult, } impl Example { fn new(method_name: &str, maybe_params_obj: Option<Value>, result_value: Value) -> Self { let params =
; Example { name: format!("{}_example", method_name), params, result: ExampleResult { name: format!("{}_example_result", method_name), value: result_value, }, } } fn from_rpc_with_params<T: RpcWithParams>() -> Self { Self::new( T::METHOD, Some(json!(T::RequestParams::doc_example())), json!(T::ResponseResult::doc_example()), ) } fn from_rpc_without_params<T: RpcWithoutParams>() -> Self { Self::new(T::METHOD, None, json!(T::ResponseResult::doc_example())) } fn from_rpc_with_optional_params<T: RpcWithOptionalParams>() -> Self { Self::new( T::METHOD, Some(json!(T::OptionalRequestParams::doc_example())), json!(T::ResponseResult::doc_example()), ) } } #[derive(Clone, Serialize, Deserialize, Debug)] struct ExampleParam { name: String, value: Value, } #[derive(Clone, Serialize, Deserialize, Debug)] struct ExampleResult { name: String, value: Value, } #[derive(Clone, Serialize, Deserialize, Debug)] struct Components { schemas: Map<String, Schema>, } #[derive(Clone, Serialize, Deserialize, JsonSchema, Debug)] #[serde(deny_unknown_fields)] pub struct ListRpcsResult { #[schemars(with = "String")] api_version: Version, name: String, #[schemars(skip)] schema: OpenRpcSchema, } impl DocExample for ListRpcsResult { fn doc_example() -> &'static Self { &*LIST_RPCS_RESULT } } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct ListRpcs {} impl RpcWithoutParams for ListRpcs { const METHOD: &'static str = "rpc.discover"; type ResponseResult = ListRpcsResult; } impl RpcWithoutParamsExt for ListRpcs { fn handle_request<REv: ReactorEventT>( _effect_builder: EffectBuilder<REv>, response_builder: Builder, _api_version: Version, ) -> BoxFuture<'static, Result<Response<Body>, Error>> { async move { Ok(response_builder.success(ListRpcsResult::doc_example().clone())?) }.boxed() } } #[cfg(test)] mod tests { use crate::{types::Chainspec, utils::Loadable}; use super::*; #[test] fn check_docs_example_version() { let chainspec = Chainspec::from_resources("production"); assert_eq!( *DOCS_EXAMPLE_PROTOCOL_VERSION, chainspec.protocol_config.version, "DOCS_EXAMPLE_VERSION needs to be updated to match the [protocol.version] in \ 'resources/production/chainspec.toml'" ); } }
match maybe_params_obj { Some(params_obj) => params_obj .as_object() .unwrap() .iter() .map(|(name, value)| ExampleParam { name: name.clone(), value: value.clone(), }) .collect(), None => vec![], }
if_condition
[ { "content": "fn dependencies(values: &[&str]) -> Result<Vec<DeployHash>> {\n\n let mut hashes = Vec::with_capacity(values.len());\n\n for value in values {\n\n let digest = Digest::from_hex(value).map_err(|error| Error::CryptoError {\n\n context: \"dependencies\",\n\n error,\...
Rust
src/poller.rs
dwrensha/multipoll
91eddb3bf9281c5d300efbef9a7b605a3e1a0122
use std::pin::Pin; use std::task::{Context, Poll}; use futures::{Future, FutureExt, Stream}; use futures::stream::FuturesUnordered; use futures::channel::mpsc; use std::cell::{RefCell}; use std::rc::Rc; enum EnqueuedTask<E> { Task(Pin<Box<dyn Future<Output=Result<(), E>>>>), Terminate(Result<(), E>), } enum TaskInProgress<E> { Task(Pin<Box<dyn Future<Output=()>>>), Terminate(Option<Result<(), E>>), } impl <E> Unpin for TaskInProgress<E> {} enum TaskDone<E> { Continue, Terminate(Result<(), E>), } impl <E> Future for TaskInProgress<E> { type Output = TaskDone<E>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { match *self { TaskInProgress::Terminate(ref mut r) => Poll::Ready(TaskDone::Terminate(r.take().unwrap())), TaskInProgress::Task(ref mut f) => { match f.as_mut().poll(cx) { Poll::Pending => Poll::Pending, Poll::Ready(()) => Poll::Ready(TaskDone::Continue), } } } } } #[must_use = "a Poller does nothing unless polled"] pub struct Poller<E> { enqueued: Option<mpsc::UnboundedReceiver<EnqueuedTask<E>>>, in_progress: FuturesUnordered<TaskInProgress<E>>, reaper: Rc<RefCell<Box<dyn Finisher<E>>>>, } impl<E> Poller<E> where E: 'static { pub fn new(reaper: Box<dyn Finisher<E>>) -> (PollerHandle<E>, Poller<E>) where E: 'static, E: ::std::fmt::Debug, { let (sender, receiver) = mpsc::unbounded(); let set = Poller { enqueued: Some(receiver), in_progress: FuturesUnordered::new(), reaper: Rc::new(RefCell::new(reaper)), }; set.in_progress.push(TaskInProgress::Task(Box::pin(::futures::future::pending()))); let handle = PollerHandle { sender: sender, }; (handle, set) } } #[derive(Clone)] pub struct PollerHandle<E> { sender: mpsc::UnboundedSender<EnqueuedTask<E>> } impl <E> PollerHandle<E> where E: 'static { pub fn add<F>(&mut self, f: F) where F: Future<Output = Result<(), E>> + 'static { let _ = self.sender.unbounded_send(EnqueuedTask::Task(Box::pin(f))); } pub fn terminate(&mut self, result: Result<(), E>) { let _ = self.sender.unbounded_send(EnqueuedTask::Terminate(result)); } } pub trait Finisher<E> where E: 'static { fn task_succeeded(&mut self) {} fn task_failed(&mut self, error: E); } impl <E> Future for Poller<E> where E: 'static { type Output = Result<(),E>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let mut enqueued_stream_complete = false; if let Poller { enqueued: Some(ref mut enqueued), ref mut in_progress, ref reaper, ..} = self.as_mut().get_mut() { loop { match Pin::new(&mut *enqueued).poll_next(cx) { Poll::Pending => break, Poll::Ready(None) => { enqueued_stream_complete = true; break; } Poll::Ready(Some(EnqueuedTask::Terminate(r))) => { in_progress.push(TaskInProgress::Terminate(Some(r))); } Poll::Ready(Some(EnqueuedTask::Task(f))) => { let reaper = Rc::downgrade(&reaper); in_progress.push( TaskInProgress::Task(Box::pin( f.map(move |r| { match reaper.upgrade() { None => (), Some(rc_reaper) => { match r { Ok(()) => rc_reaper.borrow_mut().task_succeeded(), Err(e) => rc_reaper.borrow_mut().task_failed(e), } } } })))); } } } } if enqueued_stream_complete { drop(self.enqueued.take()); } loop { match Stream::poll_next(Pin::new(&mut self.in_progress), cx) { Poll::Pending => return Poll::Pending, Poll::Ready(v) => { match v { None => return Poll::Ready(Ok(())), Some(TaskDone::Continue) => (), Some(TaskDone::Terminate(Ok(()))) => return Poll::Ready(Ok(())), Some(TaskDone::Terminate(Err(e))) => return Poll::Ready(Err(e)), } } } } } }
use std::pin::Pin; use std::task::{Context, Poll}; use futures::{Future, FutureExt, Stream}; use futures::stream::FuturesUnordered; use futures::channel::mpsc; use std::cell::{RefCell}; use std::rc::Rc; enum EnqueuedTask<E> { Task(Pin<Box<dyn Future<Output=Result<(), E>>>>), Terminate(Result<(), E>), } enum TaskInProgress<E> { Task(Pin<Box<dyn Future<Output=()>>>), Terminate(Option<Result<(), E>>), } impl <E> Unpin for TaskInProgress<E> {} enum TaskDone<E> { Continue, Terminate(Result<(), E>), } impl <E> Future for TaskInProgress<E> { type Output = TaskDone<E>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { match *self { TaskInProgress::Terminate(ref mut r) => Poll::Ready(TaskDone::Terminate(r.take().unwrap())), TaskInProgress::Task(ref mut f) => { match f.as_mut().poll(cx) { Poll::Pending => Poll::Pending, Poll::Ready(()) => Poll::Ready(TaskDone::Continue), } } } } } #[must_use = "a Poller does nothing unless polled"] pub struct Poller<E> { enqueued: Option<mpsc::UnboundedReceiver<EnqueuedTask<E>>>, in_progress: FuturesUnordered<TaskInProgress<E>>, reaper: Rc<RefCell<Box<dyn Finisher<E>>>>, } impl<E> Poller<E> where E: 'static { pub fn new(reaper: Box<dyn Finisher<E>>) -> (PollerHandle<E>, Poller<E>) where E: 'static, E: ::std::fmt::Debug, { let (sender, receiver) = mpsc::unbounded(); let set = Poller { enqueued: Some(receiver), in_progress: FuturesUnordered::new(), reaper: Rc::new(RefCell::new(reaper)), }; set.in_progress.push(TaskInProgress::Task(Box::pin(::futures::future::pending()))); let handle = PollerHandle { sender: sender, }; (handle, set) } } #[derive(Clone)] pub struct PollerHandle<E> { sender: mpsc::UnboundedSender<EnqueuedTask<E>> } impl <E> PollerHandle<E> where E: 'static { pub fn add<F>(&mut self, f: F) where F: Future<Output = Result<(), E>> + 'static { let _ = self.sender.unbounded_send(EnqueuedTask::Task(Box::pin(f))); } pub fn terminate(&mut self, result: Result<(), E>) { let _ = self.sender.unbounded_send(EnqueuedTask::Terminate(result)); } } pub trait Finisher<E> where E: 'static { fn task_succeeded(&mut self) {} fn task_failed(&mut self, error: E); } impl <E> Future for Pol
ueued_stream_complete = true; break; } Poll::Ready(Some(EnqueuedTask::Terminate(r))) => { in_progress.push(TaskInProgress::Terminate(Some(r))); } Poll::Ready(Some(EnqueuedTask::Task(f))) => { let reaper = Rc::downgrade(&reaper); in_progress.push( TaskInProgress::Task(Box::pin( f.map(move |r| { match reaper.upgrade() { None => (), Some(rc_reaper) => { match r { Ok(()) => rc_reaper.borrow_mut().task_succeeded(), Err(e) => rc_reaper.borrow_mut().task_failed(e), } } } })))); } } } } if enqueued_stream_complete { drop(self.enqueued.take()); } loop { match Stream::poll_next(Pin::new(&mut self.in_progress), cx) { Poll::Pending => return Poll::Pending, Poll::Ready(v) => { match v { None => return Poll::Ready(Ok(())), Some(TaskDone::Continue) => (), Some(TaskDone::Terminate(Ok(()))) => return Poll::Ready(Ok(())), Some(TaskDone::Terminate(Err(e))) => return Poll::Ready(Err(e)), } } } } } }
ler<E> where E: 'static { type Output = Result<(),E>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let mut enqueued_stream_complete = false; if let Poller { enqueued: Some(ref mut enqueued), ref mut in_progress, ref reaper, ..} = self.as_mut().get_mut() { loop { match Pin::new(&mut *enqueued).poll_next(cx) { Poll::Pending => break, Poll::Ready(None) => { enq
random
[ { "content": "multipoll\n\n=========\n\n\n", "file_path": "README.md", "rank": 4, "score": 7310.110037664616 }, { "content": "extern crate futures;\n\n\n\npub use poller::{Poller, PollerHandle, Finisher};\n\n\n\nmod poller;\n", "file_path": "src/lib.rs", "rank": 11, "score": 6.24...
Rust
src/contract.rs
SivaS2003/cw-template
2d75e09e2a9dfd65813bcfd71fa54fb888df33f7
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Coin, BankMsg, has_coins}; use cosmwasm_std::Addr; use cw2::set_contract_version; use crate::error::ContractError; use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg, AddressResponse, CostResponse, OwnerResponse}; use crate::state::{State, STATE}; const CONTRACT_NAME: &str = "crates.io:{{project-name}}"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, info: MessageInfo, msg: InstantiateMsg, ) -> Result<Response, ContractError> { let state = State { address : msg.address, rentcost : msg.rentcost, renters : Vec::new(), owner : info.sender.clone(), ownername : msg.ownername, }; set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; STATE.save(deps.storage, &state)?; Ok(Response::new() .add_attribute("method", "instantiate") .add_attribute("owner", info.sender) .add_attribute("address", msg.address)) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::RenterAdd {} => try_add(deps, env, info), ExecuteMsg::RenterPay {} => try_pay(deps, env, info), ExecuteMsg::RenterBoot {} => try_boot(deps, info), ExecuteMsg::ChangeRent {newprice} => try_ChangeRent(deps, info, newprice), } } pub fn try_add(deps: DepsMut, env: Env, info: MessageInfo) -> Result<Response, ContractError> { STATE.update(deps.storage, |mut state| -> Result<_, ContractError> { state.renters.push(env.contract.address); Ok(state) })?; Ok(Response::new().add_attribute("method", "try_add")) } pub fn try_pay( deps: DepsMut, env: Env, info: MessageInfo, ) -> Result<Response, ContractError> { STATE.update(deps.storage, |mut state| -> Result<_, ContractError> { if has_coins(&info.funds, &state.rentcost){ let send = BankMsg::Send { to_address: state.owner.into_string(), amount: info.funds, }; } Ok(state) })?; Ok(Response::new().add_attribute("method", "try_pay")) } pub fn try_boot(deps: DepsMut, info: MessageInfo) -> Result<Response, ContractError> { STATE.update(deps.storage, |mut state| -> Result<_, ContractError> { if info.sender != state.owner { return Err(ContractError::Unauthorized{}); } state.renters.pop(); Ok(state) })?; Ok(Response::new().add_attribute("method", "try_boot")) } pub fn try_ChangeRent(deps: DepsMut, info: MessageInfo, newprice: Vec<Coin>) -> Result<Response, ContractError> { STATE.update(deps.storage, |mut state| -> Result<_, ContractError> { if info.sender != state.owner { return Err(ContractError::Unauthorized{}); } state.rentcost = newprice; Ok(state) })?; Ok(Response::new()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::GetAddress {} => to_binary(&query_address(deps)?), QueryMsg::GetRentCost {} => to_binary(&query_rent(deps)?), QueryMsg::GetOwner {} => to_binary(&query_owner(deps)?), } } fn query_address(deps: Deps) -> StdResult<AddressResponse> { let state = STATE.load(deps.storage)?; Ok(AddressResponse { address: state.address }) } fn query_rent(deps: Deps) -> StdResult<CostResponse> { let state = STATE.load(deps.storage)?; Ok(CostResponse {rentcost: state.rentcost}) } fn query_owner(deps: Deps) -> StdResult<OwnerResponse> { let state = STATE.load(deps.storage)?; Ok(OwnerResponse {ownername : state.ownername}) } #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies_with_balance, mock_env, mock_info}; use cosmwasm_std::{coins, from_binary}; #[test] fn proper_initialization() { let mut deps = mock_dependencies_with_balance(&coins(2, "token")); let msg = InstantiateMsg { address: String::from("33 pawn lane"), rentcost: coins(10, "luna"), renters : Vec::new(), ownername: String::from("john doe") }; let info = mock_info("landlord", &coins(0, "luna")); let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); let res = query(deps.as_ref(), mock_env(), QueryMsg::GetAddress {}).unwrap(); let value: AddressResponse = from_binary(&res).unwrap(); assert_eq!(String::from("33 pawn lane"), value.address); let res = query(deps.as_ref(), mock_env(), QueryMsg::GetRentCost {}).unwrap(); let value: CostResponse = from_binary(&res).unwrap(); assert_eq!(coins(10, "luna"), value.rentcost); let res = query(deps.as_ref(), mock_env(), QueryMsg::GetRentCost {}).unwrap(); let value: OwnerResponse = from_binary(&res).unwrap(); assert_eq!(String::from("john doe"), value.ownername); } #[test] fn renters() { let mut deps = mock_dependencies_with_balance(&coins(2, "token")); let msg = InstantiateMsg { address: String::from("33 pawn lane"), rentcost: coins(10, "luna"), renters : Vec::new(), ownername: String::from("john doe") }; let info = mock_info("landlord", &coins(0, "luna")); let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let info2 = mock_info("jane doe", &coins(2, "luna")); let msg = ExecuteMsg::RenterAdd {}; let _res = execute(deps.as_mut(), mock_env(), info2, msg).unwrap(); let info3 = mock_info("jaja doe", &coins(3, "luna")); let msg = ExecuteMsg::RenterBoot {}; let res = execute(deps.as_mut(), mock_env(), info3, msg); match res { Err(ContractError::Unauthorized {}) => {} _ => panic!("Must return unauthorized error"), } } }
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Coin, BankMsg, has_coins}; use cosmwasm_std::Addr; use cw2::set_contract_version; use crate::error::ContractError; use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg, AddressResponse, CostResponse, OwnerResponse}; use crate::state::{State, STATE}; const CONTRACT_NAME: &str = "crates.io:{{project-name}}"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, info: MessageInfo, msg: InstantiateMsg, ) -> Result<Response, ContractError> { let state = State { address : msg.address, rentcost : msg.rentcost, renters : Vec::new(), owner : info.sender.clone(), ownername : msg.ownername, }; set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; STATE.save(deps.storage, &state)?;
} #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::RenterAdd {} => try_add(deps, env, info), ExecuteMsg::RenterPay {} => try_pay(deps, env, info), ExecuteMsg::RenterBoot {} => try_boot(deps, info), ExecuteMsg::ChangeRent {newprice} => try_ChangeRent(deps, info, newprice), } } pub fn try_add(deps: DepsMut, env: Env, info: MessageInfo) -> Result<Response, ContractError> { STATE.update(deps.storage, |mut state| -> Result<_, ContractError> { state.renters.push(env.contract.address); Ok(state) })?; Ok(Response::new().add_attribute("method", "try_add")) } pub fn try_pay( deps: DepsMut, env: Env, info: MessageInfo, ) -> Result<Response, ContractError> { STATE.update(deps.storage, |mut state| -> Result<_, ContractError> { if has_coins(&info.funds, &state.rentcost){ let send = BankMsg::Send { to_address: state.owner.into_string(), amount: info.funds, }; } Ok(state) })?; Ok(Response::new().add_attribute("method", "try_pay")) } pub fn try_boot(deps: DepsMut, info: MessageInfo) -> Result<Response, ContractError> { STATE.update(deps.storage, |mut state| -> Result<_, ContractError> { if info.sender != state.owner { return Err(ContractError::Unauthorized{}); } state.renters.pop(); Ok(state) })?; Ok(Response::new().add_attribute("method", "try_boot")) } pub fn try_ChangeRent(deps: DepsMut, info: MessageInfo, newprice: Vec<Coin>) -> Result<Response, ContractError> { STATE.update(deps.storage, |mut state| -> Result<_, ContractError> { if info.sender != state.owner { return Err(ContractError::Unauthorized{}); } state.rentcost = newprice; Ok(state) })?; Ok(Response::new()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::GetAddress {} => to_binary(&query_address(deps)?), QueryMsg::GetRentCost {} => to_binary(&query_rent(deps)?), QueryMsg::GetOwner {} => to_binary(&query_owner(deps)?), } } fn query_address(deps: Deps) -> StdResult<AddressResponse> { let state = STATE.load(deps.storage)?; Ok(AddressResponse { address: state.address }) } fn query_rent(deps: Deps) -> StdResult<CostResponse> { let state = STATE.load(deps.storage)?; Ok(CostResponse {rentcost: state.rentcost}) } fn query_owner(deps: Deps) -> StdResult<OwnerResponse> { let state = STATE.load(deps.storage)?; Ok(OwnerResponse {ownername : state.ownername}) } #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies_with_balance, mock_env, mock_info}; use cosmwasm_std::{coins, from_binary}; #[test] fn proper_initialization() { let mut deps = mock_dependencies_with_balance(&coins(2, "token")); let msg = InstantiateMsg { address: String::from("33 pawn lane"), rentcost: coins(10, "luna"), renters : Vec::new(), ownername: String::from("john doe") }; let info = mock_info("landlord", &coins(0, "luna")); let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); let res = query(deps.as_ref(), mock_env(), QueryMsg::GetAddress {}).unwrap(); let value: AddressResponse = from_binary(&res).unwrap(); assert_eq!(String::from("33 pawn lane"), value.address); let res = query(deps.as_ref(), mock_env(), QueryMsg::GetRentCost {}).unwrap(); let value: CostResponse = from_binary(&res).unwrap(); assert_eq!(coins(10, "luna"), value.rentcost); let res = query(deps.as_ref(), mock_env(), QueryMsg::GetRentCost {}).unwrap(); let value: OwnerResponse = from_binary(&res).unwrap(); assert_eq!(String::from("john doe"), value.ownername); } #[test] fn renters() { let mut deps = mock_dependencies_with_balance(&coins(2, "token")); let msg = InstantiateMsg { address: String::from("33 pawn lane"), rentcost: coins(10, "luna"), renters : Vec::new(), ownername: String::from("john doe") }; let info = mock_info("landlord", &coins(0, "luna")); let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap(); let info2 = mock_info("jane doe", &coins(2, "luna")); let msg = ExecuteMsg::RenterAdd {}; let _res = execute(deps.as_mut(), mock_env(), info2, msg).unwrap(); let info3 = mock_info("jaja doe", &coins(3, "luna")); let msg = ExecuteMsg::RenterBoot {}; let res = execute(deps.as_mut(), mock_env(), info3, msg); match res { Err(ContractError::Unauthorized {}) => {} _ => panic!("Must return unauthorized error"), } } }
Ok(Response::new() .add_attribute("method", "instantiate") .add_attribute("owner", info.sender) .add_attribute("address", msg.address))
call_expression
[ { "content": "fn main() {\n\n let mut out_dir = current_dir().unwrap();\n\n out_dir.push(\"schema\");\n\n create_dir_all(&out_dir).unwrap();\n\n remove_schemas(&out_dir).unwrap();\n\n\n\n export_schema(&schema_for!(InstantiateMsg), &out_dir);\n\n export_schema(&schema_for!(ExecuteMsg), &out_di...
Rust
src/asm/x86/predict.rs
kevleyski/rav1e
d9492a21b007eea38fa5a1409249e75502dfafa6
use crate::context::MAX_TX_SIZE; use crate::cpu_features::CpuFeatureLevel; use crate::predict::{ rust, IntraEdgeFilterParameters, PredictionMode, PredictionVariant, }; use crate::tiling::PlaneRegionMut; use crate::transform::TxSize; use crate::util::Aligned; use crate::Pixel; use v_frame::pixel::PixelType; macro_rules! decl_angular_ipred_fn { ($($f:ident),+) => { extern { $( fn $f( dst: *mut u8, stride: libc::ptrdiff_t, topleft: *const u8, width: libc::c_int, height: libc::c_int, angle: libc::c_int, ); )* } }; } decl_angular_ipred_fn! { rav1e_ipred_dc_avx2, rav1e_ipred_dc_ssse3, rav1e_ipred_dc_128_avx2, rav1e_ipred_dc_128_ssse3, rav1e_ipred_dc_left_avx2, rav1e_ipred_dc_left_ssse3, rav1e_ipred_dc_top_avx2, rav1e_ipred_dc_top_ssse3, rav1e_ipred_v_avx2, rav1e_ipred_v_ssse3, rav1e_ipred_h_avx2, rav1e_ipred_h_ssse3, rav1e_ipred_z1_avx2, rav1e_ipred_z3_avx2, rav1e_ipred_smooth_avx2, rav1e_ipred_smooth_ssse3, rav1e_ipred_smooth_v_avx2, rav1e_ipred_smooth_v_ssse3, rav1e_ipred_smooth_h_avx2, rav1e_ipred_smooth_h_ssse3, rav1e_ipred_paeth_avx2, rav1e_ipred_paeth_ssse3 } macro_rules! decl_angular_ipred_hbd_fn { ($($f:ident),+) => { extern { $( fn $f( dst: *mut u16, stride: libc::ptrdiff_t, topleft: *const u16, width: libc::c_int, height: libc::c_int, angle: libc::c_int, max_width: libc::c_int, max_height: libc::c_int, bit_depth_max: libc::c_int, ); )* } }; } decl_angular_ipred_hbd_fn! { rav1e_ipred_dc_16bpc_avx2, rav1e_ipred_dc_128_16bpc_avx2, rav1e_ipred_dc_left_16bpc_avx2, rav1e_ipred_dc_top_16bpc_avx2, rav1e_ipred_v_16bpc_avx2, rav1e_ipred_h_16bpc_avx2, rav1e_ipred_z1_16bpc_avx2, rav1e_ipred_z3_16bpc_avx2, rav1e_ipred_smooth_16bpc_avx2, rav1e_ipred_smooth_v_16bpc_avx2, rav1e_ipred_smooth_h_16bpc_avx2, rav1e_ipred_paeth_16bpc_avx2 } extern { fn rav1e_ipred_z2_avx2( dst: *mut u8, stride: libc::ptrdiff_t, topleft: *const u8, width: libc::c_int, height: libc::c_int, angle: libc::c_int, dx: libc::c_int, dy: libc::c_int, ); fn rav1e_ipred_z2_16bpc_avx2( dst: *mut u16, stride: libc::ptrdiff_t, topleft: *const u16, width: libc::c_int, height: libc::c_int, angle: libc::c_int, dx: libc::c_int, dy: libc::c_int, bit_depth_max: libc::c_int, ); } macro_rules! decl_cfl_pred_fn { ($($f:ident),+) => { extern { $( fn $f( dst: *mut u8, stride: libc::ptrdiff_t, topleft: *const u8, width: libc::c_int, height: libc::c_int, ac: *const i16, alpha: libc::c_int, ); )* } }; } decl_cfl_pred_fn! { rav1e_ipred_cfl_avx2, rav1e_ipred_cfl_ssse3, rav1e_ipred_cfl_128_avx2, rav1e_ipred_cfl_128_ssse3, rav1e_ipred_cfl_left_avx2, rav1e_ipred_cfl_left_ssse3, rav1e_ipred_cfl_top_avx2, rav1e_ipred_cfl_top_ssse3 } macro_rules! decl_cfl_pred_hbd_fn { ($($f:ident),+) => { extern { $( fn $f( dst: *mut u16, stride: libc::ptrdiff_t, topleft: *const u16, width: libc::c_int, height: libc::c_int, ac: *const i16, alpha: libc::c_int, bit_depth_max: libc::c_int, ); )* } }; } decl_cfl_pred_hbd_fn! { rav1e_ipred_cfl_16bpc_avx2, rav1e_ipred_cfl_128_16bpc_avx2, rav1e_ipred_cfl_left_16bpc_avx2, rav1e_ipred_cfl_top_16bpc_avx2 } #[inline(always)] pub fn dispatch_predict_intra<T: Pixel>( mode: PredictionMode, variant: PredictionVariant, dst: &mut PlaneRegionMut<'_, T>, tx_size: TxSize, bit_depth: usize, ac: &[i16], angle: isize, ief_params: Option<IntraEdgeFilterParameters>, edge_buf: &Aligned<[T; 4 * MAX_TX_SIZE + 1]>, cpu: CpuFeatureLevel, ) { let call_rust = |dst: &mut PlaneRegionMut<'_, T>| { rust::dispatch_predict_intra( mode, variant, dst, tx_size, bit_depth, ac, angle, ief_params, edge_buf, cpu, ); }; unsafe { let stride = T::to_asm_stride(dst.plane_cfg.stride) as libc::ptrdiff_t; let w = tx_size.width() as libc::c_int; let h = tx_size.height() as libc::c_int; let angle = angle as libc::c_int; match T::type_enum() { PixelType::U8 if cpu >= CpuFeatureLevel::SSSE3 => { let dst_ptr = dst.data_ptr_mut() as *mut _; let edge_ptr = edge_buf.data.as_ptr().offset(2 * MAX_TX_SIZE as isize) as *const _; if cpu >= CpuFeatureLevel::AVX2 { match mode { PredictionMode::DC_PRED => { (match variant { PredictionVariant::NONE => rav1e_ipred_dc_128_avx2, PredictionVariant::LEFT => rav1e_ipred_dc_left_avx2, PredictionVariant::TOP => rav1e_ipred_dc_top_avx2, PredictionVariant::BOTH => rav1e_ipred_dc_avx2, })(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::V_PRED if angle == 90 => { rav1e_ipred_v_avx2(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::H_PRED if angle == 180 => { rav1e_ipred_h_avx2(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::V_PRED | PredictionMode::H_PRED | PredictionMode::D45_PRED | PredictionMode::D135_PRED | PredictionMode::D113_PRED | PredictionMode::D157_PRED | PredictionMode::D203_PRED | PredictionMode::D67_PRED => { let (enable_ief, ief_smooth_filter) = if let Some(params) = ief_params { ( true as libc::c_int, params.use_smooth_filter() as libc::c_int, ) } else { (false as libc::c_int, false as libc::c_int) }; let angle_arg = angle | (enable_ief << 10) | (ief_smooth_filter << 9); let (bw, bh) = ( ((dst.plane_cfg.width + 7) >> 3) << 3, ((dst.plane_cfg.height + 7) >> 3) << 3, ); let (dx, dy) = ( (bw as isize - dst.rect().x as isize) as libc::c_int, (bh as isize - dst.rect().y as isize) as libc::c_int, ); if angle <= 90 { rav1e_ipred_z1_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, ); } else if angle < 180 { rav1e_ipred_z2_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, dx, dy, ); } else { rav1e_ipred_z3_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, ); } } PredictionMode::SMOOTH_PRED => { rav1e_ipred_smooth_avx2(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::SMOOTH_V_PRED => { rav1e_ipred_smooth_v_avx2( dst_ptr, stride, edge_ptr, w, h, angle, ); } PredictionMode::SMOOTH_H_PRED => { rav1e_ipred_smooth_h_avx2( dst_ptr, stride, edge_ptr, w, h, angle, ); } PredictionMode::PAETH_PRED => { rav1e_ipred_paeth_avx2(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::UV_CFL_PRED => { let ac_ptr = ac.as_ptr() as *const _; (match variant { PredictionVariant::NONE => rav1e_ipred_cfl_128_avx2, PredictionVariant::LEFT => rav1e_ipred_cfl_left_avx2, PredictionVariant::TOP => rav1e_ipred_cfl_top_avx2, PredictionVariant::BOTH => rav1e_ipred_cfl_avx2, })(dst_ptr, stride, edge_ptr, w, h, ac_ptr, angle); } _ => call_rust(dst), } } else if cpu >= CpuFeatureLevel::SSSE3 { match mode { PredictionMode::DC_PRED => { (match variant { PredictionVariant::NONE => rav1e_ipred_dc_128_ssse3, PredictionVariant::LEFT => rav1e_ipred_dc_left_ssse3, PredictionVariant::TOP => rav1e_ipred_dc_top_ssse3, PredictionVariant::BOTH => rav1e_ipred_dc_ssse3, })(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::V_PRED if angle == 90 => { rav1e_ipred_v_ssse3(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::H_PRED if angle == 180 => { rav1e_ipred_h_ssse3(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::SMOOTH_PRED => { rav1e_ipred_smooth_ssse3(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::SMOOTH_V_PRED => { rav1e_ipred_smooth_v_ssse3( dst_ptr, stride, edge_ptr, w, h, angle, ); } PredictionMode::SMOOTH_H_PRED => { rav1e_ipred_smooth_h_ssse3( dst_ptr, stride, edge_ptr, w, h, angle, ); } PredictionMode::PAETH_PRED => { rav1e_ipred_paeth_ssse3(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::UV_CFL_PRED => { let ac_ptr = ac.as_ptr() as *const _; (match variant { PredictionVariant::NONE => rav1e_ipred_cfl_128_ssse3, PredictionVariant::LEFT => rav1e_ipred_cfl_left_ssse3, PredictionVariant::TOP => rav1e_ipred_cfl_top_ssse3, PredictionVariant::BOTH => rav1e_ipred_cfl_ssse3, })(dst_ptr, stride, edge_ptr, w, h, ac_ptr, angle); } _ => call_rust(dst), } } } PixelType::U16 if cpu >= CpuFeatureLevel::AVX2 => { let dst_ptr = dst.data_ptr_mut() as *mut _; let edge_ptr = edge_buf.data.as_ptr().offset(2 * MAX_TX_SIZE as isize) as *const _; let bd_max = (1 << bit_depth) - 1; match mode { PredictionMode::DC_PRED => { (match variant { PredictionVariant::NONE => rav1e_ipred_dc_128_16bpc_avx2, PredictionVariant::LEFT => rav1e_ipred_dc_left_16bpc_avx2, PredictionVariant::TOP => rav1e_ipred_dc_top_16bpc_avx2, PredictionVariant::BOTH => rav1e_ipred_dc_16bpc_avx2, })( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max ); } PredictionMode::V_PRED if angle == 90 => { rav1e_ipred_v_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::H_PRED if angle == 180 => { rav1e_ipred_h_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::V_PRED | PredictionMode::H_PRED | PredictionMode::D45_PRED | PredictionMode::D135_PRED | PredictionMode::D113_PRED | PredictionMode::D157_PRED | PredictionMode::D203_PRED | PredictionMode::D67_PRED => { let (enable_ief, ief_smooth_filter) = if let Some(params) = ief_params { (true as libc::c_int, params.use_smooth_filter() as libc::c_int) } else { (false as libc::c_int, false as libc::c_int) }; let angle_arg = angle | (enable_ief << 10) | (ief_smooth_filter << 9); let (bw, bh) = ( ((dst.plane_cfg.width + 7) >> 3) << 3, ((dst.plane_cfg.height + 7) >> 3) << 3, ); let (dx, dy) = ( (bw as isize - dst.rect().x as isize) as libc::c_int, (bh as isize - dst.rect().y as isize) as libc::c_int, ); if angle <= 90 { rav1e_ipred_z1_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, 0, 0, bd_max, ); } else if angle < 180 { rav1e_ipred_z2_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, dx, dy, bd_max, ); } else { rav1e_ipred_z3_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, 0, 0, bd_max, ); } } PredictionMode::SMOOTH_PRED => { rav1e_ipred_smooth_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::SMOOTH_V_PRED => { rav1e_ipred_smooth_v_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::SMOOTH_H_PRED => { rav1e_ipred_smooth_h_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::PAETH_PRED => { rav1e_ipred_paeth_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::UV_CFL_PRED => { let ac_ptr = ac.as_ptr() as *const _; (match variant { PredictionVariant::NONE => rav1e_ipred_cfl_128_16bpc_avx2, PredictionVariant::LEFT => rav1e_ipred_cfl_left_16bpc_avx2, PredictionVariant::TOP => rav1e_ipred_cfl_top_16bpc_avx2, PredictionVariant::BOTH => rav1e_ipred_cfl_16bpc_avx2, })( dst_ptr, stride, edge_ptr, w, h, ac_ptr, angle, bd_max ); } _ => call_rust(dst), } } _ => call_rust(dst), } } }
use crate::context::MAX_TX_SIZE; use crate::cpu_features::CpuFeatureLevel; use crate::predict::{ rust, IntraEdgeFilterParameters, PredictionMode, PredictionVariant, }; use crate::tiling::PlaneRegionMut; use crate::transform::TxSize; use crate::util::Aligned; use crate::Pixel; use v_frame::pixel::PixelType; macro_rules! decl_angular_ipred_fn { ($($f:ident),+) => { extern { $( fn $f( dst: *mut u8, stride: libc::ptrdiff_t, topleft: *const u8, width: libc::c_int, height: libc::c_int, angle: libc::c_int, ); )* } }; } decl_angular_ipred_fn! { rav1e_ipred_dc_avx2, rav1e_ipred_dc_ssse3, rav1e_ipred_dc_128_avx2, rav1e_ipred_dc_128_ssse3, rav1e_ipred_dc_left_avx2, rav1e_ipred_dc_left_ssse3, rav1e_ipred_dc_top_avx2, rav1e_ipred_dc_top_ssse3, rav1e_ipred_v_avx2, rav1e_ipred_v_ssse3, rav1e_ipred_h_avx2, rav1e_ipred_h_ssse3, rav1e_ipred_z1_avx2, rav1e_ipred_z3_avx2, rav1e_ipred_smooth_avx2, rav1e_ipred_smooth_ssse3, rav1e_ipred_smooth_v_avx2, rav1e_ipred_smooth_v_ssse3, rav1e_ipred_smooth_h_avx2, rav1e_ipred_smooth_h_ssse3, rav1e_ipred_paeth_avx2, rav1e_ipred_paeth_ssse3 } macro_rules! decl_angular_ipred_hbd_fn { ($($f:ident),+) => { extern { $( fn $f( dst: *mut u16, stride: libc::ptrdiff_t, topleft: *const u16, width: libc::c_int, height: libc::c_int, angle: libc::c_int, max_width: libc::c_int, max_height: libc::c_int, bit_depth_max: libc::c_int, ); )* } }; } decl_angular_ipred_hbd_fn! { rav1e_ipred_dc_16bpc_avx2, rav1e_ipred_dc_128_16bpc_avx2, rav1e_ipred_dc_left_16bpc_avx2, rav1e_ipred_dc_top_16bpc_avx2, rav1e_ipred_v_16bpc_avx2, rav1e_ipred_h_16bpc_avx2, rav1e_ipred_z1_16bpc_avx2, rav1e_ipred_z3_16bpc_avx2, rav1e_ipred_smooth_16bpc_avx2, rav1e_ipred_smooth_v_16bpc_avx2, rav1e_ipred_smooth_h_16bpc_avx2, rav1e_ipred_paeth_16bpc_avx2 } extern { fn rav1e_ipred_z2_avx2( dst: *mut u8, stride: libc::ptrdiff_t, topleft: *const u8, width: libc::c_int, height: libc::c_int, angle: libc::c_int, dx: libc::c_int, dy: libc::c_int, ); fn rav1e_ipred_z2_16bpc_avx2( dst: *mut u16, stride: libc::ptrdiff_t, topleft: *const u16, width: libc::c_int, height: libc::c_int, angle: libc::c_int, dx: libc::c_int, dy: libc::c_int, bit_depth_max: libc::c_int, ); } macro_rules! decl_cfl_pred_fn { ($($f:ident),+) => { extern { $( fn $f( dst: *mut u8, stride: libc::ptrdiff_t, topleft: *const u8, width: libc::c_int, height: libc::c_int, ac: *const i16, alpha: libc::c_int, ); )* } }; } decl_cfl_pred_fn! { rav1e_ipred_cfl_avx2, rav1e_ipred_cfl_ssse3, rav1e_ipred_cfl_128_avx2, rav1e_ipred_cfl_128_ssse3, rav1e_ipred_cfl_left_avx2, rav1e_ipred_cfl_left_ssse3, rav1e_ipred_cfl_top_avx2, rav1e_ipred_cfl_top_ssse3 } macro_rules! decl_cfl_pred_hbd_fn { ($($f:ident),+) => { extern { $( fn $f( dst: *mut u16, stride: libc::ptrdiff_t, topleft: *const u16, width: libc::c_int, height: libc::c_int, ac: *const i16, alpha: libc::c_int, bit_depth_max: libc::c_int, ); )* } }; } decl_cfl_pred_hbd_fn! { rav1e_ipred_cfl_16bpc_avx2, rav1e_ipred_cfl_128_16bpc_avx2, rav1e_ipred_cfl_left_16bpc_avx2, rav1e_ipred_cfl_top_16bpc_avx2 } #[inline(always)] pub fn dispatch_predict_intra<T: Pixel>( mode: PredictionMode, variant: PredictionVariant, dst: &mut PlaneRegionMut<'_, T>, tx_size: TxSize, bit_depth: usize, ac: &[i16], angle: isize, ief_params: Option<IntraEdgeFilterParameters>, edge_buf: &Aligned<[T; 4 * MAX_TX_SIZE + 1]>, cpu: CpuFeatureLevel, ) { let call_rust = |dst: &mut PlaneRegionMut<'_, T>| { rust::dispatch_predict_intra( mode, variant, dst, tx_size, bit_depth, ac, angle, ief_params, edge_buf, cpu, ); }; unsafe { let stride = T::to_asm_stride(dst.plane_cfg.stride) as libc::ptrdiff_t; let w = tx_size.width() as libc::c_int; let h = tx_size.height() as libc::c_int; let angle = angle as libc::c_int; match T::type_enum() { PixelType::U8 if cpu >= CpuFeatureLevel::SSSE3 => { let dst_ptr = dst.data_ptr_mut() as *mut _; let edge_ptr = edge_buf.data.as_ptr().offset(2 * MAX_TX_SIZE as isize) as *const _; if cpu >= CpuFeatureLevel::AVX2 { match mode { PredictionMode::DC_PRED => { (match variant { PredictionVariant::NONE => rav1e_ipred_dc_128_avx2, PredictionVariant::LEFT => rav1e_ipred_dc_left_avx2, PredictionVariant::TOP => rav1e_ipred_dc_top_avx2, PredictionVariant::BOTH => rav1e_ipred_dc_avx2, })(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::V_PRED if angle == 90 => { rav1e_ipred_v_avx2(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::H_PRED if angle == 180 => { rav1e_ipred_h_avx2(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::V_PRED | PredictionMode::H_PRED | PredictionMode::D45_PRED | PredictionMode::D135_PRED | PredictionMode::D113_PRED | PredictionMode::D157_PRED | PredictionMode::D203_PRED | PredictionMode::D67_PRED => { let (enable_ief, ief_smooth_filter) = if let Some(params) = ief_params { ( true as libc::c_int, params.use_smooth_filter() as libc::c_int, ) } else { (false as libc::c_int, false as libc::c_int) }; let angle_arg = angle | (enable_ief << 10) | (ief_smooth_filter << 9); let (bw, bh) = ( ((dst.plane_cfg.width + 7) >> 3) << 3, ((dst.plane_cfg.height + 7) >> 3) << 3, ); let (dx, dy) = ( (bw as isize - dst.rect().x as isize) as libc::c_int, (bh as isize - dst.rect().y as isize) as libc::c_int, ); if angle <= 90 { rav1e_ipred_z1_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, ); } else if angle < 180 { rav1e_ipred_z2_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, dx, dy, ); } else { rav1e_ipred_z3_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, ); } } PredictionMode::SMOOTH_PRED => { rav1e_ipred_smooth_avx2(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::SMOOTH_V_PRED => { rav1e_ipred_smooth_v_avx2( dst_ptr, stride, edge_ptr, w, h, angle, ); } PredictionMode::SMOOTH_H_PRED => { rav1e_ipred_smooth_h_avx2( dst_ptr, stride, edge_ptr, w, h, angle, ); } PredictionMode::PAETH_PRED => { rav1e_ipred_paeth_avx2(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::UV_CFL_PRED => { let ac_ptr = ac.as_ptr() as *const _; (match variant { PredictionVariant::NONE => rav1e_ipred_cfl_128_avx2, PredictionVariant::LEFT => rav1e_ipred_cfl_left_avx2, PredictionVariant::TOP => rav1e_ipred_cfl_top_avx2, PredictionVariant::BOTH => rav1e_ipred_cfl_avx2, })(dst_ptr, stride, edge_ptr, w, h, ac_ptr, angle); } _ => call_rust(dst), } } else if cpu >= CpuFeatureLevel::SSSE3 { match mode { PredictionMode::DC_PRED => { (match variant { PredictionVariant::NONE => rav1e_ipred_dc_128_ssse3, PredictionVariant::LEFT => rav1e_ipred_dc_left_ssse3, PredictionVariant::TOP => rav1e_ipred_dc_top_ssse3, PredictionVariant::BOTH => rav1e_ipred_dc_ssse3, })(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::V_PRED if angle == 90 => { rav1e_ipred_v_ssse3(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::H_PRED if angle == 180 => { rav1e_ipred_h_ssse3(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::SMOOTH_PRED => { rav1e_ipred_smooth_ssse3(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::SMOOTH_V_PRED => { rav1e_ipred_smooth_v_ssse3( dst_ptr, stride, edge_ptr, w, h, angle, ); } PredictionMode::SMOOTH_H_PRED => { rav1e_ipred_smooth_h_ssse
3( dst_ptr, stride, edge_ptr, w, h, angle, ); } PredictionMode::PAETH_PRED => { rav1e_ipred_paeth_ssse3(dst_ptr, stride, edge_ptr, w, h, angle); } PredictionMode::UV_CFL_PRED => { let ac_ptr = ac.as_ptr() as *const _; (match variant { PredictionVariant::NONE => rav1e_ipred_cfl_128_ssse3, PredictionVariant::LEFT => rav1e_ipred_cfl_left_ssse3, PredictionVariant::TOP => rav1e_ipred_cfl_top_ssse3, PredictionVariant::BOTH => rav1e_ipred_cfl_ssse3, })(dst_ptr, stride, edge_ptr, w, h, ac_ptr, angle); } _ => call_rust(dst), } } } PixelType::U16 if cpu >= CpuFeatureLevel::AVX2 => { let dst_ptr = dst.data_ptr_mut() as *mut _; let edge_ptr = edge_buf.data.as_ptr().offset(2 * MAX_TX_SIZE as isize) as *const _; let bd_max = (1 << bit_depth) - 1; match mode { PredictionMode::DC_PRED => { (match variant { PredictionVariant::NONE => rav1e_ipred_dc_128_16bpc_avx2, PredictionVariant::LEFT => rav1e_ipred_dc_left_16bpc_avx2, PredictionVariant::TOP => rav1e_ipred_dc_top_16bpc_avx2, PredictionVariant::BOTH => rav1e_ipred_dc_16bpc_avx2, })( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max ); } PredictionMode::V_PRED if angle == 90 => { rav1e_ipred_v_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::H_PRED if angle == 180 => { rav1e_ipred_h_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::V_PRED | PredictionMode::H_PRED | PredictionMode::D45_PRED | PredictionMode::D135_PRED | PredictionMode::D113_PRED | PredictionMode::D157_PRED | PredictionMode::D203_PRED | PredictionMode::D67_PRED => { let (enable_ief, ief_smooth_filter) = if let Some(params) = ief_params { (true as libc::c_int, params.use_smooth_filter() as libc::c_int) } else { (false as libc::c_int, false as libc::c_int) }; let angle_arg = angle | (enable_ief << 10) | (ief_smooth_filter << 9); let (bw, bh) = ( ((dst.plane_cfg.width + 7) >> 3) << 3, ((dst.plane_cfg.height + 7) >> 3) << 3, ); let (dx, dy) = ( (bw as isize - dst.rect().x as isize) as libc::c_int, (bh as isize - dst.rect().y as isize) as libc::c_int, ); if angle <= 90 { rav1e_ipred_z1_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, 0, 0, bd_max, ); } else if angle < 180 { rav1e_ipred_z2_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, dx, dy, bd_max, ); } else { rav1e_ipred_z3_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle_arg, 0, 0, bd_max, ); } } PredictionMode::SMOOTH_PRED => { rav1e_ipred_smooth_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::SMOOTH_V_PRED => { rav1e_ipred_smooth_v_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::SMOOTH_H_PRED => { rav1e_ipred_smooth_h_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::PAETH_PRED => { rav1e_ipred_paeth_16bpc_avx2( dst_ptr, stride, edge_ptr, w, h, angle, 0, 0, bd_max, ); } PredictionMode::UV_CFL_PRED => { let ac_ptr = ac.as_ptr() as *const _; (match variant { PredictionVariant::NONE => rav1e_ipred_cfl_128_16bpc_avx2, PredictionVariant::LEFT => rav1e_ipred_cfl_left_16bpc_avx2, PredictionVariant::TOP => rav1e_ipred_cfl_top_16bpc_avx2, PredictionVariant::BOTH => rav1e_ipred_cfl_16bpc_avx2, })( dst_ptr, stride, edge_ptr, w, h, ac_ptr, angle, bd_max ); } _ => call_rust(dst), } } _ => call_rust(dst), } } }
function_block-function_prefixed
[ { "content": "pub fn ac_q(qindex: u8, delta_q: i8, bit_depth: usize) -> i16 {\n\n static AC_Q: [&[i16; 256]; 3] =\n\n [&ac_qlookup_Q3, &ac_qlookup_10_Q3, &ac_qlookup_12_Q3];\n\n let bd = ((bit_depth ^ 8) >> 1).min(2);\n\n AC_Q[bd][((qindex as isize + delta_q as isize).max(0) as usize).min(255)]\n\n}\n\n\n...
Rust
src/embeds/osu/pinned.rs
JoshiDhima/Bathbot
7a8dd8a768caede285df4f8ea5aead27bdbbf660
use std::fmt::Write; use eyre::Report; use hashbrown::HashMap; use rosu_v2::prelude::{Beatmapset, GameMode, Score, User}; use crate::{ commands::osu::TopOrder, core::Context, embeds::{osu, Author, Footer}, pp::PpCalculator, util::{ constants::OSU_BASE, datetime::how_long_ago_dynamic, numbers::with_comma_int, osu::ScoreOrder, ScoreExt, }, }; use super::OrderAppendix; pub struct PinnedEmbed { author: Author, description: String, footer: Footer, thumbnail: String, } impl PinnedEmbed { pub async fn new<'i, S>( user: &User, scores: S, ctx: &Context, sort_by: ScoreOrder, pages: (usize, usize), ) -> Self where S: Iterator<Item = &'i Score>, { let mut description = String::with_capacity(512); let farm = HashMap::new(); for score in scores { let map = score.map.as_ref().unwrap(); let mapset = score.mapset.as_ref().unwrap(); let (pp, max_pp, stars) = match PpCalculator::new(ctx, map.map_id).await { Ok(mut calc) => { calc.score(score); let stars = calc.stars(); let max_pp = calc.max_pp(); let pp = match score.pp { Some(pp) => pp, None => calc.pp() as f32, }; (Some(pp), Some(max_pp as f32), stars as f32) } Err(err) => { warn!("{:?}", Report::new(err)); (None, None, 0.0) } }; let stars = osu::get_stars(stars); let pp = osu::get_pp(pp, max_pp); let mapset_opt = if let ScoreOrder::RankedDate = sort_by { let mapset_fut = ctx.psql().get_beatmapset::<Beatmapset>(mapset.mapset_id); match mapset_fut.await { Ok(mapset) => Some(mapset), Err(err) => { let report = Report::new(err).wrap_err("failed to get mapset"); warn!("{report:?}"); None } } } else { None }; let _ = writeln!( description, "**- [{title} [{version}]]({OSU_BASE}b/{id}) {mods}** [{stars}]\n\ {grade} {pp} ~ {acc}% ~ {score}{appendix}\n[ {combo} ] ~ {hits} ~ {ago}", title = mapset.title, version = map.version, id = map.map_id, mods = osu::get_mods(score.mods), grade = score.grade_emote(score.mode), acc = score.acc(score.mode), score = with_comma_int(score.score), appendix = OrderAppendix::new(TopOrder::Other(sort_by), map, mapset_opt, score, &farm), combo = osu::get_combo(score, map), hits = score.hits_string(score.mode), ago = how_long_ago_dynamic(&score.created_at) ); } description.pop(); let footer_text = format!( "Page {}/{} | Mode: {}", pages.0, pages.1, mode_str(user.mode) ); Self { author: author!(user), description, footer: Footer::new(footer_text), thumbnail: user.avatar_url.to_owned(), } } } fn mode_str(mode: GameMode) -> &'static str { match mode { GameMode::STD => "osu!", GameMode::TKO => "Taiko", GameMode::CTB => "Catch", GameMode::MNA => "Mania", } } impl_builder!(PinnedEmbed { author, description, footer, thumbnail, });
use std::fmt::Write; use eyre::Report; use hashbrown::HashMap; use rosu_v2::prelude::{Beatmapset, GameMode, Score, User}; use crate::{ commands::osu::TopOrder, core::Context, embeds::{osu, Author, Footer}, pp::PpCalculator, util::{ constants::OSU_BASE, datetime::how_long_ago_dynamic, numbers::with_comma_int, osu::ScoreOrder, ScoreExt, }, }; use super::OrderAppendix; pub struct PinnedEmbed { author: Author, description: String, footer: Footer, thumbnail: String, } impl PinnedEmbed { pub async fn new<'i, S>( user: &User, scores: S, ctx: &Context, sort_by: ScoreOrder, pages: (usize, usize), ) -> Self where S: Iterator<Item = &'i Score>, { let mut description = String::with_capacity(512); let farm = HashMap::new(); for score in scores { let map = score.map.as_ref().unwrap(); let mapset = score.mapset.as_ref().unwrap(); let (pp, max_pp, stars) = match PpCalculator::new(ctx, map.map_id).await { Ok(mut calc) => { calc.score(score); let stars = calc.stars(); let max_pp = calc.max_pp(); let pp = match score.pp { Some(pp) => pp, None => calc.pp() as f32, }; (Some(pp), Some(max_pp as f32), stars as f32) } Err(err) => { warn!("{:?}", Report::new(err)); (None, None, 0.0) } }; let
} fn mode_str(mode: GameMode) -> &'static str { match mode { GameMode::STD => "osu!", GameMode::TKO => "Taiko", GameMode::CTB => "Catch", GameMode::MNA => "Mania", } } impl_builder!(PinnedEmbed { author, description, footer, thumbnail, });
stars = osu::get_stars(stars); let pp = osu::get_pp(pp, max_pp); let mapset_opt = if let ScoreOrder::RankedDate = sort_by { let mapset_fut = ctx.psql().get_beatmapset::<Beatmapset>(mapset.mapset_id); match mapset_fut.await { Ok(mapset) => Some(mapset), Err(err) => { let report = Report::new(err).wrap_err("failed to get mapset"); warn!("{report:?}"); None } } } else { None }; let _ = writeln!( description, "**- [{title} [{version}]]({OSU_BASE}b/{id}) {mods}** [{stars}]\n\ {grade} {pp} ~ {acc}% ~ {score}{appendix}\n[ {combo} ] ~ {hits} ~ {ago}", title = mapset.title, version = map.version, id = map.map_id, mods = osu::get_mods(score.mods), grade = score.grade_emote(score.mode), acc = score.acc(score.mode), score = with_comma_int(score.score), appendix = OrderAppendix::new(TopOrder::Other(sort_by), map, mapset_opt, score, &farm), combo = osu::get_combo(score, map), hits = score.hits_string(score.mode), ago = how_long_ago_dynamic(&score.created_at) ); } description.pop(); let footer_text = format!( "Page {}/{} | Mode: {}", pages.0, pages.1, mode_str(user.mode) ); Self { author: author!(user), description, footer: Footer::new(footer_text), thumbnail: user.avatar_url.to_owned(), } }
function_block-function_prefixed
[ { "content": "fn new_pp(pp: f32, user: &User, scores: &[Score], actual_offset: f32) -> (usize, f32) {\n\n let actual: f32 = scores\n\n .iter()\n\n .filter_map(|s| s.weight)\n\n .fold(0.0, |sum, weight| sum + weight.pp);\n\n\n\n let total = user.statistics.as_ref().map_or(0.0, |stats| ...
Rust
src/platform_impl/web/event_loop/window_target.rs
michaelkirk/winit
412bd94ea473c7b175f94a190d66f4be3e92aaab
use super::{super::monitor, backend, device, proxy::Proxy, runner, window}; use crate::dpi::{PhysicalSize, Size}; use crate::event::{DeviceId, ElementState, Event, KeyboardInput, TouchPhase, WindowEvent}; use crate::event_loop::ControlFlow; use crate::window::{Theme, WindowId}; use std::clone::Clone; use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque}; pub struct WindowTarget<T: 'static> { pub(crate) runner: runner::Shared<T>, } impl<T> Clone for WindowTarget<T> { fn clone(&self) -> Self { WindowTarget { runner: self.runner.clone(), } } } impl<T> WindowTarget<T> { pub fn new() -> Self { WindowTarget { runner: runner::Shared::new(), } } pub fn proxy(&self) -> Proxy<T> { Proxy::new(self.runner.clone()) } pub fn run(&self, event_handler: Box<dyn FnMut(Event<'static, T>, &mut ControlFlow)>) { self.runner.set_listener(event_handler); } pub fn generate_id(&self) -> window::Id { window::Id(self.runner.generate_id()) } pub fn register(&self, canvas: &mut backend::Canvas, id: window::Id) { let runner = self.runner.clone(); canvas.set_attribute("data-raw-handle", &id.0.to_string()); canvas.on_blur(move || { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::Focused(false), }); }); let runner = self.runner.clone(); canvas.on_focus(move || { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::Focused(true), }); }); let runner = self.runner.clone(); canvas.on_keyboard_press(move |scancode, virtual_keycode, modifiers| { #[allow(deprecated)] runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::KeyboardInput { device_id: DeviceId(unsafe { device::Id::dummy() }), input: KeyboardInput { scancode, state: ElementState::Pressed, virtual_keycode, modifiers, }, is_synthetic: false, }, }); }); let runner = self.runner.clone(); canvas.on_keyboard_release(move |scancode, virtual_keycode, modifiers| { #[allow(deprecated)] runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::KeyboardInput { device_id: DeviceId(unsafe { device::Id::dummy() }), input: KeyboardInput { scancode, state: ElementState::Released, virtual_keycode, modifiers, }, is_synthetic: false, }, }); }); let runner = self.runner.clone(); canvas.on_received_character(move |char_code| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::ReceivedCharacter(char_code), }); }); let runner = self.runner.clone(); canvas.on_cursor_leave(move |pointer_id| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::CursorLeft { device_id: DeviceId(device::Id(pointer_id)), }, }); }); let runner = self.runner.clone(); canvas.on_cursor_enter(move |pointer_id| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::CursorEntered { device_id: DeviceId(device::Id(pointer_id)), }, }); }); let runner = self.runner.clone(); canvas.on_cursor_move(move |pointer_id, position, modifiers| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::CursorMoved { device_id: DeviceId(device::Id(pointer_id)), position, modifiers, }, }); }); let runner = self.runner.clone(); canvas.on_mouse_press(move |pointer_id, button, modifiers| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::MouseInput { device_id: DeviceId(device::Id(pointer_id)), state: ElementState::Pressed, button, modifiers, }, }); }); let runner = self.runner.clone(); canvas.on_mouse_release(move |pointer_id, button, modifiers| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::MouseInput { device_id: DeviceId(device::Id(pointer_id)), state: ElementState::Released, button, modifiers, }, }); }); let runner = self.runner.clone(); canvas.on_mouse_wheel(move |pointer_id, delta, modifiers| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::MouseWheel { device_id: DeviceId(device::Id(pointer_id)), delta, phase: TouchPhase::Moved, modifiers, }, }); }); let runner = self.runner.clone(); let raw = canvas.raw().clone(); let mut intended_size = PhysicalSize { width: raw.width() as u32, height: raw.height() as u32, }; canvas.on_fullscreen_change(move || { let new_size = if backend::is_fullscreen(&raw) { intended_size = PhysicalSize { width: raw.width() as u32, height: raw.height() as u32, }; backend::window_size().to_physical(backend::scale_factor()) } else { intended_size }; backend::set_canvas_size(&raw, Size::Physical(new_size)); runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::Resized(new_size), }); runner.request_redraw(WindowId(id)); }); let runner = self.runner.clone(); canvas.on_dark_mode(move |is_dark_mode| { let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::ThemeChanged(theme), }); }); } pub fn available_monitors(&self) -> VecDequeIter<monitor::Handle> { VecDeque::new().into_iter() } pub fn primary_monitor(&self) -> monitor::Handle { monitor::Handle } }
use super::{super::monitor, backend, device, proxy::Proxy, runner, window}; use crate::dpi::{PhysicalSize, Size}; use crate::event::{DeviceId, ElementState, Event, KeyboardInput, TouchPhase, WindowEvent}; use crate::event_loop::ControlFlow; use crate::window::{Theme, WindowId}; use std::clone::Clone; use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque}; pub struct WindowTarget<T: 'static> { pub(crate) runner: runner::Shared<T>, } impl<T> Clone for WindowTarget<T> { fn clone(&self) -> Self { WindowTarget { runner: self.runner.clone(), } } } impl<T> WindowTarget<T> { pub fn new() -> Self { WindowTarget { runner: runner::Shared::new(), } } pub fn proxy(&self) -> Proxy<T> { Proxy::new(self.runner.clone()) } pub fn run(&self, event_handler: Box<dyn FnMut(Event<'static, T>, &mut ControlFlow)>) { self.runner.set_listener(event_handler); } pub fn generate_id(&self) -> window::Id { window::Id(self.runner.generate_id()) } pub fn register(&self, canvas: &mut backend::Canvas, id: window::Id) { let runner = self.runner.clone(); canvas.set_attribute("data-raw-handle", &id.0.to_string()); canvas.on_blur(move || { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::Focused(false), }); }); let runner = self.runner.clone(); canvas.on_focus(move || { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::Focused(true), }); }); let runner = self.runner.clone(); canvas.on_keyboard_press(move |scancode, virtual_keycode, modifiers| { #[allow(deprecated)] runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::KeyboardInput { device_id: DeviceId(unsafe { device::Id::dummy() }), input: KeyboardInput { scancode, state: ElementState::Pressed, virtual_keycode, modifiers, }, is_synthetic: false, }, }); }); let runner = self.runner.clone(); canvas.on_keyboard_release(move |scancode, virtual_keycode, modifiers| { #[allow(deprecated)] runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::KeyboardInput { device_id: DeviceId(unsafe { device::Id::dummy() }), input: KeyboardInput { scancode, state: ElementState::Released, virtual_keycode, modifiers, }, is_synthetic: false, }, }); }); let runner = self.runner.clone(); canvas.on_received_character(move |char_code| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::ReceivedCharacter(char_code), }); }); let runner = self.runner.clone(); canvas.on_cursor_leave(move |pointer_id| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::CursorLeft { device_id: DeviceId(device::Id(pointer_id)), }, }); }); let runner = self.runner.clone(); canvas.on_cursor_enter(move |pointer_id| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::CursorEntered { device_id: DeviceId(device::Id(pointer_id)), }, }); }); let runner = self.runner.clone(); canvas.on_cursor_move(move |pointer_id, position, modifiers| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::CursorMoved {
}
device_id: DeviceId(device::Id(pointer_id)), position, modifiers, }, }); }); let runner = self.runner.clone(); canvas.on_mouse_press(move |pointer_id, button, modifiers| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::MouseInput { device_id: DeviceId(device::Id(pointer_id)), state: ElementState::Pressed, button, modifiers, }, }); }); let runner = self.runner.clone(); canvas.on_mouse_release(move |pointer_id, button, modifiers| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::MouseInput { device_id: DeviceId(device::Id(pointer_id)), state: ElementState::Released, button, modifiers, }, }); }); let runner = self.runner.clone(); canvas.on_mouse_wheel(move |pointer_id, delta, modifiers| { runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::MouseWheel { device_id: DeviceId(device::Id(pointer_id)), delta, phase: TouchPhase::Moved, modifiers, }, }); }); let runner = self.runner.clone(); let raw = canvas.raw().clone(); let mut intended_size = PhysicalSize { width: raw.width() as u32, height: raw.height() as u32, }; canvas.on_fullscreen_change(move || { let new_size = if backend::is_fullscreen(&raw) { intended_size = PhysicalSize { width: raw.width() as u32, height: raw.height() as u32, }; backend::window_size().to_physical(backend::scale_factor()) } else { intended_size }; backend::set_canvas_size(&raw, Size::Physical(new_size)); runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::Resized(new_size), }); runner.request_redraw(WindowId(id)); }); let runner = self.runner.clone(); canvas.on_dark_mode(move |is_dark_mode| { let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; runner.send_event(Event::WindowEvent { window_id: WindowId(id), event: WindowEvent::ThemeChanged(theme), }); }); } pub fn available_monitors(&self) -> VecDequeIter<monitor::Handle> { VecDeque::new().into_iter() } pub fn primary_monitor(&self) -> monitor::Handle { monitor::Handle }
random
[ { "content": "pub fn event_mods(event: id) -> ModifiersState {\n\n let flags = unsafe { NSEvent::modifierFlags(event) };\n\n let mut m = ModifiersState::empty();\n\n m.set(\n\n ModifiersState::SHIFT,\n\n flags.contains(NSEventModifierFlags::NSShiftKeyMask),\n\n );\n\n m.set(\n\n ...
Rust
crates/oci-distribution/src/reference.rs
thomastaylor312/krustlet
a99a507bda67595a07713860e1c13ab40f977bad
use std::convert::{Into, TryFrom}; use std::error::Error; use std::fmt; use std::path::PathBuf; use std::str::FromStr; const NAME_TOTAL_LENGTH_MAX: usize = 255; #[derive(Debug, PartialEq, Eq)] pub enum ParseError { DigestInvalidFormat, NameContainsUppercase, NameEmpty, NameNotCanonical, NameTooLong, ReferenceInvalidFormat, TagInvalidFormat, } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ParseError::DigestInvalidFormat => write!(f, "invalid digest format"), ParseError::NameContainsUppercase => write!(f, "repository name must be lowercase"), ParseError::NameEmpty => write!(f, "repository name must have at least one component"), ParseError::NameNotCanonical => write!(f, "repository name must be canonical"), ParseError::NameTooLong => write!( f, "repository name must not be more than {} characters", NAME_TOTAL_LENGTH_MAX ), ParseError::ReferenceInvalidFormat => write!(f, "invalid reference format"), ParseError::TagInvalidFormat => write!(f, "invalid tag format"), } } } impl Error for ParseError {} #[derive(Clone, Hash, PartialEq, Eq)] pub struct Reference { registry: String, repository: String, tag: Option<String>, digest: Option<String>, } impl Reference { pub fn registry(&self) -> &str { &self.registry } pub fn repository(&self) -> &str { &self.repository } pub fn tag(&self) -> Option<&str> { self.tag.as_deref() } pub fn digest(&self) -> Option<&str> { self.digest.as_deref() } fn full_name(&self) -> String { let mut path = PathBuf::new(); path.push(self.registry()); path.push(self.repository()); path.to_str().unwrap_or("").to_owned() } pub fn whole(&self) -> String { let mut s = self.full_name(); if let Some(t) = self.tag() { if s != "" { s.push_str(":"); } s.push_str(t); } if let Some(d) = self.digest() { if s != "" { s.push_str("@"); } s.push_str(d); } s } } impl std::fmt::Debug for Reference { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.whole()) } } impl fmt::Display for Reference { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.whole()) } } impl FromStr for Reference { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { Reference::try_from(s) } } impl TryFrom<String> for Reference { type Error = ParseError; fn try_from(s: String) -> Result<Self, Self::Error> { let repo_start = s .find('/') .ok_or_else(|| ParseError::ReferenceInvalidFormat)?; let first_colon = s[repo_start + 1..].find(':').map(|i| repo_start + i); let digest_start = s[repo_start + 1..].find('@').map(|i| repo_start + i + 1); let tag_start = match (digest_start, first_colon) { (Some(ds), Some(fc)) => { if fc < ds { Some(fc) } else { None } } (None, Some(fc)) => Some(fc), _ => None, } .map(|i| i + 1); let repo_end = match (digest_start, tag_start) { (Some(_), Some(ts)) => ts, (None, Some(ts)) => ts, (Some(ds), None) => ds, (None, None) => s.len(), }; let tag: Option<String> = match (digest_start, tag_start) { (Some(d), Some(t)) => Some(s[t + 1..d].to_string()), (None, Some(t)) => Some(s[t + 1..].to_string()), _ => None, }; let digest: Option<String> = match digest_start { Some(c) => Some(s[c + 1..].to_string()), None => None, }; let reference = Reference { registry: s[..repo_start].to_string(), repository: s[repo_start + 1..repo_end].to_string(), tag, digest, }; if reference.repository().len() > NAME_TOTAL_LENGTH_MAX { return Err(ParseError::NameTooLong); } Ok(reference) } } impl TryFrom<&str> for Reference { type Error = ParseError; fn try_from(string: &str) -> Result<Self, Self::Error> { TryFrom::try_from(string.to_owned()) } } impl Into<String> for Reference { fn into(self) -> String { self.whole() } } #[cfg(test)] mod test { use super::*; mod parse { use super::*; fn must_parse(image: &str) -> Reference { Reference::try_from(image).expect("could not parse reference") } fn validate_registry_and_repository(reference: &Reference) { assert_eq!(reference.registry(), "webassembly.azurecr.io"); assert_eq!(reference.repository(), "hello"); } fn validate_tag(reference: &Reference) { assert_eq!(reference.tag(), Some("v1")); } fn validate_digest(reference: &Reference) { assert_eq!( reference.digest(), Some("sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9") ); } #[test] fn name_too_long() { assert_eq!( Reference::try_from(format!( "webassembly.azurecr.io/{}", (0..256).map(|_| "a").collect::<String>() )) .err(), Some(ParseError::NameTooLong) ); } #[test] fn owned_string() { let reference = Reference::from_str("webassembly.azurecr.io/hello:v1") .expect("could not parse reference"); validate_registry_and_repository(&reference); validate_tag(&reference); assert_eq!(reference.digest(), None); } #[test] fn tag_only() { let reference = must_parse("webassembly.azurecr.io/hello:v1"); validate_registry_and_repository(&reference); validate_tag(&reference); assert_eq!(reference.digest(), None); } #[test] fn digest_only() { let reference = must_parse("webassembly.azurecr.io/hello@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9"); validate_registry_and_repository(&reference); validate_digest(&reference); assert_eq!(reference.tag(), None); } #[test] fn tag_and_digest() { let reference = must_parse("webassembly.azurecr.io/hello:v1@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9"); validate_registry_and_repository(&reference); validate_tag(&reference); validate_digest(&reference); } #[test] fn no_tag_or_digest() { let reference = must_parse("webassembly.azurecr.io/hello"); validate_registry_and_repository(&reference); assert_eq!(reference.tag(), None); assert_eq!(reference.digest(), None); } #[test] fn missing_slash_char() { Reference::try_from("webassembly.azurecr.io:hello") .expect_err("no slash should produce an error"); } } }
use std::convert::{Into, TryFrom}; use std::error::Error; use std::fmt; use std::path::PathBuf; use std::str::FromStr; const NAME_TOTAL_LENGTH_MAX: usize = 255; #[derive(Debug, PartialEq, Eq)] pub enum ParseError { DigestInvalidFormat, NameContainsUppercase, NameEmpty, NameNotCanonical, NameTooLong, ReferenceInvalidFormat, TagInvalidFormat, } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ParseError::DigestInvalidFormat => write!(f, "invalid digest format"), ParseError::NameContainsUppercase => write!(f, "repository name must be lowercase"), ParseError::NameEmpty => write!(f, "repository name must have at least one component"), ParseError::NameNotCanonical => write!(f, "repository name must be canonical"), ParseError::NameTooLong => write!( f, "repository name must not be more than {} characters", NAME_TOTAL_LENGTH_MAX ), ParseError::ReferenceInvalidFormat => write!(f, "invalid reference format"), ParseError::TagInvalidFormat => write!(f, "invalid tag format"), } } } impl Error for ParseError {} #[derive(Clone, Hash, PartialEq, Eq)] pub struct Reference { registry: String, repository: String, tag: Option<String>, digest: Option<String>, } impl Reference { pub fn registry(&self) -> &str { &self.registry } pub fn repository(&self) -> &str { &self.repository } pub fn tag(&self) -> Option<&str> { self.tag.as_deref() } pub fn digest(&self) -> Option<&str> { self.digest.as_deref() } fn full_name(&self) -> String { let mut path = PathBuf::new(); path.push(self.registry()); path.push(self.repository()); path.to_str().unwrap_or("").to_owned() } pub fn whole(&self) -> String { let mut s = self.full_name(); if let Some(t) = self.tag() { if s != "" { s.push_str(":"); } s.push_str(t); } if let Some(d) = self.digest() { if s != "" { s.push_str("@"); } s.push_str(d); } s } } impl std::fmt::Debug for Reference { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.whole()) } } impl fmt::Display for Reference { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.whole()) } } impl FromStr for Reference { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { Reference::try_from(s) } } impl TryFrom<String> for Reference { type Error = ParseError; fn try_from(s: String) -> Result<Self, Self::Error> { let repo_start = s .find('/') .ok_or_else(|| ParseError::ReferenceInvalidFormat)?; let first_colon = s[repo_start + 1..].find(':').map(|i| repo_start + i); let digest_start = s[repo_start + 1..].find('@').map(|i| repo_start + i + 1); let tag_start = match (digest_start, first_colon) { (Some(ds), Some(fc)) => { if fc < ds { Some(fc) } else { None } } (None, Some(fc)) => Some(fc), _ => None, } .map(|i| i + 1); let repo_end = match (digest_start, tag_start) { (Some(_), Some(ts)) => ts, (None, Some(ts)) => ts, (Some(ds), None) => ds, (None, None) => s.len(), }; let tag: Option<String> = match (digest_start, tag_start) { (Some(d), Some(t)) => Some(s[t + 1..d].to_string()), (None, Some(t)) => Some(s[t + 1..].to_string()), _ => None, }; let digest: Option<String> = match digest_start { Some(c) => Some(s[c + 1..].to_string()), None => None, }; let reference = Reference { registry: s[..repo_start].to_string(), repository: s[repo_start + 1..repo_end].to_string(), tag, digest, }; if reference.repository().len() > NAME_TOTAL_LENGTH_MAX { return Err(ParseError::NameTooLong); } Ok(reference) } } impl TryFrom<&str> for Reference { type Error = ParseError; fn try_from(string: &str) -> Result<Self, Self::Error> { TryFrom::try_from(string.to_owned()) } } impl Into<String> for Reference { fn into(self) -> String { self.whole() } } #[cfg(test)] mod test { use super::*; mod parse { use super::*; fn must_parse(image: &str) -> Reference { Reference::try_from(image).expect("could not parse reference") } fn validate_registry_and_repository(reference: &Reference) { assert_eq!(reference.registry(), "webassembly.azurecr.io"); assert_eq!(reference.repository(), "hello"); } fn validate_tag(reference: &Reference) { assert_eq!(reference.tag(), Some("v1")); }
#[test] fn name_too_long() { assert_eq!( Reference::try_from(format!( "webassembly.azurecr.io/{}", (0..256).map(|_| "a").collect::<String>() )) .err(), Some(ParseError::NameTooLong) ); } #[test] fn owned_string() { let reference = Reference::from_str("webassembly.azurecr.io/hello:v1") .expect("could not parse reference"); validate_registry_and_repository(&reference); validate_tag(&reference); assert_eq!(reference.digest(), None); } #[test] fn tag_only() { let reference = must_parse("webassembly.azurecr.io/hello:v1"); validate_registry_and_repository(&reference); validate_tag(&reference); assert_eq!(reference.digest(), None); } #[test] fn digest_only() { let reference = must_parse("webassembly.azurecr.io/hello@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9"); validate_registry_and_repository(&reference); validate_digest(&reference); assert_eq!(reference.tag(), None); } #[test] fn tag_and_digest() { let reference = must_parse("webassembly.azurecr.io/hello:v1@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9"); validate_registry_and_repository(&reference); validate_tag(&reference); validate_digest(&reference); } #[test] fn no_tag_or_digest() { let reference = must_parse("webassembly.azurecr.io/hello"); validate_registry_and_repository(&reference); assert_eq!(reference.tag(), None); assert_eq!(reference.digest(), None); } #[test] fn missing_slash_char() { Reference::try_from("webassembly.azurecr.io:hello") .expect_err("no slash should produce an error"); } } }
fn validate_digest(reference: &Reference) { assert_eq!( reference.digest(), Some("sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9") ); }
function_block-full_function
[ { "content": "fn config_file_path_str(file_name: impl AsRef<std::path::Path>) -> String {\n\n config_dir().join(file_name).to_str().unwrap().to_owned()\n\n}\n\n\n", "file_path": "tests/oneclick/src/main.rs", "rank": 0, "score": 299495.3732690705 }, { "content": "fn warn_if_premature_exit(...
Rust
src_testbed/nphysics_backend.rs
sebcrozet/rapier
b61bec83487224c285a1e95ac58d48885254285b
use ncollide::shape::{Ball, Capsule, Cuboid, ShapeHandle}; use nphysics::force_generator::DefaultForceGeneratorSet; use nphysics::joint::{ DefaultJointConstraintSet, FixedConstraint, PrismaticConstraint, RevoluteConstraint, }; use nphysics::object::{ BodyPartHandle, ColliderDesc, DefaultBodyHandle, DefaultBodySet, DefaultColliderSet, RigidBodyDesc, }; use nphysics::world::{DefaultGeometricalWorld, DefaultMechanicalWorld}; use rapier::counters::Counters; use rapier::dynamics::{ IntegrationParameters, JointParams, JointSet, RigidBodyHandle, RigidBodySet, }; use rapier::geometry::{Collider, ColliderSet}; use rapier::math::Vector; use std::collections::HashMap; #[cfg(feature = "dim3")] use {ncollide::shape::TriMesh, nphysics::joint::BallConstraint}; pub struct NPhysicsWorld { rapier2nphysics: HashMap<RigidBodyHandle, DefaultBodyHandle>, mechanical_world: DefaultMechanicalWorld<f32>, geometrical_world: DefaultGeometricalWorld<f32>, bodies: DefaultBodySet<f32>, colliders: DefaultColliderSet<f32>, joints: DefaultJointConstraintSet<f32>, force_generators: DefaultForceGeneratorSet<f32>, } impl NPhysicsWorld { pub fn from_rapier( gravity: Vector<f32>, bodies: &RigidBodySet, colliders: &ColliderSet, joints: &JointSet, ) -> Self { let mut rapier2nphysics = HashMap::new(); let mechanical_world = DefaultMechanicalWorld::new(gravity); let geometrical_world = DefaultGeometricalWorld::new(); let mut nphysics_bodies = DefaultBodySet::new(); let mut nphysics_colliders = DefaultColliderSet::new(); let mut nphysics_joints = DefaultJointConstraintSet::new(); let force_generators = DefaultForceGeneratorSet::new(); for (rapier_handle, rb) in bodies.iter() { let nphysics_rb = RigidBodyDesc::new().position(*rb.position()).build(); let nphysics_rb_handle = nphysics_bodies.insert(nphysics_rb); rapier2nphysics.insert(rapier_handle, nphysics_rb_handle); } for (_, collider) in colliders.iter() { let parent = &bodies[collider.parent()]; let nphysics_rb_handle = rapier2nphysics[&collider.parent()]; if let Some(collider) = nphysics_collider_from_rapier_collider(&collider, parent.is_dynamic()) { let nphysics_collider = collider.build(BodyPartHandle(nphysics_rb_handle, 0)); nphysics_colliders.insert(nphysics_collider); } else { eprintln!("Creating shape unknown to the nphysics backend.") } } for joint in joints.iter() { let b1 = BodyPartHandle(rapier2nphysics[&joint.1.body1], 0); let b2 = BodyPartHandle(rapier2nphysics[&joint.1.body2], 0); match &joint.1.params { JointParams::FixedJoint(params) => { let c = FixedConstraint::new( b1, b2, params.local_anchor1.translation.vector.into(), params.local_anchor1.rotation, params.local_anchor2.translation.vector.into(), params.local_anchor2.rotation, ); nphysics_joints.insert(c); } #[cfg(feature = "dim3")] JointParams::BallJoint(params) => { let c = BallConstraint::new(b1, b2, params.local_anchor1, params.local_anchor2); nphysics_joints.insert(c); } #[cfg(feature = "dim2")] JointParams::BallJoint(params) => { let c = RevoluteConstraint::new(b1, b2, params.local_anchor1, params.local_anchor2); nphysics_joints.insert(c); } #[cfg(feature = "dim3")] JointParams::RevoluteJoint(params) => { let c = RevoluteConstraint::new( b1, b2, params.local_anchor1, params.local_axis1, params.local_anchor2, params.local_axis2, ); nphysics_joints.insert(c); } JointParams::PrismaticJoint(params) => { let mut c = PrismaticConstraint::new( b1, b2, params.local_anchor1, params.local_axis1(), params.local_anchor2, ); if params.limits_enabled { c.enable_min_offset(params.limits[0]); c.enable_max_offset(params.limits[1]); } nphysics_joints.insert(c); } } } Self { rapier2nphysics, mechanical_world, geometrical_world, bodies: nphysics_bodies, colliders: nphysics_colliders, joints: nphysics_joints, force_generators, } } pub fn step(&mut self, counters: &mut Counters, params: &IntegrationParameters) { self.mechanical_world .integration_parameters .max_position_iterations = params.max_position_iterations; self.mechanical_world .integration_parameters .max_velocity_iterations = params.max_velocity_iterations; self.mechanical_world .integration_parameters .set_dt(params.dt()); counters.step_started(); self.mechanical_world.step( &mut self.geometrical_world, &mut self.bodies, &mut self.colliders, &mut self.joints, &mut self.force_generators, ); counters.step_completed(); } pub fn sync(&self, bodies: &mut RigidBodySet, colliders: &mut ColliderSet) { for (rapier_handle, nphysics_handle) in self.rapier2nphysics.iter() { let rb = bodies.get_mut(*rapier_handle).unwrap(); let ra = self.bodies.rigid_body(*nphysics_handle).unwrap(); let pos = *ra.position(); rb.set_position(pos, false); for coll_handle in rb.colliders() { let collider = &mut colliders[*coll_handle]; collider.set_position_debug(pos * collider.position_wrt_parent()); } } } } fn nphysics_collider_from_rapier_collider( collider: &Collider, is_dynamic: bool, ) -> Option<ColliderDesc<f32>> { let margin = ColliderDesc::<f32>::default_margin(); let mut pos = *collider.position_wrt_parent(); let shape = collider.shape(); let shape = if let Some(cuboid) = shape.as_cuboid() { ShapeHandle::new(Cuboid::new(cuboid.half_extents.map(|e| e - margin))) } else if let Some(ball) = shape.as_ball() { ShapeHandle::new(Ball::new(ball.radius - margin)) } else if let Some(capsule) = shape.as_capsule() { pos *= capsule.transform_wrt_y(); ShapeHandle::new(Capsule::new(capsule.half_height(), capsule.radius)) } else if let Some(heightfield) = shape.as_heightfield() { ShapeHandle::new(heightfield.clone()) } else { #[cfg(feature = "dim3")] if let Some(trimesh) = shape.as_trimesh() { ShapeHandle::new(TriMesh::new( trimesh.vertices().to_vec(), trimesh .indices() .iter() .map(|idx| na::convert(*idx)) .collect(), None, )) } else { return None; } #[cfg(feature = "dim2")] { return None; } }; let density = if is_dynamic { collider.density() } else { 0.0 }; Some( ColliderDesc::new(shape) .position(pos) .density(density) .sensor(collider.is_sensor()), ) }
use ncollide::shape::{Ball, Capsule, Cuboid, ShapeHandle}; use nphysics::force_generator::DefaultForceGeneratorSet; use nphysics::joint::{ DefaultJointConstraintSet, FixedConstraint, PrismaticConstraint, RevoluteConstraint, }; use nphysics::object::{ BodyPartHandle, ColliderDesc, DefaultBodyHandle, DefaultBodySet, DefaultColliderSet, RigidBodyDesc, }; use nphysics::world::{DefaultGeometricalWorld, DefaultMechanicalWorld}; use rapier::counters::Counters; use rapier::dynamics::{ IntegrationParameters, JointParams, JointSet, RigidBodyHandle, RigidBodySet, }; use rapier::geometry::{Collider, ColliderSet}; use rapier::math::Vector; use std::collections::HashMap; #[cfg(feature = "dim3")] use {ncollide::shape::TriMesh, nphysics::joint::BallConstraint}; pub struct NPhysicsWorld { rapier2nphysics: HashMap<RigidBodyHandle, DefaultBodyHandle>, mechanical_world: DefaultMechanicalWorld<f32>, geometrical_world: DefaultGeometricalWorld<f32>, bodies: DefaultBodySet<f32>, colliders: DefaultColliderSet<f32>, joints: DefaultJointConstraintSet<f32>, force_generators: DefaultForceGeneratorSet<f32>, } impl NPhysicsWorld { pub fn from_rapier( gravity: Vector<f32>, bodies: &RigidBodySet, colliders: &ColliderSet, joints: &JointSet, ) -> Self { let mut rapier2nphysics = HashMap::new(); let mechanical_world = DefaultMechanicalWorld::new(gravity); let geometrical_world = DefaultGeometricalWorld::new(); let mut nphysics_bodies = DefaultBodySet::new(); let mut nphysics_colliders = DefaultColliderSet::new(); let mut nphysics_joints = DefaultJointConstraintSet::new(); let force_generators = DefaultForceGeneratorSet::new(); for (rapier_handle, rb) in bodies.iter() { let nphysics_rb = RigidBodyDesc::new().position(*rb.position()).build(); let nphysics_rb_handle = nphysics_bodies.insert(nphysics_rb); rapier2nphysics.insert(rapier_handle, nphysics_rb_handle); } for (_, collider) in colliders.iter() { let parent = &bodies[collider.parent()]; let nphysics_rb_handle = rapier2nphysics[&collider.parent()]; if let Some(collider) = nphysics_collider_from_rapier_collider(&collider, parent.is_dynamic()) { let nphysics_collider = collider.build(BodyPartHandle(nphysics_rb_handle, 0)); nphysics_colliders.insert(nphysics_collider); } else { eprintln!("Creating shape unknown to the nphysics backend.") } } for joint in joints.iter() { let b1 = BodyPartHandle(rapier2nphysics[&joint.1.body1], 0); let b2 = BodyPartHandle(rapier2nphysics[&joint.1.body2], 0); match &joint.1.params { JointParams::FixedJoint(params) => { let c = FixedConstraint::new( b1, b2, params.local_anchor1.translation.vector.into(), params.local_anchor1.rotation, params.local_anchor2.translation.vector.into(), params.local_anchor2.rotation, ); nphysics_joints.insert(c); } #[cfg(feature = "dim3")] JointParams::BallJoint(params) => { let c = BallConstraint::new(b1, b2, params.local_anchor1, params.local_anchor2); nphysics_joints.insert(c); } #[cfg(feature = "dim2")] JointParams::BallJoint(params) => { let c = RevoluteConstraint::new(b1, b2, params.local_anchor1, params.local_anchor2); nphysics_joints.insert(c); } #[cfg(feature = "dim3")] JointParams::RevoluteJoint(params) => { let c = RevoluteConstraint::new( b1, b2, params.local_anchor1, params.local_axis1, params.local_anchor2, params.local_axis2, ); nphysics_joints.insert(c); } JointParams::PrismaticJoint(params) => { let mut c = PrismaticConstraint::new( b1, b2, params.local_anchor1, params.local_axis1(), params.local_anchor2, ); if params.limits_enabled { c.enable_min_offset(params.limits[0]); c.enable_max_offset(params.limits[1]); } nphysics_joints.insert(c); } } } Self { rapier2nphysics, mechanical_world, geometrical_world, bodies: nphysics_bodies, colliders: nphysics_colliders, joints: nphysics_joints, force_generators, } } pub fn step(&mut self, counters: &mut Counters, params: &IntegrationParameters) { self.mechanical_world .integration_parameters .max_position_iterations = params.max_position_iterations; self.mechanical_world .integration_parameters .max_velocity_iterations = params.max_velocity_iterations; self.mechanical_world .integration_parameters .set_dt(params.dt()); counters.step_started(); self.mechanical_world.step( &mut self.geometrical_world, &mut self.bodies, &mut self.colliders, &mut self.joints, &mut self.force_generators, ); counters.step_completed(); } pub fn sync(&self, bodies: &mut RigidBodySet, colliders: &mut ColliderSet) { for (rapier_handle, nphysics_handle) in self.rapier2nphysics.iter() { let rb = bodies.get_mut(*rapier_handle).unwrap(); let ra = self.bodies.rigid_body(*nphysics_handle).unwrap(); let pos = *ra.position(); rb.set_position(pos, false); for coll_handle in rb.colliders() { let collider = &mut colliders[*coll_handle]; collider.set_position_debug(pos * collider.position_wrt_parent()); } } } } fn nphysics_collider_from_rapier_collider( collider: &Collider, is_dynamic: bool, ) -> Option<ColliderDesc<f32>> { let margin = ColliderDesc::<f32>::default_margin(); let mut pos = *collider.position_wrt_parent(); let shape = collider.shape(); let shape = if let Some(cuboid) = shape.as_cuboid() { ShapeHandle::new(Cuboid::new(cuboid.half_extents.map(|e| e - margin))) } else if let Some(ball) = shape.as_ball() { ShapeHandle::new(Ball::new(ball.radius - margin)) } else if let Some(capsule) = shape.as_capsule() { pos *= capsule.transform_wrt_y(); ShapeHandle::new(Capsule::new(capsule.half_height(), capsule.radius)) } else if let Some(heightfield) = shape.as_heightfield() { ShapeHandle::new(heightfield.clone()) } else { #[cfg(feature = "dim3")] if let Some(trimesh) = shape.as_trimesh() { ShapeHandle::new(TriMesh::new( trimesh.vertices().to_vec(), trimesh .indices() .iter() .map(|idx| na::convert(*idx)) .collect(), None, )) } else { return None; } #[cfg(feature = "dim2")] { return None; } }; let density = if is_dynamic { collider.density() } else { 0.0 };
}
Some( ColliderDesc::new(shape) .position(pos) .density(density) .sensor(collider.is_sensor()), )
call_expression
[ { "content": "pub fn generate_contacts_trimesh_shape(ctxt: &mut ContactGenerationContext) {\n\n let collider1 = &ctxt.colliders[ctxt.pair.pair.collider1];\n\n let collider2 = &ctxt.colliders[ctxt.pair.pair.collider2];\n\n\n\n if let Some(trimesh1) = collider1.shape().as_trimesh() {\n\n do_genera...
Rust
tests/cli-v1.rs
Boddlnagg/rustup.rs
c4e7616c565630d0ad93767ec8676c8a570995c5
extern crate rustup_dist; extern crate rustup_utils; extern crate rustup_mock; extern crate tempdir; use std::fs; use tempdir::TempDir; use rustup_mock::clitools::{self, Config, Scenario, expect_ok, expect_stdout_ok, expect_err, expect_stderr_ok, set_current_dist_date, this_host_triple}; macro_rules! for_host { ($s: expr) => (&format!($s, this_host_triple())) } pub fn setup(f: &Fn(&mut Config)) { clitools::setup(Scenario::SimpleV1, f); } #[test] fn rustc_no_default_toolchain() { setup(&|config| { expect_err(config, &["rustc"], "no default toolchain configured"); }); } #[test] fn expected_bins_exist() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "1.3.0"); }); } #[test] fn install_toolchain_from_channel() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); expect_ok(config, &["rustup", "default", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); expect_ok(config, &["rustup", "default", "stable"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } #[test] fn install_toolchain_from_archive() { clitools::setup(Scenario::ArchivesV1, &|config| { expect_ok(config, &["rustup", "default" , "nightly-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); expect_ok(config, &["rustup", "default" , "beta-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-1"); expect_ok(config, &["rustup", "default" , "stable-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-1"); }); } #[test] fn install_toolchain_from_version() { setup(&|config| { expect_ok(config, &["rustup", "default" , "1.1.0"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } #[test] fn default_existing_toolchain() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_stderr_ok(config, &["rustup", "default", "nightly"], for_host!("using existing install for 'nightly-{0}'")); }); } #[test] fn update_channel() { clitools::setup(Scenario::ArchivesV1, &|config| { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "default", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } #[test] fn list_toolchains() { clitools::setup(Scenario::ArchivesV1, &|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "update", "beta-2015-01-01"]); expect_stdout_ok(config, &["rustup", "toolchain", "list"], "nightly"); expect_stdout_ok(config, &["rustup", "toolchain", "list"], "beta-2015-01-01"); }); } #[test] fn list_toolchains_with_none() { setup(&|config| { expect_stdout_ok(config, &["rustup", "toolchain", "list"], "no installed toolchains"); }); } #[test] fn remove_toolchain() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]); expect_ok(config, &["rustup", "toolchain", "list"]); expect_stdout_ok(config, &["rustup", "toolchain", "list"], "no installed toolchains"); }); } #[test] fn remove_default_toolchain_err_handling() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]); expect_err(config, &["rustc"], for_host!("toolchain 'nightly-{0}' is not installed")); }); } #[test] fn remove_override_toolchain_err_handling() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_ok(config, &["rustup", "toolchain", "remove", "beta"]); expect_err(config, &["rustc"], for_host!("toolchain 'beta-{0}' is not installed")); }); }); } #[test] fn bad_sha_on_manifest() { setup(&|config| { let sha_file = config.distdir.join("dist/channel-rust-nightly.sha256"); let sha_str = rustup_utils::raw::read_file(&sha_file).unwrap(); let mut sha_bytes = sha_str.into_bytes(); sha_bytes[..10].clone_from_slice(b"aaaaaaaaaa"); let sha_str = String::from_utf8(sha_bytes).unwrap(); rustup_utils::raw::write_file(&sha_file, &sha_str).unwrap(); expect_err(config, &["rustup", "default", "nightly"], "checksum failed"); }); } #[test] fn bad_sha_on_installer() { setup(&|config| { let dir = config.distdir.join("dist"); for file in fs::read_dir(&dir).unwrap() { let file = file.unwrap(); let path = file.path(); let filename = path.to_string_lossy(); if filename.ends_with(".tar.gz") || filename.ends_with(".tar.xz") { rustup_utils::raw::write_file(&path, "xxx").unwrap(); } } expect_err(config, &["rustup", "default", "nightly"], "checksum failed"); }); } #[test] fn install_override_toolchain_from_channel() { setup(&|config| { expect_ok(config, &["rustup", "override", "add", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); expect_ok(config, &["rustup", "override", "add", "stable"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } #[test] fn install_override_toolchain_from_archive() { clitools::setup(Scenario::ArchivesV1, &|config| { expect_ok(config, &["rustup", "override", "add", "nightly-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); expect_ok(config, &["rustup", "override", "add", "beta-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-1"); expect_ok(config, &["rustup", "override", "add", "stable-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-1"); }); } #[test] fn install_override_toolchain_from_version() { setup(&|config| { expect_ok(config, &["rustup", "override", "add", "1.1.0"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } #[test] fn override_overrides_default() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); expect_ok(config, &["rustup", "default" , "nightly"]); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "override" , "add", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); }); }); } #[test] fn multiple_overrides() { setup(&|config| { let tempdir1 = TempDir::new("rustup").unwrap(); let tempdir2 = TempDir::new("rustup").unwrap(); expect_ok(config, &["rustup", "default", "nightly"]); config.change_dir(tempdir1.path(), &|| { expect_ok(config, &["rustup", "override", "add", "beta"]); }); config.change_dir(tempdir2.path(), &|| { expect_ok(config, &["rustup", "override", "add", "stable"]); }); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); config.change_dir(tempdir1.path(), &|| { expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); }); config.change_dir(tempdir2.path(), &|| { expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); }); } #[test] fn change_override() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "override", "add", "nightly"]); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); }); }); } #[test] fn remove_override_no_default() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "override", "add", "nightly"]); expect_ok(config, &["rustup", "override", "remove"]); expect_err(config, &["rustc"], "no default toolchain configured"); }); }); } #[test] fn remove_override_with_default() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_ok(config, &["rustup", "override", "remove"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); }); } #[test] fn remove_override_with_multiple_overrides() { setup(&|config| { let tempdir1 = TempDir::new("rustup").unwrap(); let tempdir2 = TempDir::new("rustup").unwrap(); expect_ok(config, &["rustup", "default", "nightly"]); config.change_dir(tempdir1.path(), &|| { expect_ok(config, &["rustup", "override", "add", "beta"]); }); config.change_dir(tempdir2.path(), &|| { expect_ok(config, &["rustup", "override", "add", "stable"]); }); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); config.change_dir(tempdir1.path(), &|| { expect_ok(config, &["rustup", "override", "remove"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); config.change_dir(tempdir2.path(), &|| { expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); }); } #[test] fn no_update_on_channel_when_date_has_not_changed() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_stdout_ok(config, &["rustup", "update", "nightly"], "unchanged"); }); } #[test] fn update_on_channel_when_date_has_changed() { clitools::setup(Scenario::ArchivesV1, &|config| { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "default", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } #[test] fn run_command() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "default", "beta"]); expect_stdout_ok(config, &["rustup", "run", "nightly", "rustc" , "--version"], "hash-n-2"); }); } #[test] fn remove_toolchain_then_add_again() { setup(&|config| { expect_ok(config, &["rustup", "default", "beta"]); expect_ok(config, &["rustup", "toolchain", "remove", "beta"]); expect_ok(config, &["rustup", "update", "beta"]); expect_ok(config, &["rustc", "--version"]); }); }
extern crate rustup_dist; extern crate rustup_utils; extern crate rustup_mock; extern crate tempdir; use std::fs; use tempdir::TempDir; use rustup_mock::clitools::{self, Config, Scenario, expect_ok, expect_stdout_ok, expect_err, expect_stderr_ok, set_current_dist_date, this_host_triple}; macro_rules! for_host { ($s: expr) => (&format!($s, this_host_triple())) } pub fn setup(f: &Fn(&mut Config)) { clitools::setup(Scenario::SimpleV1, f); } #[test] fn rustc_no_default_toolchain() { setup(&|config| { expect_err(config, &["rustc"], "no default toolchain configured"); }); } #[test] fn expected_bins_exist() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "1.3.0"); }); } #[test] fn install_toolchain_from_channel() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); expect_ok(config, &["rustup", "default", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); expect_ok(config, &["rustup", "default", "stable"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } #[test] fn install_toolchain_from_archive() { clitools::setup(Scenario::ArchivesV1, &|config| { expect_ok(config, &["rustup", "default" , "nightly-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); expect_ok(config, &["rustup", "default" , "beta-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-1"); expect_ok(config, &["rustup", "default" , "stable-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-1"); }); } #[test]
#[test] fn default_existing_toolchain() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_stderr_ok(config, &["rustup", "default", "nightly"], for_host!("using existing install for 'nightly-{0}'")); }); } #[test] fn update_channel() { clitools::setup(Scenario::ArchivesV1, &|config| { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "default", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } #[test] fn list_toolchains() { clitools::setup(Scenario::ArchivesV1, &|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "update", "beta-2015-01-01"]); expect_stdout_ok(config, &["rustup", "toolchain", "list"], "nightly"); expect_stdout_ok(config, &["rustup", "toolchain", "list"], "beta-2015-01-01"); }); } #[test] fn list_toolchains_with_none() { setup(&|config| { expect_stdout_ok(config, &["rustup", "toolchain", "list"], "no installed toolchains"); }); } #[test] fn remove_toolchain() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]); expect_ok(config, &["rustup", "toolchain", "list"]); expect_stdout_ok(config, &["rustup", "toolchain", "list"], "no installed toolchains"); }); } #[test] fn remove_default_toolchain_err_handling() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]); expect_err(config, &["rustc"], for_host!("toolchain 'nightly-{0}' is not installed")); }); } #[test] fn remove_override_toolchain_err_handling() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_ok(config, &["rustup", "toolchain", "remove", "beta"]); expect_err(config, &["rustc"], for_host!("toolchain 'beta-{0}' is not installed")); }); }); } #[test] fn bad_sha_on_manifest() { setup(&|config| { let sha_file = config.distdir.join("dist/channel-rust-nightly.sha256"); let sha_str = rustup_utils::raw::read_file(&sha_file).unwrap(); let mut sha_bytes = sha_str.into_bytes(); sha_bytes[..10].clone_from_slice(b"aaaaaaaaaa"); let sha_str = String::from_utf8(sha_bytes).unwrap(); rustup_utils::raw::write_file(&sha_file, &sha_str).unwrap(); expect_err(config, &["rustup", "default", "nightly"], "checksum failed"); }); } #[test] fn bad_sha_on_installer() { setup(&|config| { let dir = config.distdir.join("dist"); for file in fs::read_dir(&dir).unwrap() { let file = file.unwrap(); let path = file.path(); let filename = path.to_string_lossy(); if filename.ends_with(".tar.gz") || filename.ends_with(".tar.xz") { rustup_utils::raw::write_file(&path, "xxx").unwrap(); } } expect_err(config, &["rustup", "default", "nightly"], "checksum failed"); }); } #[test] fn install_override_toolchain_from_channel() { setup(&|config| { expect_ok(config, &["rustup", "override", "add", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); expect_ok(config, &["rustup", "override", "add", "stable"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } #[test] fn install_override_toolchain_from_archive() { clitools::setup(Scenario::ArchivesV1, &|config| { expect_ok(config, &["rustup", "override", "add", "nightly-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); expect_ok(config, &["rustup", "override", "add", "beta-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-1"); expect_ok(config, &["rustup", "override", "add", "stable-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-1"); }); } #[test] fn install_override_toolchain_from_version() { setup(&|config| { expect_ok(config, &["rustup", "override", "add", "1.1.0"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } #[test] fn override_overrides_default() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); expect_ok(config, &["rustup", "default" , "nightly"]); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "override" , "add", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); }); }); } #[test] fn multiple_overrides() { setup(&|config| { let tempdir1 = TempDir::new("rustup").unwrap(); let tempdir2 = TempDir::new("rustup").unwrap(); expect_ok(config, &["rustup", "default", "nightly"]); config.change_dir(tempdir1.path(), &|| { expect_ok(config, &["rustup", "override", "add", "beta"]); }); config.change_dir(tempdir2.path(), &|| { expect_ok(config, &["rustup", "override", "add", "stable"]); }); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); config.change_dir(tempdir1.path(), &|| { expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); }); config.change_dir(tempdir2.path(), &|| { expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); }); } #[test] fn change_override() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "override", "add", "nightly"]); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); }); }); } #[test] fn remove_override_no_default() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "override", "add", "nightly"]); expect_ok(config, &["rustup", "override", "remove"]); expect_err(config, &["rustc"], "no default toolchain configured"); }); }); } #[test] fn remove_override_with_default() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_ok(config, &["rustup", "override", "remove"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); }); } #[test] fn remove_override_with_multiple_overrides() { setup(&|config| { let tempdir1 = TempDir::new("rustup").unwrap(); let tempdir2 = TempDir::new("rustup").unwrap(); expect_ok(config, &["rustup", "default", "nightly"]); config.change_dir(tempdir1.path(), &|| { expect_ok(config, &["rustup", "override", "add", "beta"]); }); config.change_dir(tempdir2.path(), &|| { expect_ok(config, &["rustup", "override", "add", "stable"]); }); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); config.change_dir(tempdir1.path(), &|| { expect_ok(config, &["rustup", "override", "remove"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); config.change_dir(tempdir2.path(), &|| { expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); }); } #[test] fn no_update_on_channel_when_date_has_not_changed() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_stdout_ok(config, &["rustup", "update", "nightly"], "unchanged"); }); } #[test] fn update_on_channel_when_date_has_changed() { clitools::setup(Scenario::ArchivesV1, &|config| { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "default", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } #[test] fn run_command() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "default", "beta"]); expect_stdout_ok(config, &["rustup", "run", "nightly", "rustc" , "--version"], "hash-n-2"); }); } #[test] fn remove_toolchain_then_add_again() { setup(&|config| { expect_ok(config, &["rustup", "default", "beta"]); expect_ok(config, &["rustup", "toolchain", "remove", "beta"]); expect_ok(config, &["rustup", "update", "beta"]); expect_ok(config, &["rustc", "--version"]); }); }
fn install_toolchain_from_version() { setup(&|config| { expect_ok(config, &["rustup", "default" , "1.1.0"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); }
function_block-full_function
[ { "content": "pub fn rustc_version(toolchain: &Toolchain) -> String {\n\n if toolchain.exists() {\n\n let rustc_path = toolchain.binary_file(\"rustc\");\n\n if utils::is_file(&rustc_path) {\n\n let mut cmd = Command::new(&rustc_path);\n\n cmd.arg(\"--version\");\n\n ...
Rust
src/bin/vessel.rs
ByronBecker/vessel
a2c2d3c2ffe39b3802a82be512f812e75ee32ea2
use anyhow::Result; use fern::colors::ColoredLevelConfig; use fern::Output; use log::LevelFilter; use std::io::Write; use std::path::PathBuf; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(about = "Simple package management for Motoko")] struct Opts { #[structopt(long, parse(from_os_str), default_value = "package-set.dhall")] package_set: PathBuf, #[structopt(subcommand)] command: Command, } #[derive(Debug, StructOpt)] enum Command { Init, Install, UpgradeSet { tag: Option<String>, }, Sources, Bin, Verify { #[structopt(long)] version: Option<String>, #[structopt(long, parse(from_os_str))] moc: Option<PathBuf>, #[structopt(long)] moc_args: Option<String>, #[structopt()] package: Option<String>, }, } fn setup_logger(opts: &Opts) -> Result<(), fern::InitError> { let (log_level, out_channel): (LevelFilter, Output) = match opts.command { Command::Sources | Command::Bin => (log::LevelFilter::Info, std::io::stderr().into()), _ => (log::LevelFilter::Info, std::io::stdout().into()), }; let colors = ColoredLevelConfig::new(); fern::Dispatch::new() .format(move |out, message, record| { out.finish(format_args!( "[{}] {}", colors.color(record.level()), message )) }) .level(log_level) .chain(out_channel) .apply()?; Ok(()) } fn main() -> Result<()> { let opts = Opts::from_args(); setup_logger(&opts)?; match opts.command { Command::Init => vessel::init(), Command::Install => { let vessel = vessel::Vessel::new(&opts.package_set)?; let _ = vessel.install_packages()?; Ok(()) } Command::UpgradeSet { tag } => { let (url, hash) = match tag { None => vessel::fetch_latest_package_set()?, Some(tag) => vessel::fetch_package_set(&tag)?, }; println!("let upstream =\n {} {}", url, hash); Ok(()) } Command::Bin => { let vessel = vessel::Vessel::new(&opts.package_set)?; let path = vessel.install_compiler()?; print!("{}", path.display().to_string()); std::io::stdout().flush()?; Ok(()) } Command::Sources => { let vessel = vessel::Vessel::new(&opts.package_set)?; let sources = vessel .install_packages()? .into_iter() .map(|(name, path)| format!("--package {} {}", name, path.display().to_string())) .collect::<Vec<_>>() .join(" "); print!("{}", sources); std::io::stdout().flush()?; Ok(()) } Command::Verify { moc, moc_args, version, package, } => { let vessel = vessel::Vessel::new_without_manifest(&opts.package_set)?; let moc = match (moc, version) { (None, None) => PathBuf::from("moc"), (Some(moc), None) => moc, (None, Some(version)) => { let bin_path = vessel::download_compiler(&version)?; bin_path.join("moc") } (Some(_), Some(_)) => { return Err(anyhow::anyhow!( "The --version and --moc flags are mutually exclusive." )) } }; match package { None => vessel.verify_all(&moc, &moc_args), Some(package) => vessel.verify_package(&moc, &moc_args, &package), } } } }
use anyhow::Result; use fern::colors::ColoredLevelConfig; use fern::Output; use log::LevelFilter; use std::io::Write; use std::path::PathBuf; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(about = "Simple package management for Motoko")] struct Opts { #[structopt(long, parse(from_os_str), default_value = "package-set.dhall")] package_set: PathBuf, #[structopt(subcommand)] command: Command, } #[derive(Debug, StructOpt)] enum Command { Init, Install, UpgradeSet { tag: Option<String>, }, Sources, Bin, Verify { #[structopt(long)] version: Option<String>, #[structopt(long, parse(from_os_str))] moc: Option<PathBuf>, #[structopt(long)] moc_args: Option<String>, #[structopt()] package: Option<String>, }, } fn setup_logger(opts: &Opts) -> Result<(), fern::InitError> { let (log_level, out_channel): (LevelFilter, Output) = match opts.command { Command::Sources | Command::Bin => (log::LevelFilter::Info, std::io::stderr().into()), _ => (log::LevelFilter::Info, std::io::stdout().into()), }; let colors = ColoredLevelConfig::new(); fern::Dispatch::new() .format(move |out, message, record| { out.finish(format_args!( "[{}] {}", colors.color(record.level()), message )) }) .level(log_level) .chain(out_channel) .apply()?; Ok(()) } fn main() -> Result<()> { let opts = Opts::from_args(); setup_logger(&opts)?; match opts.command { Command::Init => vessel::init(), Command::Install => { let vessel = vessel::Vessel::new(&opts.package_set)?; let _ = vessel.install_packages()?; Ok(()) } Command::UpgradeSet { tag } => { let (url, hash) = match tag { None => vessel::fetch_latest_package_set()?, Some(tag) => vessel::fetch_package_set(&tag)?, }; println!("let upstream =\n {} {}", url, hash); Ok(()) } Command::Bin => { let vessel = vessel::
bin_path.join("moc") } (Some(_), Some(_)) => { return Err(anyhow::anyhow!( "The --version and --moc flags are mutually exclusive." )) } }; match package { None => vessel.verify_all(&moc, &moc_args), Some(package) => vessel.verify_package(&moc, &moc_args, &package), } } } }
Vessel::new(&opts.package_set)?; let path = vessel.install_compiler()?; print!("{}", path.display().to_string()); std::io::stdout().flush()?; Ok(()) } Command::Sources => { let vessel = vessel::Vessel::new(&opts.package_set)?; let sources = vessel .install_packages()? .into_iter() .map(|(name, path)| format!("--package {} {}", name, path.display().to_string())) .collect::<Vec<_>>() .join(" "); print!("{}", sources); std::io::stdout().flush()?; Ok(()) } Command::Verify { moc, moc_args, version, package, } => { let vessel = vessel::Vessel::new_without_manifest(&opts.package_set)?; let moc = match (moc, version) { (None, None) => PathBuf::from("moc"), (Some(moc), None) => moc, (None, Some(version)) => { let bin_path = vessel::download_compiler(&version)?;
function_block-random_span
[ { "content": "/// Like `fetch_latest_package_set`, but lets you specify the tag\n\npub fn fetch_package_set(tag: &str) -> Result<(Url, Hash)> {\n\n let client = reqwest::blocking::Client::new();\n\n fetch_package_set_impl(&client, tag)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score"...
Rust
crates/binding_core_node/src/parse.rs
10088/swc
6bc39005bb851b57f4f49b046688f4acc6e850f3
use std::{ path::{Path, PathBuf}, sync::Arc, }; use anyhow::Context as _; use napi::{ bindgen_prelude::{AbortSignal, AsyncTask, Buffer}, Env, Task, }; use swc::{ config::{ErrorFormat, ParseOptions}, Compiler, }; use swc_common::{comments::Comments, FileName}; use swc_nodejs_common::{deserialize_json, get_deserialized, MapErr}; use crate::{get_compiler, util::try_with}; pub struct ParseTask { pub c: Arc<Compiler>, pub filename: FileName, pub src: String, pub options: String, } pub struct ParseFileTask { pub c: Arc<Compiler>, pub path: PathBuf, pub options: String, } #[napi] impl Task for ParseTask { type JsValue = String; type Output = String; fn compute(&mut self) -> napi::Result<Self::Output> { let options: ParseOptions = deserialize_json(&self.options)?; let fm = self .c .cm .new_source_file(self.filename.clone(), self.src.clone()); let comments = if options.comments { Some(self.c.comments() as &dyn Comments) } else { None }; let program = try_with(self.c.cm.clone(), false, ErrorFormat::Normal, |handler| { self.c.parse_js( fm, handler, options.target, options.syntax, options.is_module, comments, ) }) .convert_err()?; let ast_json = serde_json::to_string(&program)?; Ok(ast_json) } fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> { Ok(result) } } #[napi] impl Task for ParseFileTask { type JsValue = String; type Output = String; fn compute(&mut self) -> napi::Result<Self::Output> { let program = try_with(self.c.cm.clone(), false, ErrorFormat::Normal, |handler| { self.c.run(|| { let options: ParseOptions = deserialize_json(&self.options)?; let fm = self .c .cm .load_file(&self.path) .context("failed to read module")?; let c = self.c.comments().clone(); let comments = if options.comments { Some(&c as &dyn Comments) } else { None }; self.c.parse_js( fm, handler, options.target, options.syntax, options.is_module, comments, ) }) }) .convert_err()?; let ast_json = serde_json::to_string(&program)?; Ok(ast_json) } fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> { Ok(result) } } #[napi] pub fn parse( src: String, options: Buffer, filename: Option<String>, signal: Option<AbortSignal>, ) -> AsyncTask<ParseTask> { swc_nodejs_common::init_default_trace_subscriber(); let c = get_compiler(); let options = String::from_utf8_lossy(options.as_ref()).to_string(); let filename = if let Some(value) = filename { FileName::Real(value.into()) } else { FileName::Anon }; AsyncTask::with_optional_signal( ParseTask { c, filename, src, options, }, signal, ) } #[napi] pub fn parse_sync(src: String, opts: Buffer, filename: Option<String>) -> napi::Result<String> { swc_nodejs_common::init_default_trace_subscriber(); let c = get_compiler(); let options: ParseOptions = get_deserialized(&opts)?; let filename = if let Some(value) = filename { FileName::Real(value.into()) } else { FileName::Anon }; let program = try_with(c.cm.clone(), false, ErrorFormat::Normal, |handler| { c.run(|| { let fm = c.cm.new_source_file(filename, src); let comments = if options.comments { Some(c.comments() as &dyn Comments) } else { None }; c.parse_js( fm, handler, options.target, options.syntax, options.is_module, comments, ) }) }) .convert_err()?; Ok(serde_json::to_string(&program)?) } #[napi] pub fn parse_file_sync(path: String, opts: Buffer) -> napi::Result<String> { swc_nodejs_common::init_default_trace_subscriber(); let c = get_compiler(); let options: ParseOptions = get_deserialized(&opts)?; let program = { try_with(c.cm.clone(), false, ErrorFormat::Normal, |handler| { let fm = c.cm.load_file(Path::new(path.as_str())) .expect("failed to read program file"); let comments = if options.comments { Some(c.comments() as &dyn Comments) } else { None }; c.parse_js( fm, handler, options.target, options.syntax, options.is_module, comments, ) }) } .convert_err()?; Ok(serde_json::to_string(&program)?) } #[napi] pub fn parse_file( path: String, options: Buffer, signal: Option<AbortSignal>, ) -> AsyncTask<ParseFileTask> { swc_nodejs_common::init_default_trace_subscriber(); let c = get_compiler(); let path = PathBuf::from(&path); let options = String::from_utf8_lossy(options.as_ref()).to_string(); AsyncTask::with_optional_signal(ParseFileTask { c, path, options }, signal) }
use std::{ path::{Path, PathBuf}, sync::Arc, }; use anyhow::Context as _; use napi::{ bindgen_prelude::{AbortSignal, AsyncTask, Buffer}, Env, Task, }; use swc::{ config::{ErrorFormat, ParseOptions}, Compiler, }; use swc_common::{comments::Comments, FileName}; use swc_nodejs_common::{deserialize_json, get_deserialized, MapErr}; use crate::{get_compiler, util::try_with}; pub struct ParseTask { pub c: Arc<Compiler>, pub filename: FileName, pub src: String, pub options: String, } pub struct ParseFileTask { pub c: Arc<Compiler>, pub path: PathBuf, pub options: String, } #[napi] impl Task for ParseTask { type JsValue = String; type Output = String; fn compute(&mut self) -> napi::Result<Self::Output> { let options: ParseOptions = deserialize_json(&self.options)?; let fm = self .c .cm .new_source_file(self.filename.clone(), self.src.clone()); let comments = if options.comments { Some(self.c.comments() as &dyn Comments) } else { None }; let program = try_with(self.c.cm.clone(), false, ErrorFormat::Normal, |handler| { self.c.parse_js( fm, handler, options.target, options.syntax, options.is_module, comments, ) }) .convert_err()?; let ast_json = serde_json::to_string(&program)?; Ok(ast_json) } fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> { Ok(result) } } #[napi] impl Task for ParseFileTask { type JsValue = String; type Output = String; fn compute(&mut self) -> napi::Result<Self::Output> { let program = try_with(self.c.cm.clone(), false, ErrorFormat::Normal, |handler| { self.c.run(|| { let options: ParseOptions = deserialize_json(&self.options)?; let fm = self .c .cm .load_file(&self.path) .context("failed to read module")?; let c = self.c.comments().clone(); let comments = if options.comments { Some(&c as &dyn Comments) } else { None }; self.c.parse_js( fm, handler, options.target, options.syntax, options.is_module, comments, ) }) }) .convert_err()?; let ast_json = serde_json::to_string(&program)?; Ok(ast_json) } fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> { Ok(result) } } #[napi] pub fn parse( src: String, options: Buffer, filename: Option<String>, signal: Option<AbortSignal>, ) -> AsyncTask<ParseTask> { swc_nodejs_common::init_default_trace_subscriber(); let c = get_compiler(); let options = String::from_utf8_lossy(options.as_ref()).to_string(); let filename = if let Some(value) = filename { FileName::Real(value.into()) } else { FileName::Anon }; AsyncTask::with_optional_signal( ParseTask { c, filename, src, options, }, signal, ) } #[napi] pub fn parse_sync(src: String, opts: Buffer, filename: Option<String>) -> napi::Result<String> { swc_nodejs_common::init_default_trace_subscriber(); let c = get_compiler(); let options: ParseOptions = get_deserialized(&opts)?; let filename = if let Some(value) = filename { FileName::Real(value.into()) } else { FileName::Anon }; let program = try_with(c.cm.clone(), false, ErrorFormat::Normal, |handler| { c.run(|| { let fm = c.cm.new_source_file(filename, src);
c.parse_js( fm, handler, options.target, options.syntax, options.is_module, comments, ) }) }) .convert_err()?; Ok(serde_json::to_string(&program)?) } #[napi] pub fn parse_file_sync(path: String, opts: Buffer) -> napi::Result<String> { swc_nodejs_common::init_default_trace_subscriber(); let c = get_compiler(); let options: ParseOptions = get_deserialized(&opts)?; let program = { try_with(c.cm.clone(), false, ErrorFormat::Normal, |handler| { let fm = c.cm.load_file(Path::new(path.as_str())) .expect("failed to read program file"); let comments = if options.comments { Some(c.comments() as &dyn Comments) } else { None }; c.parse_js( fm, handler, options.target, options.syntax, options.is_module, comments, ) }) } .convert_err()?; Ok(serde_json::to_string(&program)?) } #[napi] pub fn parse_file( path: String, options: Buffer, signal: Option<AbortSignal>, ) -> AsyncTask<ParseFileTask> { swc_nodejs_common::init_default_trace_subscriber(); let c = get_compiler(); let path = PathBuf::from(&path); let options = String::from_utf8_lossy(options.as_ref()).to_string(); AsyncTask::with_optional_signal(ParseFileTask { c, path, options }, signal) }
let comments = if options.comments { Some(c.comments() as &dyn Comments) } else { None };
assignment_statement
[]
Rust
rlp/src/impls.rs
Byeongjee/rlp
6a4c2c39f76eba2b3b68863941cd64fddee3e5cc
use super::stream::RlpStream; use super::traits::{Decodable, Encodable}; use super::{DecoderError, Rlp}; use primitives::{H128, H160, H256, H384, H512, H520, H768, U256}; use std::iter::{empty, once}; use std::{cmp, mem, str}; pub fn decode_usize(bytes: &[u8]) -> Result<usize, DecoderError> { let expected = mem::size_of::<usize>(); match bytes.len() { l if l <= expected => { if bytes[0] == 0 { return Err(DecoderError::RlpInvalidIndirection) } let mut res = 0usize; for (i, byte) in bytes.iter().enumerate() { let shift = (l - 1 - i) * 8; res += (*byte as usize) << shift; } Ok(res) } got => Err(DecoderError::RlpIsTooBig { expected, got, }), } } impl Encodable for bool { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_iter(once(if *self { 1u8 } else { 0 })); } } impl Decodable for bool { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| match bytes.len() { 0 => Ok(false), 1 => Ok(bytes[0] != 0), got => Err(DecoderError::RlpIsTooBig { expected: 1, got, }), }) } } impl<'a> Encodable for &'a [u8] { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self); } } impl Encodable for Vec<u8> { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self); } } impl Decodable for Vec<u8> { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| Ok(bytes.to_vec())) } } impl Encodable for Vec<Vec<u8>> { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(self.len()); for e in self { s.append(e); } } } impl Decodable for Vec<Vec<u8>> { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.as_list::<Vec<u8>>() } } impl<T> Encodable for Option<T> where T: Encodable, { fn rlp_append(&self, s: &mut RlpStream) { match *self { None => { s.begin_list(0); } Some(ref value) => { s.begin_list(1); s.append(value); } } } } impl<T> Decodable for Option<T> where T: Decodable, { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { let items = rlp.item_count()?; match items { 1 => rlp.val_at(0).map(Some), 0 => Ok(None), got => Err(DecoderError::RlpIncorrectListLen { expected: 1, got, }), } } } impl Encodable for u8 { fn rlp_append(&self, s: &mut RlpStream) { if *self != 0 { s.encoder().encode_iter(once(*self)); } else { s.encoder().encode_iter(empty()); } } } impl Decodable for u8 { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| match bytes.len() { 1 if bytes[0] != 0 => Ok(bytes[0]), 0 => Ok(0), 1 => Err(DecoderError::RlpInvalidIndirection), got => Err(DecoderError::RlpIsTooBig { expected: 1, got, }), }) } } macro_rules! impl_encodable_for_u { ($name: ident) => { impl Encodable for $name { fn rlp_append(&self, s: &mut RlpStream) { let leading_empty_bytes = self.leading_zeros() as usize / 8; let buffer = self.to_be_bytes(); s.encoder().encode_value(&buffer[leading_empty_bytes..]); } } }; } macro_rules! impl_decodable_for_u { ($name: ident) => { impl Decodable for $name { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| match bytes.len() { 0 | 1 => u8::decode(rlp).map($name::from), l if l <= mem::size_of::<$name>() => { if bytes[0] == 0 { return Err(DecoderError::RlpInvalidIndirection) } let mut res = 0 as $name; for (i, byte) in bytes.iter().enumerate() { let shift = (l - 1 - i) * 8; res += $name::from(*byte) << shift; } Ok(res) } got => Err(DecoderError::RlpIsTooBig { expected: mem::size_of::<$name>(), got, }), }) } } }; } impl_encodable_for_u!(u16); impl_encodable_for_u!(u32); impl_encodable_for_u!(u64); impl_encodable_for_u!(u128); impl_decodable_for_u!(u16); impl_decodable_for_u!(u32); impl_decodable_for_u!(u64); impl_decodable_for_u!(u128); impl Encodable for usize { fn rlp_append(&self, s: &mut RlpStream) { (*self as u64).rlp_append(s); } } impl Decodable for usize { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { u64::decode(rlp).map(|value| value as usize) } } macro_rules! impl_encodable_for_hash { ($name: ident) => { impl Encodable for $name { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self); } } }; } macro_rules! impl_decodable_for_hash { ($name: ident, $size: expr) => { impl Decodable for $name { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| match bytes.len().cmp(&$size) { cmp::Ordering::Less => Err(DecoderError::RlpIsTooShort { expected: $size, got: bytes.len(), }), cmp::Ordering::Greater => Err(DecoderError::RlpIsTooBig { expected: $size, got: bytes.len(), }), cmp::Ordering::Equal => { let mut t = [0u8; $size]; t.copy_from_slice(bytes); Ok($name(t)) } }) } } }; } impl_encodable_for_hash!(H128); impl_encodable_for_hash!(H160); impl_encodable_for_hash!(H256); impl_encodable_for_hash!(H384); impl_encodable_for_hash!(H512); impl_encodable_for_hash!(H520); impl_encodable_for_hash!(H768); impl_decodable_for_hash!(H128, 16); impl_decodable_for_hash!(H160, 20); impl_decodable_for_hash!(H256, 32); impl_decodable_for_hash!(H384, 48); impl_decodable_for_hash!(H512, 64); impl_decodable_for_hash!(H520, 65); impl_decodable_for_hash!(H768, 96); macro_rules! impl_encodable_for_uint { ($name: ident, $size: expr) => { impl Encodable for $name { fn rlp_append(&self, s: &mut RlpStream) { let leading_empty_bytes = $size - (self.bits() + 7) / 8; let mut buffer = [0u8; $size]; self.to_big_endian(&mut buffer); s.encoder().encode_value(&buffer[leading_empty_bytes..]); } } }; } macro_rules! impl_decodable_for_uint { ($name: ident, $size: expr) => { impl Decodable for $name { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| { if !bytes.is_empty() && bytes[0] == 0 { Err(DecoderError::RlpInvalidIndirection) } else if bytes.len() <= $size { Ok($name::from(bytes)) } else { Err(DecoderError::RlpIsTooBig { expected: $size, got: bytes.len(), }) } }) } } }; } impl_encodable_for_uint!(U256, 32); impl_decodable_for_uint!(U256, 32); impl<'a> Encodable for &'a str { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self.as_bytes()); } } impl Encodable for String { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self.as_bytes()); } } impl Decodable for String { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| { if bytes.contains(&b'\0') { return Err(DecoderError::RlpNullTerminatedString) } match str::from_utf8(bytes) { Ok(s) => Ok(s.to_owned()), Err(_err) => Err(DecoderError::RlpExpectedToBeData), } }) } } impl<T1: Encodable, T2: Encodable, T3: Encodable> Encodable for (T1, T2, T3) { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(3).append(&self.0).append(&self.1).append(&self.2); } } impl<T1: Decodable, T2: Decodable, T3: Decodable> Decodable for (T1, T2, T3) { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { let item_count = rlp.item_count()?; if item_count != 3 { return Err(DecoderError::RlpIncorrectListLen { expected: 3, got: item_count, }) } Ok((rlp.val_at(0)?, rlp.val_at(1)?, rlp.val_at(2)?)) } } #[macro_export] macro_rules! rlp_encode_and_decode_test { ($origin:expr) => { fn rlp_encode_and_decode_test<T>(origin: T) where T: $crate::Encodable + $crate::Decodable + ::std::fmt::Debug + PartialEq, { let encoded = $crate::encode(&origin); let decoded = $crate::decode::<T>(&encoded); assert_eq!(Ok(origin), decoded); } rlp_encode_and_decode_test($origin); }; } #[cfg(test)] mod tests { use super::*; #[test] fn vec_of_bytes() { let origin: Vec<Vec<u8>> = vec![vec![0, 1, 2, 3, 4], vec![5, 6, 7], vec![], vec![8, 9]]; let encoded = crate::encode(&origin); let expected = { let mut s = RlpStream::new(); s.begin_list(4); s.append::<Vec<u8>>(&origin[0]); s.append::<Vec<u8>>(&origin[1]); s.append::<Vec<u8>>(&origin[2]); s.append::<Vec<u8>>(&origin[3]); s.out() }; assert_eq!(expected, encoded.to_vec()); rlp_encode_and_decode_test!(origin); } #[test] fn rlp_zero_h160() { let h = H160::zero(); let encoded = h.rlp_bytes().to_vec(); assert_eq!(&[0x80 + 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], encoded.as_slice()); } #[test] fn vec_and_hash() { let vec: Vec<u8> = { let mut vec = Vec::with_capacity(32); for i in 0..32 { vec.push(i); } vec }; let hash: H256 = { let mut hash = H256::zero(); assert_eq!(32, hash.iter().len()); for (i, h) in hash.iter_mut().enumerate().take(32) { *h = i as u8; } hash }; assert_eq!(vec.rlp_bytes(), hash.rlp_bytes()); } #[test] fn slice_and_hash() { let array: [u8; 32] = { let mut array = [0 as u8; 32]; assert_eq!(32, array.iter().len()); for (i, a) in array.iter_mut().enumerate().take(32) { *a = i as u8; } array }; let slice: &[u8] = &array; let hash: H256 = { let mut hash = H256::zero(); assert_eq!(32, hash.iter().len()); for (i, h) in hash.iter_mut().enumerate().take(32) { *h = i as u8; } hash }; assert_eq!(slice.rlp_bytes(), hash.rlp_bytes()); } #[test] fn empty_bytes() { let empty_bytes: Vec<u8> = vec![]; assert_eq!(&[0x80], &empty_bytes.rlp_bytes().to_vec().as_slice()); rlp_encode_and_decode_test!(empty_bytes); } #[test] fn empty_slice_of_u8() { let empty_slice: &[u8] = &[]; assert_eq!(&[0x80], &empty_slice.rlp_bytes().to_vec().as_slice()); } #[test] fn empty_list() { let mut stream = RlpStream::new(); stream.begin_list(0); assert_eq!(vec![0xC0], stream.out()); } #[test] fn tuple() { let tuple: (u32, u32, u32) = (1, 2, 3); rlp_encode_and_decode_test!(tuple); } }
use super::stream::RlpStream; use super::traits::{Decodable, Encodable}; use super::{DecoderError, Rlp}; use primitives::{H128, H160, H256, H384, H512, H520, H768, U256}; use std::iter::{empty, once}; use std::{cmp, mem, str}; pub fn decode_usize(bytes: &[u8]) -> Result<usize, DecoderError> { let expected = mem::size_of::<usize>(); match bytes.len() { l if l <= expected => { if bytes[0] == 0 { return Err(DecoderError::RlpInvalidIndirection) } let mut res = 0usize; for (i, byte) in bytes.iter().enumerate() { let shift = (l - 1 - i) * 8; res += (*byte as usize) << shift; } Ok(res) } got => Err(DecoderError::RlpIsTooBig { expected, got, }), } } impl Encodable for bool { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_iter(once(if *self { 1u8 } else { 0 })); } } impl Decodable for bool { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| match bytes.len() { 0 => Ok(false), 1 => Ok(bytes[0] != 0), got => Err(DecoderError::RlpIsTooBig { expected: 1, got, }), }) } } impl<'a> Encodable for &'a [u8] { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self); } } impl Encodable for Vec<u8> { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self); } } impl Decodable for Vec<u8> { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| Ok(bytes.to_vec())) } } impl Encodable for Vec<Vec<u8>> { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(self.len()); for e in self { s.append(e); } } } impl Decodable for Vec<Vec<u8>> { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.as_list::<Vec<u8>>() } } impl<T> Encodable for Option<T> where T: Encodable, { fn rlp_append(&self, s: &mut RlpStream) { match *self { None => {
} impl<T> Decodable for Option<T> where T: Decodable, { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { let items = rlp.item_count()?; match items { 1 => rlp.val_at(0).map(Some), 0 => Ok(None), got => Err(DecoderError::RlpIncorrectListLen { expected: 1, got, }), } } } impl Encodable for u8 { fn rlp_append(&self, s: &mut RlpStream) { if *self != 0 { s.encoder().encode_iter(once(*self)); } else { s.encoder().encode_iter(empty()); } } } impl Decodable for u8 { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| match bytes.len() { 1 if bytes[0] != 0 => Ok(bytes[0]), 0 => Ok(0), 1 => Err(DecoderError::RlpInvalidIndirection), got => Err(DecoderError::RlpIsTooBig { expected: 1, got, }), }) } } macro_rules! impl_encodable_for_u { ($name: ident) => { impl Encodable for $name { fn rlp_append(&self, s: &mut RlpStream) { let leading_empty_bytes = self.leading_zeros() as usize / 8; let buffer = self.to_be_bytes(); s.encoder().encode_value(&buffer[leading_empty_bytes..]); } } }; } macro_rules! impl_decodable_for_u { ($name: ident) => { impl Decodable for $name { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| match bytes.len() { 0 | 1 => u8::decode(rlp).map($name::from), l if l <= mem::size_of::<$name>() => { if bytes[0] == 0 { return Err(DecoderError::RlpInvalidIndirection) } let mut res = 0 as $name; for (i, byte) in bytes.iter().enumerate() { let shift = (l - 1 - i) * 8; res += $name::from(*byte) << shift; } Ok(res) } got => Err(DecoderError::RlpIsTooBig { expected: mem::size_of::<$name>(), got, }), }) } } }; } impl_encodable_for_u!(u16); impl_encodable_for_u!(u32); impl_encodable_for_u!(u64); impl_encodable_for_u!(u128); impl_decodable_for_u!(u16); impl_decodable_for_u!(u32); impl_decodable_for_u!(u64); impl_decodable_for_u!(u128); impl Encodable for usize { fn rlp_append(&self, s: &mut RlpStream) { (*self as u64).rlp_append(s); } } impl Decodable for usize { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { u64::decode(rlp).map(|value| value as usize) } } macro_rules! impl_encodable_for_hash { ($name: ident) => { impl Encodable for $name { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self); } } }; } macro_rules! impl_decodable_for_hash { ($name: ident, $size: expr) => { impl Decodable for $name { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| match bytes.len().cmp(&$size) { cmp::Ordering::Less => Err(DecoderError::RlpIsTooShort { expected: $size, got: bytes.len(), }), cmp::Ordering::Greater => Err(DecoderError::RlpIsTooBig { expected: $size, got: bytes.len(), }), cmp::Ordering::Equal => { let mut t = [0u8; $size]; t.copy_from_slice(bytes); Ok($name(t)) } }) } } }; } impl_encodable_for_hash!(H128); impl_encodable_for_hash!(H160); impl_encodable_for_hash!(H256); impl_encodable_for_hash!(H384); impl_encodable_for_hash!(H512); impl_encodable_for_hash!(H520); impl_encodable_for_hash!(H768); impl_decodable_for_hash!(H128, 16); impl_decodable_for_hash!(H160, 20); impl_decodable_for_hash!(H256, 32); impl_decodable_for_hash!(H384, 48); impl_decodable_for_hash!(H512, 64); impl_decodable_for_hash!(H520, 65); impl_decodable_for_hash!(H768, 96); macro_rules! impl_encodable_for_uint { ($name: ident, $size: expr) => { impl Encodable for $name { fn rlp_append(&self, s: &mut RlpStream) { let leading_empty_bytes = $size - (self.bits() + 7) / 8; let mut buffer = [0u8; $size]; self.to_big_endian(&mut buffer); s.encoder().encode_value(&buffer[leading_empty_bytes..]); } } }; } macro_rules! impl_decodable_for_uint { ($name: ident, $size: expr) => { impl Decodable for $name { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| { if !bytes.is_empty() && bytes[0] == 0 { Err(DecoderError::RlpInvalidIndirection) } else if bytes.len() <= $size { Ok($name::from(bytes)) } else { Err(DecoderError::RlpIsTooBig { expected: $size, got: bytes.len(), }) } }) } } }; } impl_encodable_for_uint!(U256, 32); impl_decodable_for_uint!(U256, 32); impl<'a> Encodable for &'a str { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self.as_bytes()); } } impl Encodable for String { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self.as_bytes()); } } impl Decodable for String { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { rlp.decoder().decode_value(|bytes| { if bytes.contains(&b'\0') { return Err(DecoderError::RlpNullTerminatedString) } match str::from_utf8(bytes) { Ok(s) => Ok(s.to_owned()), Err(_err) => Err(DecoderError::RlpExpectedToBeData), } }) } } impl<T1: Encodable, T2: Encodable, T3: Encodable> Encodable for (T1, T2, T3) { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(3).append(&self.0).append(&self.1).append(&self.2); } } impl<T1: Decodable, T2: Decodable, T3: Decodable> Decodable for (T1, T2, T3) { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { let item_count = rlp.item_count()?; if item_count != 3 { return Err(DecoderError::RlpIncorrectListLen { expected: 3, got: item_count, }) } Ok((rlp.val_at(0)?, rlp.val_at(1)?, rlp.val_at(2)?)) } } #[macro_export] macro_rules! rlp_encode_and_decode_test { ($origin:expr) => { fn rlp_encode_and_decode_test<T>(origin: T) where T: $crate::Encodable + $crate::Decodable + ::std::fmt::Debug + PartialEq, { let encoded = $crate::encode(&origin); let decoded = $crate::decode::<T>(&encoded); assert_eq!(Ok(origin), decoded); } rlp_encode_and_decode_test($origin); }; } #[cfg(test)] mod tests { use super::*; #[test] fn vec_of_bytes() { let origin: Vec<Vec<u8>> = vec![vec![0, 1, 2, 3, 4], vec![5, 6, 7], vec![], vec![8, 9]]; let encoded = crate::encode(&origin); let expected = { let mut s = RlpStream::new(); s.begin_list(4); s.append::<Vec<u8>>(&origin[0]); s.append::<Vec<u8>>(&origin[1]); s.append::<Vec<u8>>(&origin[2]); s.append::<Vec<u8>>(&origin[3]); s.out() }; assert_eq!(expected, encoded.to_vec()); rlp_encode_and_decode_test!(origin); } #[test] fn rlp_zero_h160() { let h = H160::zero(); let encoded = h.rlp_bytes().to_vec(); assert_eq!(&[0x80 + 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], encoded.as_slice()); } #[test] fn vec_and_hash() { let vec: Vec<u8> = { let mut vec = Vec::with_capacity(32); for i in 0..32 { vec.push(i); } vec }; let hash: H256 = { let mut hash = H256::zero(); assert_eq!(32, hash.iter().len()); for (i, h) in hash.iter_mut().enumerate().take(32) { *h = i as u8; } hash }; assert_eq!(vec.rlp_bytes(), hash.rlp_bytes()); } #[test] fn slice_and_hash() { let array: [u8; 32] = { let mut array = [0 as u8; 32]; assert_eq!(32, array.iter().len()); for (i, a) in array.iter_mut().enumerate().take(32) { *a = i as u8; } array }; let slice: &[u8] = &array; let hash: H256 = { let mut hash = H256::zero(); assert_eq!(32, hash.iter().len()); for (i, h) in hash.iter_mut().enumerate().take(32) { *h = i as u8; } hash }; assert_eq!(slice.rlp_bytes(), hash.rlp_bytes()); } #[test] fn empty_bytes() { let empty_bytes: Vec<u8> = vec![]; assert_eq!(&[0x80], &empty_bytes.rlp_bytes().to_vec().as_slice()); rlp_encode_and_decode_test!(empty_bytes); } #[test] fn empty_slice_of_u8() { let empty_slice: &[u8] = &[]; assert_eq!(&[0x80], &empty_slice.rlp_bytes().to_vec().as_slice()); } #[test] fn empty_list() { let mut stream = RlpStream::new(); stream.begin_list(0); assert_eq!(vec![0xC0], stream.out()); } #[test] fn tuple() { let tuple: (u32, u32, u32) = (1, 2, 3); rlp_encode_and_decode_test!(tuple); } }
s.begin_list(0); } Some(ref value) => { s.begin_list(1); s.append(value); } } }
function_block-function_prefix_line
[ { "content": "/// Shortcut function to encode structure into rlp.\n\n///\n\n/// ```rust\n\n/// fn main () {\n\n/// \tlet animal = \"cat\";\n\n/// \tlet out = rlp::encode(&animal);\n\n/// \tassert_eq!(out, vec![0x83, b'c', b'a', b't']);\n\n/// }\n\n/// ```\n\npub fn encode<E>(object: &E) -> Vec<u8>\n\nwhere\n\n ...
Rust
src/main.rs
MeiK2333/river
1106b73423620bd70af37d9f41f683c0bcf4293c
#![recursion_limit = "512"] #[macro_use] extern crate log; use std::path::Path; use std::pin::Pin; use futures::StreamExt; use futures_core::Stream; use log4rs; use tempfile::tempdir_in; use tokio::fs::read_dir; use tonic::transport::Server; use tonic::{Request, Response, Status}; use river::judge_request::Data; use river::river_server::{River, RiverServer}; use river::{ Empty, JudgeRequest, JudgeResponse, JudgeResultEnum, LanguageConfigResponse, LanguageItem, LsCase, LsRequest, LsResponse, }; mod config; mod error; mod judger; mod result; mod sandbox; pub mod river { tonic::include_proto!("river"); } #[derive(Debug, Default)] pub struct RiverService {} #[tonic::async_trait] impl River for RiverService { type JudgeStream = Pin<Box<dyn Stream<Item = Result<JudgeResponse, Status>> + Send + Sync + 'static>>; async fn judge( &self, request: Request<tonic::Streaming<JudgeRequest>>, ) -> Result<Response<Self::JudgeStream>, Status> { let mut stream = request.into_inner(); let output = async_stream::try_stream! { let pwd = match tempdir_in(&config::CONFIG.judge_dir) { Ok(val) => val, Err(e) => { yield result::system_error(error::Error::IOError(e)); return; } }; debug!("{:?}", pwd); let path_str = pwd.path().to_str().unwrap(); info!("new request running on `{}`", path_str); let mut compile_success = false; let mut language = String::from(""); while let Some(req) = stream.next().await { yield result::pending(); yield result::running(); let req = req?; let result = match &req.data { Some(Data::CompileData(data)) => { language = String::from(&data.language); let res = judger::compile(&language, &data.code, &pwd.path()).await; if let Ok(ref val) = res { if let Some(river::judge_response::State::Result(rst)) = &val.state { if rst.result == JudgeResultEnum::CompileSuccess as i32 { compile_success = true; } } } res }, Some(Data::JudgeData(data)) => { if language == "" || !compile_success { Err(error::Error::CustomError(String::from("not compiled"))) } else { judger::judge( &language, &data.in_file, &data.out_file, &data.spj_file, data.time_limit, data.memory_limit, data.judge_type, &pwd.path() ).await } }, None => Err(error::Error::CustomError(String::from("unrecognized request types"))), }; let res = match result { Ok(res) => res, Err(e) => result::system_error(e) }; info!("path: {}, result: {:?}", path_str, res); yield res; }; info!("request end on `{}`", path_str); }; Ok(Response::new(Box::pin(output) as Self::JudgeStream)) } async fn language_config( &self, _request: Request<Empty>, ) -> Result<Response<LanguageConfigResponse>, Status> { let mut languages: Vec<LanguageItem> = vec![]; for (key, value) in &config::CONFIG.languages { languages.push(LanguageItem { language: String::from(key), compile: String::from(&value.compile_cmd), run: String::from(&value.run_cmd), version: String::from(&value.version), }); } let response = LanguageConfigResponse { languages }; Ok(Response::new(response)) } async fn ls(&self, request: Request<LsRequest>) -> Result<Response<LsResponse>, Status> { let pid = request.into_inner().pid; let mut response = LsResponse { cases: vec![] }; let mut directory_stream = match read_dir(Path::new(&config::CONFIG.data_dir).join(pid.to_string())).await { Ok(val) => val, Err(_) => return Ok(Response::new(response)), }; let mut files: Vec<String> = vec![]; while let Ok(Some(entry)) = directory_stream.next_entry().await { let file = entry.file_name().into_string().unwrap(); files.push(file); } let mut iter = 1; loop { let in_file = format!("data{}.in", iter); let out_file = format!("data{}.out", iter); if files.contains(&in_file) && files.contains(&out_file) { response.cases.push(LsCase { r#in: in_file, out: out_file, }); iter += 1; } else { break; } } Ok(Response::new(response)) } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { log4rs::init_file("log4rs.yaml", Default::default()).unwrap(); let addr = "0.0.0.0:4003".parse()?; let river = RiverService::default(); info!("listen on: {}", addr); Server::builder() .concurrency_limit_per_connection(5) .add_service(RiverServer::new(river)) .serve(addr) .await?; Ok(()) }
#![recursion_limit = "512"] #[macro_use] extern crate log; use std::path::Path; use std::pin::Pin; use futures::StreamExt; use futures_core::Stream; use log4rs; use tempfile::tempdir_in; use tokio::fs::read_dir; use tonic::transport::Server; use tonic::{Request, Response, Status}; use river::judge_request::Data; use river::river_server::{River, RiverServer}; use river::{ Empty, JudgeRequest, JudgeResponse, JudgeResultEnum, LanguageConfigResponse, LanguageItem, LsCase, LsRequest, LsResponse, }; mod config; mod error; mod judger; mod result; mod sandbox; pub mod river { tonic::include_proto!("river"); } #[derive(Debug, Default)] pub struct RiverService {} #[tonic::async_trait] impl River for RiverService { type JudgeStream = Pin<Box<dyn Stream<Item = Result<JudgeResponse, Status>> + Send + Sync + 'static>>; async fn judge( &self, request: Request<tonic::Streaming<JudgeRequest>>, ) -> Result<Response<Self::JudgeStream>, Status> { let mut stream = request.into_inner(); let output = async_stream::try_stream! { let pwd = match tempdir_in(&config::CONFIG.judge_dir) { Ok(val) => val, Err(e) => { yield result::system_error(error::Error::IOError(e)); return; } }; debug!("{:?}", pwd); let path_str = pwd.path().to_str().unwrap(); info!("new request running on `{}`", path_str); let mut compile_success = false; let mut language = String::from(""); while let Some(req) = stream.next().await { yield result::pending(); yield result::running(); let req = req?; let result = match &req.data { Some(Data::CompileData(data)) => { language = String::from(&data.language); let res = judger::compile(&language, &data.code, &pwd.path()).await; if let Ok(ref val) = res { if let Some(river::judge_response::State::Result(rst)) = &val.state { if rst.result == JudgeResultEnum::CompileSuccess as i32 { compile_success = true; } } } res }, Some(Data::JudgeData(data)) => { if language == "" || !compile_success { Err(error::Error::CustomError(String::from("not compiled"))) } else { judger::judge( &language, &data.in_file, &data.out_file, &data.spj_file, data.time_limit, data.memory_limit, data.judge_type, &pwd.path() ).await } }, None => Err(error::Error::CustomError(String::from("unrecognized request types"))), }; let res = match result { Ok(res) => res, Err(e) => result::system_error(e) }; info!("path: {}, result: {:?}", path_str, res); yield res; }; info!("request end on `{}`", path_str); }; Ok(Response::new(Box::pin(output) as Self::JudgeStream)) } async fn language_config( &self, _request: Request<Empty>, ) -> Result<Response<LanguageConfigResponse>, Status> { let mut languages: Vec<LanguageItem> = vec![]; for (key, value) in &config::CONFIG.languages { languages.push(LanguageItem { language: String::from(key), compile: String::from(&value.compile_cmd), run: String::from(&value.run_cmd), version: String::from(&value.version), }); } let response = LanguageConfigResponse { languages }; Ok(Response::new(response)) } async fn ls(&self, request: Request<LsRequest>) -> Result<Response<LsResponse>, Status> { let pid = request.into_inner().pid; let mut response = LsResponse { cases: vec![] }; let mut directory_stream = match read_dir(Path::new(&config::CONFIG.data_dir).join(pid.to_string())).await { Ok(val) => val, Err(_) => return Ok(Response::new(response)), }; let mut files: Vec<String> = vec![]; while let Ok(Some(entry)) = directory_stream.next_entry().await { let file = entry.file_name().into_string().unwrap(); files.push(file); } let mut iter = 1; loop { let in_file = format!("data{}.in", iter); let out_file = format!("data{}.out", iter); if files.contains(&in_file) && files.contains(&out_file) { response.cases.push(LsCase { r#in: in_file, out: out_file, }); iter += 1; } else { break; } } Ok(Response::new(response)) } } #[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> { log4rs::init_file("log4rs.yaml", Default::default()).unwrap(); let addr = "0.0.0.0:4003".parse()?; let river = RiverService::default(); info!("listen on: {}", addr); Server::builder() .concurrency_limit_per_connection(5) .add_service(RiverServer::new(river)) .serve(addr) .await?; Ok(()) }
function_block-full_function
[ { "content": "pub fn system_error(err: Error) -> JudgeResponse {\n\n warn!(\"{}\", err);\n\n JudgeResponse {\n\n state: Some(State::Result(JudgeResult {\n\n time_used: 0,\n\n memory_used: 0,\n\n result: JudgeResultEnum::SystemError as i32,\n\n errmsg: for...
Rust
src/sys/windows/mod.rs
jmagnuson/mio
40df934a11b05233a7796c4de19a4ee06bc4e03e
mod afd; mod io_status_block; pub mod event; pub use event::{Event, Events}; mod selector; pub use selector::{Selector, SelectorInner, SockState}; cfg_net! { macro_rules! syscall { ($fn: ident ( $($arg: expr),* $(,)* ), $err_test: path, $err_value: expr) => {{ let res = unsafe { $fn($($arg, )*) }; if $err_test(&res, &$err_value) { Err(io::Error::last_os_error()) } else { Ok(res) } }}; } } cfg_tcp! { pub(crate) mod tcp; } cfg_udp! { pub(crate) mod udp; } mod waker; pub(crate) use waker::Waker; cfg_net! { use std::io; use std::os::windows::io::RawSocket; use std::pin::Pin; use std::sync::{Arc, Mutex}; use crate::{poll, Interest, Registry, Token}; mod net; struct InternalState { selector: Arc<SelectorInner>, token: Token, interests: Interest, sock_state: Pin<Arc<Mutex<SockState>>>, } impl Drop for InternalState { fn drop(&mut self) { let mut sock_state = self.sock_state.lock().unwrap(); sock_state.mark_delete(); } } pub struct IoSourceState { inner: Option<Box<InternalState>>, } impl IoSourceState { pub fn new() -> IoSourceState { IoSourceState { inner: None } } pub fn do_io<T, F, R>(&self, f: F, io: &T) -> io::Result<R> where F: FnOnce(&T) -> io::Result<R>, { let result = f(io); if let Err(ref e) = result { if e.kind() == io::ErrorKind::WouldBlock { self.inner.as_ref().map_or(Ok(()), |state| { state .selector .reregister(state.sock_state.clone(), state.token, state.interests) })?; } } result } pub fn register( &mut self, registry: &Registry, token: Token, interests: Interest, socket: RawSocket, ) -> io::Result<()> { if self.inner.is_some() { Err(io::ErrorKind::AlreadyExists.into()) } else { poll::selector(registry) .register(socket, token, interests) .map(|state| { self.inner = Some(Box::new(state)); }) } } pub fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { match self.inner.as_mut() { Some(state) => { poll::selector(registry) .reregister(state.sock_state.clone(), token, interests) .map(|()| { state.token = token; state.interests = interests; }) } None => Err(io::ErrorKind::NotFound.into()), } } pub fn deregister(&mut self) -> io::Result<()> { match self.inner.as_mut() { Some(state) => { { let mut sock_state = state.sock_state.lock().unwrap(); sock_state.mark_delete(); } self.inner = None; Ok(()) } None => Err(io::ErrorKind::NotFound.into()), } } } }
mod afd; mod io_status_block; pub mod event; pub use event::{Event, Events}; mod selector; pub use selector::{Selector, SelectorInner, SockState}; cfg_net! { macro_rules! syscall { ($fn: ident ( $($arg: expr),* $(,)* ), $err_test: path, $err_value: expr) => {{ let res = unsafe { $fn($($arg, )*) }; if $err_test(&res, &$err_value) { Err(io::Error::last_os_error()) } else { Ok(res) } }}; } } cfg_tcp! { pub(crate) mod tcp; } cfg_udp! { pub(crate) mod udp; } mod waker; pub(crate) use waker::Waker; cfg_net! { use std::io; use std::os::windows::io::RawSocket; use std::pin::Pin; use std::sync::{Arc, Mutex}; use crate::{poll, Interest, Registry, Token}; mod net; struct InternalState { selector: Arc<SelectorInner>, token: Token, interests: Interest, sock_state: Pin<Arc<Mutex<SockState>>>, } impl Drop for InternalState { fn drop(&mut self) { let mut sock_state = self.sock_state.lock().unwrap(); sock_state.mark_delete(); } } pub struct IoSourceState { inner: Option<Box<InternalState>>, } impl IoSourceState { pub fn new
f e.kind() == io::ErrorKind::WouldBlock { self.inner.as_ref().map_or(Ok(()), |state| { state .selector .reregister(state.sock_state.clone(), state.token, state.interests) })?; } } result } pub fn register( &mut self, registry: &Registry, token: Token, interests: Interest, socket: RawSocket, ) -> io::Result<()> { if self.inner.is_some() { Err(io::ErrorKind::AlreadyExists.into()) } else { poll::selector(registry) .register(socket, token, interests) .map(|state| { self.inner = Some(Box::new(state)); }) } } pub fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { match self.inner.as_mut() { Some(state) => { poll::selector(registry) .reregister(state.sock_state.clone(), token, interests) .map(|()| { state.token = token; state.interests = interests; }) } None => Err(io::ErrorKind::NotFound.into()), } } pub fn deregister(&mut self) -> io::Result<()> { match self.inner.as_mut() { Some(state) => { { let mut sock_state = state.sock_state.lock().unwrap(); sock_state.mark_delete(); } self.inner = None; Ok(()) } None => Err(io::ErrorKind::NotFound.into()), } } } }
() -> IoSourceState { IoSourceState { inner: None } } pub fn do_io<T, F, R>(&self, f: F, io: &T) -> io::Result<R> where F: FnOnce(&T) -> io::Result<R>, { let result = f(io); if let Err(ref e) = result { i
random
[ { "content": "fn expect_waker_event(poll: &mut Poll, events: &mut Events, token: Token) {\n\n poll.poll(events, Some(Duration::from_millis(100))).unwrap();\n\n assert!(!events.is_empty());\n\n for event in events.iter() {\n\n assert_eq!(event.token(), token);\n\n assert!(event.is_readable...
Rust
sway-core/src/parse_tree/declaration/reassignment.rs
mitchmindtree/sway
38479274e0c50518e20c919682b8173ae4a555d3
use crate::build_config::BuildConfig; use crate::error::{err, ok, CompileError, CompileResult}; use crate::parse_tree::Expression; use crate::parser::Rule; use crate::span::Span; use crate::{parse_array_index, Ident}; use pest::iterators::Pair; #[derive(Debug, Clone)] pub struct Reassignment { pub lhs: Box<Expression>, pub rhs: Expression, pub(crate) span: Span, } impl Reassignment { pub(crate) fn parse_from_pair( pair: Pair<Rule>, config: Option<&BuildConfig>, ) -> CompileResult<Reassignment> { let path = config.map(|c| c.path()); let span = Span { span: pair.as_span(), path: path.clone(), }; let mut warnings = vec![]; let mut errors = vec![]; let mut iter = pair.into_inner(); let variable_or_struct_reassignment = iter.next().expect("guaranteed by grammar"); match variable_or_struct_reassignment.as_rule() { Rule::variable_reassignment => { let mut iter = variable_or_struct_reassignment.into_inner(); let name = check!( Expression::parse_from_pair_inner(iter.next().unwrap(), config), return err(warnings, errors), warnings, errors ); let body = iter.next().unwrap(); let body = check!( Expression::parse_from_pair(body.clone(), config), Expression::Tuple { fields: vec![], span: Span { span: body.as_span(), path } }, warnings, errors ); ok( Reassignment { lhs: Box::new(name), rhs: body, span, }, warnings, errors, ) } Rule::struct_field_reassignment => { let mut iter = variable_or_struct_reassignment.into_inner(); let lhs = iter.next().expect("guaranteed by grammar"); let rhs = iter.next().expect("guaranteed by grammar"); let rhs_span = Span { span: rhs.as_span(), path: path.clone(), }; let body = check!( Expression::parse_from_pair(rhs, config), Expression::Tuple { fields: vec![], span: rhs_span }, warnings, errors ); let inner = lhs.into_inner().next().expect("guaranteed by grammar"); assert_eq!(inner.as_rule(), Rule::subfield_path); let mut name_parts = inner.into_inner(); let mut expr = check!( parse_subfield_path_ensure_only_var( name_parts.next().expect("guaranteed by grammar"), config ), return err(warnings, errors), warnings, errors ); for name_part in name_parts { expr = Expression::SubfieldExpression { prefix: Box::new(expr.clone()), span: Span { span: name_part.as_span(), path: path.clone(), }, field_to_access: check!( Ident::parse_from_pair(name_part, config), continue, warnings, errors ), } } ok( Reassignment { lhs: Box::new(expr), rhs: body, span, }, warnings, errors, ) } _ => unreachable!("guaranteed by grammar"), } } } fn parse_subfield_path_ensure_only_var( item: Pair<Rule>, config: Option<&BuildConfig>, ) -> CompileResult<Expression> { let warnings = vec![]; let mut errors = vec![]; let path = config.map(|c| c.path()); let item = item.into_inner().next().expect("guarenteed by grammar"); match item.as_rule() { Rule::call_item => parse_call_item_ensure_only_var(item, config), Rule::array_index => parse_array_index(item, config), a => { eprintln!( "Unimplemented subfield path: {:?} ({:?}) ({:?})", a, item.as_str(), item.as_rule() ); errors.push(CompileError::UnimplementedRule( a, Span { span: item.as_span(), path: path.clone(), }, )); let exp = Expression::Tuple { fields: vec![], span: Span { span: item.as_span(), path, }, }; ok(exp, warnings, errors) } } } fn parse_call_item_ensure_only_var( item: Pair<Rule>, config: Option<&BuildConfig>, ) -> CompileResult<Expression> { let path = config.map(|c| c.path()); let mut warnings = vec![]; let mut errors = vec![]; assert_eq!(item.as_rule(), Rule::call_item); let item = item.into_inner().next().expect("guaranteed by grammar"); let exp = match item.as_rule() { Rule::ident => Expression::VariableExpression { name: check!( Ident::parse_from_pair(item.clone(), config), return err(warnings, errors), warnings, errors ), span: Span { span: item.as_span(), path, }, }, Rule::expr => { errors.push(CompileError::InvalidExpressionOnLhs { span: Span { span: item.as_span(), path, }, }); return err(warnings, errors); } a => unreachable!("{:?}", a), }; ok(exp, warnings, errors) }
use crate::build_config::BuildConfig; use crate::error::{err, ok, CompileError, CompileResult}; use crate::parse_tree::Expression; use crate::parser::Rule; use crate::span::Span; use crate::{parse_array_index, Ident}; use pest::iterators::Pair; #[derive(Debug, Clone)] pub struct Reassignment { pub lhs: Box<Expression>, pub rhs: Expression, pub(crate) span: Span, } impl Reassignment { pub(crate) fn parse_from_pair( pair: Pair<Rule>, config: Option<&BuildConfig>, ) -> CompileResult<Reassignment> { let path = config.map(|c| c.path()); let span = Span { span: pair.as_span(), path: path.clone(), }; let mut warnings = vec![]; let mut errors = vec![]; let mut iter = pair.into_inner(); let variable_or_struct_reassignment = iter.next().expect("guaranteed by grammar"); match variable_or_struct_reassignment.as_rule() { Rule::variable_reassignment => { let mut iter = variable_or_struct_reassignment.into_inner();
let body = iter.next().unwrap(); let body = check!( Expression::parse_from_pair(body.clone(), config), Expression::Tuple { fields: vec![], span: Span { span: body.as_span(), path } }, warnings, errors ); ok( Reassignment { lhs: Box::new(name), rhs: body, span, }, warnings, errors, ) } Rule::struct_field_reassignment => { let mut iter = variable_or_struct_reassignment.into_inner(); let lhs = iter.next().expect("guaranteed by grammar"); let rhs = iter.next().expect("guaranteed by grammar"); let rhs_span = Span { span: rhs.as_span(), path: path.clone(), }; let body = check!( Expression::parse_from_pair(rhs, config), Expression::Tuple { fields: vec![], span: rhs_span }, warnings, errors ); let inner = lhs.into_inner().next().expect("guaranteed by grammar"); assert_eq!(inner.as_rule(), Rule::subfield_path); let mut name_parts = inner.into_inner(); let mut expr = check!( parse_subfield_path_ensure_only_var( name_parts.next().expect("guaranteed by grammar"), config ), return err(warnings, errors), warnings, errors ); for name_part in name_parts { expr = Expression::SubfieldExpression { prefix: Box::new(expr.clone()), span: Span { span: name_part.as_span(), path: path.clone(), }, field_to_access: check!( Ident::parse_from_pair(name_part, config), continue, warnings, errors ), } } ok( Reassignment { lhs: Box::new(expr), rhs: body, span, }, warnings, errors, ) } _ => unreachable!("guaranteed by grammar"), } } } fn parse_subfield_path_ensure_only_var( item: Pair<Rule>, config: Option<&BuildConfig>, ) -> CompileResult<Expression> { let warnings = vec![]; let mut errors = vec![]; let path = config.map(|c| c.path()); let item = item.into_inner().next().expect("guarenteed by grammar"); match item.as_rule() { Rule::call_item => parse_call_item_ensure_only_var(item, config), Rule::array_index => parse_array_index(item, config), a => { eprintln!( "Unimplemented subfield path: {:?} ({:?}) ({:?})", a, item.as_str(), item.as_rule() ); errors.push(CompileError::UnimplementedRule( a, Span { span: item.as_span(), path: path.clone(), }, )); let exp = Expression::Tuple { fields: vec![], span: Span { span: item.as_span(), path, }, }; ok(exp, warnings, errors) } } } fn parse_call_item_ensure_only_var( item: Pair<Rule>, config: Option<&BuildConfig>, ) -> CompileResult<Expression> { let path = config.map(|c| c.path()); let mut warnings = vec![]; let mut errors = vec![]; assert_eq!(item.as_rule(), Rule::call_item); let item = item.into_inner().next().expect("guaranteed by grammar"); let exp = match item.as_rule() { Rule::ident => Expression::VariableExpression { name: check!( Ident::parse_from_pair(item.clone(), config), return err(warnings, errors), warnings, errors ), span: Span { span: item.as_span(), path, }, }, Rule::expr => { errors.push(CompileError::InvalidExpressionOnLhs { span: Span { span: item.as_span(), path, }, }); return err(warnings, errors); } a => unreachable!("{:?}", a), }; ok(exp, warnings, errors) }
let name = check!( Expression::parse_from_pair_inner(iter.next().unwrap(), config), return err(warnings, errors), warnings, errors );
assignment_statement
[ { "content": "fn disallow_opcode(op: &Ident) -> Vec<CompileError> {\n\n let mut errors = vec![];\n\n\n\n match op.as_str().to_lowercase().as_str() {\n\n \"jnei\" => {\n\n errors.push(CompileError::DisallowedJnei {\n\n span: op.span().clone(),\n\n });\n\n ...
Rust
src/interchange/src/avro/encode.rs
jiangyuzhao/materialize
2f8bf7a64197cff27e43132f251d5908f2f9e520
use std::fmt; use byteorder::{NetworkEndian, WriteBytesExt}; use chrono::Timelike; use itertools::Itertools; use lazy_static::lazy_static; use mz_avro::types::AvroMap; use repr::adt::jsonb::JsonbRef; use repr::adt::numeric::{self, NUMERIC_AGG_MAX_PRECISION, NUMERIC_DATUM_MAX_PRECISION}; use repr::{ColumnName, ColumnType, Datum, RelationDesc, Row, ScalarType}; use serde_json::json; use crate::encode::{column_names_and_types, Encode, TypedDatum}; use crate::json::build_row_schema_json; use mz_avro::types::{DecimalValue, Value}; use mz_avro::Schema; lazy_static! { static ref DEBEZIUM_TRANSACTION_SCHEMA: Schema = Schema::parse(&json!({ "type": "record", "name": "envelope", "fields": [ { "name": "id", "type": "string" }, { "name": "status", "type": "string" }, { "name": "event_count", "type": [ "null", "long" ] }, { "name": "data_collections", "type": [ "null", { "type": "array", "items": { "type": "record", "name": "data_collection", "fields": [ { "name": "data_collection", "type": "string" }, { "name": "event_count", "type": "long" }, ] } } ], "default": null, }, ] })).expect("valid schema constructed"); } fn build_schema(columns: &[(ColumnName, ColumnType)]) -> Schema { let row_schema = build_row_schema_json(&columns, "envelope"); Schema::parse(&row_schema).expect("valid schema constructed") } fn encode_avro_header(buf: &mut Vec<u8>, schema_id: i32) { buf.write_u8(0).expect("writing to vec cannot fail"); buf.write_i32::<NetworkEndian>(schema_id) .expect("writing to vec cannot fail"); } struct KeyInfo { columns: Vec<(ColumnName, ColumnType)>, schema: Schema, } fn encode_message_unchecked( schema_id: i32, row: Row, schema: &Schema, columns: &[(ColumnName, ColumnType)], ) -> Vec<u8> { let mut buf = vec![]; encode_avro_header(&mut buf, schema_id); let value = encode_datums_as_avro(row.iter(), columns); mz_avro::encode_unchecked(&value, schema, &mut buf); buf } pub struct AvroSchemaGenerator { value_columns: Vec<(ColumnName, ColumnType)>, key_info: Option<KeyInfo>, writer_schema: Schema, } impl AvroSchemaGenerator { pub fn new( key_desc: Option<RelationDesc>, value_desc: RelationDesc, include_transaction: bool, ) -> Self { let mut value_columns = column_names_and_types(value_desc); if include_transaction { value_columns.push(( "transaction".into(), ColumnType { nullable: false, scalar_type: ScalarType::Record { fields: vec![( "id".into(), ColumnType { scalar_type: ScalarType::String, nullable: false, }, )], custom_oid: None, custom_name: Some("transaction".to_string()), }, }, )); } let writer_schema = build_schema(&value_columns); let key_info = key_desc.map(|key_desc| { let columns = column_names_and_types(key_desc); let row_schema = build_row_schema_json(&columns, "row"); KeyInfo { schema: Schema::parse(&row_schema).expect("valid schema constructed"), columns, } }); AvroSchemaGenerator { value_columns, key_info, writer_schema, } } pub fn value_writer_schema(&self) -> &Schema { &self.writer_schema } pub fn value_columns(&self) -> &[(ColumnName, ColumnType)] { &self.value_columns } pub fn key_writer_schema(&self) -> Option<&Schema> { self.key_info.as_ref().map(|KeyInfo { schema, .. }| schema) } pub fn key_columns(&self) -> Option<&[(ColumnName, ColumnType)]> { self.key_info .as_ref() .map(|KeyInfo { columns, .. }| columns.as_slice()) } } impl fmt::Debug for AvroSchemaGenerator { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SchemaGenerator") .field("writer_schema", &self.writer_schema) .finish() } } pub struct AvroEncoder { schema_generator: AvroSchemaGenerator, key_schema_id: Option<i32>, value_schema_id: i32, } impl fmt::Debug for AvroEncoder { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("AvroEncoder") .field("writer_schema", &self.schema_generator.writer_schema) .finish() } } impl AvroEncoder { pub fn new( schema_generator: AvroSchemaGenerator, key_schema_id: Option<i32>, value_schema_id: i32, ) -> Self { AvroEncoder { schema_generator, key_schema_id, value_schema_id, } } pub fn encode_key_unchecked(&self, schema_id: i32, row: Row) -> Vec<u8> { let schema = self.schema_generator.key_writer_schema().unwrap(); let columns = self.schema_generator.key_columns().unwrap(); encode_message_unchecked(schema_id, row, schema, columns) } pub fn encode_value_unchecked(&self, schema_id: i32, row: Row) -> Vec<u8> { let schema = self.schema_generator.value_writer_schema(); let columns = self.schema_generator.value_columns(); encode_message_unchecked(schema_id, row, schema, columns) } } impl Encode for AvroEncoder { fn get_format_name(&self) -> &str { "avro" } fn encode_key_unchecked(&self, row: Row) -> Vec<u8> { self.encode_key_unchecked(self.key_schema_id.unwrap(), row) } fn encode_value_unchecked(&self, row: Row) -> Vec<u8> { self.encode_value_unchecked(self.value_schema_id, row) } } pub fn encode_datums_as_avro<'a, I>(datums: I, names_types: &[(ColumnName, ColumnType)]) -> Value where I: IntoIterator<Item = Datum<'a>>, { let value_fields: Vec<(String, Value)> = names_types .iter() .zip_eq(datums) .map(|((name, typ), datum)| { let name = name.as_str().to_owned(); use mz_avro::types::ToAvro; (name, TypedDatum::new(datum, typ.clone()).avro()) }) .collect(); let v = Value::Record(value_fields); v } impl<'a> mz_avro::types::ToAvro for TypedDatum<'a> { fn avro(self) -> Value { let TypedDatum { datum, typ } = self; if typ.nullable && datum.is_null() { Value::Union { index: 0, inner: Box::new(Value::Null), n_variants: 2, null_variant: Some(0), } } else { let mut val = match &typ.scalar_type { ScalarType::Bool => Value::Boolean(datum.unwrap_bool()), ScalarType::Int16 => Value::Int(i32::from(datum.unwrap_int16())), ScalarType::Int32 | ScalarType::Oid => Value::Int(datum.unwrap_int32()), ScalarType::Int64 => Value::Long(datum.unwrap_int64()), ScalarType::Float32 => Value::Float(datum.unwrap_float32()), ScalarType::Float64 => Value::Double(datum.unwrap_float64()), ScalarType::Numeric { scale } => { let mut d = datum.unwrap_numeric().0; let (unscaled, precision, scale) = match scale { Some(scale) => { numeric::rescale(&mut d, *scale).unwrap(); ( numeric::numeric_to_twos_complement_be(d).to_vec(), NUMERIC_DATUM_MAX_PRECISION, usize::from(*scale), ) } None => ( numeric::numeric_to_twos_complement_wide(d).to_vec(), NUMERIC_AGG_MAX_PRECISION, NUMERIC_DATUM_MAX_PRECISION, ), }; Value::Decimal(DecimalValue { unscaled, precision, scale, }) } ScalarType::Date => Value::Date(datum.unwrap_date()), ScalarType::Time => Value::Long({ let time = datum.unwrap_time(); (time.num_seconds_from_midnight() * 1_000_000) as i64 + (time.nanosecond() as i64) / 1_000 }), ScalarType::Timestamp => Value::Timestamp(datum.unwrap_timestamp()), ScalarType::TimestampTz => Value::Timestamp(datum.unwrap_timestamptz().naive_utc()), ScalarType::Interval => Value::Fixed(20, { let iv = datum.unwrap_interval(); let mut buf = Vec::with_capacity(24); buf.extend(&iv.months.to_le_bytes()); buf.extend(&iv.duration.to_le_bytes()); debug_assert_eq!(buf.len(), 20); buf }), ScalarType::Bytes => Value::Bytes(Vec::from(datum.unwrap_bytes())), ScalarType::String => Value::String(datum.unwrap_str().to_owned()), ScalarType::Jsonb => Value::Json(JsonbRef::from_datum(datum).to_serde_json()), ScalarType::Uuid => Value::Uuid(datum.unwrap_uuid()), ScalarType::Array(element_type) | ScalarType::List { element_type, .. } => { let list = match typ.scalar_type { ScalarType::Array(_) => datum.unwrap_array().elements(), ScalarType::List { .. } => datum.unwrap_list(), _ => unreachable!(), }; let values = list .into_iter() .map(|datum| { let datum = TypedDatum::new( datum, ColumnType { nullable: true, scalar_type: (**element_type).clone(), }, ); datum.avro() }) .collect(); Value::Array(values) } ScalarType::Map { value_type, .. } => { let map = datum.unwrap_map(); let elements = map .into_iter() .map(|(key, datum)| { let datum = TypedDatum::new( datum, ColumnType { nullable: true, scalar_type: (**value_type).clone(), }, ); let value = datum.avro(); (key.to_string(), value) }) .collect(); Value::Map(AvroMap(elements)) } ScalarType::Record { fields, .. } => { let list = datum.unwrap_list(); let fields = fields .iter() .zip(list.into_iter()) .map(|((name, typ), datum)| { let name = name.to_string(); let datum = TypedDatum::new(datum, typ.clone()); let value = datum.avro(); (name, value) }) .collect(); Value::Record(fields) } }; if typ.nullable { val = Value::Union { index: 1, inner: Box::new(val), n_variants: 2, null_variant: Some(0), }; } val } } } pub fn get_debezium_transaction_schema() -> &'static Schema { &DEBEZIUM_TRANSACTION_SCHEMA } pub fn encode_debezium_transaction_unchecked( schema_id: i32, collection: &str, id: &str, status: &str, message_count: Option<i64>, ) -> Vec<u8> { let mut buf = Vec::new(); encode_avro_header(&mut buf, schema_id); let transaction_id = Value::String(id.to_owned()); let status = Value::String(status.to_owned()); let event_count = match message_count { None => Value::Union { index: 0, inner: Box::new(Value::Null), n_variants: 2, null_variant: Some(0), }, Some(count) => Value::Union { index: 1, inner: Box::new(Value::Long(count)), n_variants: 2, null_variant: Some(0), }, }; let data_collections = if let Some(message_count) = message_count { let collection = Value::Record(vec![ ("data_collection".into(), Value::String(collection.into())), ("event_count".into(), Value::Long(message_count)), ]); Value::Union { index: 1, inner: Box::new(Value::Array(vec![collection])), n_variants: 2, null_variant: Some(0), } } else { Value::Union { index: 0, inner: Box::new(Value::Null), n_variants: 2, null_variant: Some(0), } }; let record_contents = vec![ ("id".into(), transaction_id), ("status".into(), status), ("event_count".into(), event_count), ("data_collections".into(), data_collections), ]; let avro = Value::Record(record_contents); debug_assert!(avro.validate(DEBEZIUM_TRANSACTION_SCHEMA.top_node())); mz_avro::encode_unchecked(&avro, &DEBEZIUM_TRANSACTION_SCHEMA, &mut buf); buf }
use std::fmt; use byteorder::{NetworkEndian, WriteBytesExt}; use chrono::Timelike; use itertools::Itertools; use lazy_static::lazy_static; use mz_avro::types::AvroMap; use repr::adt::jsonb::JsonbRef; use repr::adt::numeric::{self, NUMERIC_AGG_MAX_PRECISION, NUMERIC_DATUM_MAX_PRECISION}; use repr::{ColumnName, ColumnType, Datum, RelationDesc, Row, ScalarType}; use serde_json::json; use crate::encode::{column_names_and_types, Encode, TypedDatum}; use crate::json::build_row_schema_json; use mz_avro::types::{DecimalValue, Value}; use mz_avro::Schema; lazy_static! { static ref DEBEZIUM_TRANSACTION_SCHEMA: Schema = Schema::parse(&json!({ "type": "record", "name": "envelope", "fields": [ { "name": "id", "type": "string" }, { "name": "status", "type": "string" }, { "name": "event_count", "type": [ "null", "long" ] }, { "name": "data_collections", "type": [ "null", { "type": "array", "items": { "type": "record", "name": "data_collection", "fields": [ { "name": "data_collection", "type": "string" }, { "name": "event_count", "type": "long" }, ] } } ], "default": null, }, ] })).expect("valid schema constructed"); } fn build_schema(columns: &[(ColumnName, ColumnType)]) -> Schema { let row_schema = build_row_schema_json(&columns, "envelope"); Schema::parse(&row_schema).expect("valid schema constructed") } fn encode_avro_header(buf: &mut Vec<u8>, schema_id: i32) { buf.write_u8(0).expect("writing to vec cannot fail"); buf.write_i32::<NetworkEndian>(schema_id) .expect("writing to vec cannot fail"); } struct KeyInfo { columns: Vec<(ColumnName, ColumnType)>, schema: Schema, } fn encode_message_unchecked( schema_id: i32, row: Row, schema: &Schema, columns: &[(ColumnName, ColumnType)], ) -> Vec<u8> { let mut buf = vec![]; encode_avro_header(&mut buf, schema_id); let value = encode_datums_as_avro(row.iter(), columns); mz_avro::encode_unchecked(&value, schema, &mut buf); buf } pub struct AvroSchemaGenerator { value_columns: Vec<(ColumnName, ColumnType)>, key_info: Option<KeyInfo>, writer_schema: Schema, } impl AvroSchemaGenerator { pub fn new( key_desc: Option<RelationDesc>, value_desc: RelationDesc, include_transaction: bool, ) -> Self { let mut value_columns = column_names_and_types(value_desc); if include_transaction { value_columns.push(( "transaction".into(), ColumnType { nullable: false, scalar_type: ScalarType::Record { fields: vec![( "id".into(), ColumnType { scalar_type: ScalarType::String, nullable: false, }, )], custom_oid: None, custom_name: Some("transaction".to_string()), }, }, )); } let writer_schema = build_schema(&value_columns); let key_info = key_desc.map(|key_desc| { let columns = column_names_and_types(key_desc); let row_schema = build_row_schema_json(&columns, "row"); KeyInfo { schema: Schema::parse(&row_schema).expect("valid schema constructed"), columns, } }); AvroSchemaGenerator { value_columns, key_info, writer_schema, } } pub fn value_writer_schema(&self) -> &Schema { &self.writer_schema } pub fn value_columns(&self) -> &[(ColumnName, ColumnType)] { &self.value_columns } pub fn key_writer_schema(&self) -> Option<&Schema> { self.key_info.as_ref().map(|KeyInfo { schema, .. }| schema) } pub fn key_columns(&self) -> Option<&[(ColumnName, ColumnType)]> { self.key_info .as_ref() .map(|KeyInfo { columns, .. }| columns.as_slice()) } } impl fmt::Debug for AvroSchemaGenerator { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SchemaGenerator") .field("writer_schema", &self.writer_schema) .finish() } } pub struct AvroEncoder { schema_generator: AvroSchemaGenerator, key_schema_id: Option<i32>, value_schema_id: i32, } impl fmt::Debug for AvroEncoder { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("AvroEncoder") .field("writer_schema", &self.schema_generator.writer_schema) .finish() } } impl AvroEncoder { pub fn new( schema_generator: AvroSchemaGenerator, key_schema_id: Option<i32>, value_schema_id: i32, ) -> Self { AvroEncoder { schema_generator, key_schema_id, value_schema_id, } } pub fn encode_key_unchecked(&self, schema_id: i32, row: Row) -> Vec<u8> { let schema = self.schema_generator.key_writer_schema().unwrap(); let columns = self.schema_generator.key_columns().unwrap(); encode_message_unchecked(schema_id, row, schema, columns) } pub fn encode_value_unchecked(&self, schema_id: i32, row: Row) -> Vec<u8> { let schema = self.schema_generator.value_writer_schema(); let columns = self.schema_generator.value_columns(); encode_message_unchecked(schema_id, row, schema, columns) } } impl Encode for AvroEncoder { fn get_format_name(&self) -> &str { "avro" } fn encode_key_unchecked(&self, row: Row) -> Vec<u8> { self.encode_key_unchecked(self.key_schema_id.unwrap(), row) } fn encode_value_unchecked(&self, row: Row) -> Vec<u8> { self.encode_value_unchecked(self.value_schema_id, row) } } pub fn encode_datums_as_avro<'a, I>(datums: I, names_types: &[(ColumnName, ColumnType)]) -> Value where
impl<'a> mz_avro::types::ToAvro for TypedDatum<'a> { fn avro(self) -> Value { let TypedDatum { datum, typ } = self; if typ.nullable && datum.is_null() { Value::Union { index: 0, inner: Box::new(Value::Null), n_variants: 2, null_variant: Some(0), } } else { let mut val = match &typ.scalar_type { ScalarType::Bool => Value::Boolean(datum.unwrap_bool()), ScalarType::Int16 => Value::Int(i32::from(datum.unwrap_int16())), ScalarType::Int32 | ScalarType::Oid => Value::Int(datum.unwrap_int32()), ScalarType::Int64 => Value::Long(datum.unwrap_int64()), ScalarType::Float32 => Value::Float(datum.unwrap_float32()), ScalarType::Float64 => Value::Double(datum.unwrap_float64()), ScalarType::Numeric { scale } => { let mut d = datum.unwrap_numeric().0; let (unscaled, precision, scale) = match scale { Some(scale) => { numeric::rescale(&mut d, *scale).unwrap(); ( numeric::numeric_to_twos_complement_be(d).to_vec(), NUMERIC_DATUM_MAX_PRECISION, usize::from(*scale), ) } None => ( numeric::numeric_to_twos_complement_wide(d).to_vec(), NUMERIC_AGG_MAX_PRECISION, NUMERIC_DATUM_MAX_PRECISION, ), }; Value::Decimal(DecimalValue { unscaled, precision, scale, }) } ScalarType::Date => Value::Date(datum.unwrap_date()), ScalarType::Time => Value::Long({ let time = datum.unwrap_time(); (time.num_seconds_from_midnight() * 1_000_000) as i64 + (time.nanosecond() as i64) / 1_000 }), ScalarType::Timestamp => Value::Timestamp(datum.unwrap_timestamp()), ScalarType::TimestampTz => Value::Timestamp(datum.unwrap_timestamptz().naive_utc()), ScalarType::Interval => Value::Fixed(20, { let iv = datum.unwrap_interval(); let mut buf = Vec::with_capacity(24); buf.extend(&iv.months.to_le_bytes()); buf.extend(&iv.duration.to_le_bytes()); debug_assert_eq!(buf.len(), 20); buf }), ScalarType::Bytes => Value::Bytes(Vec::from(datum.unwrap_bytes())), ScalarType::String => Value::String(datum.unwrap_str().to_owned()), ScalarType::Jsonb => Value::Json(JsonbRef::from_datum(datum).to_serde_json()), ScalarType::Uuid => Value::Uuid(datum.unwrap_uuid()), ScalarType::Array(element_type) | ScalarType::List { element_type, .. } => { let list = match typ.scalar_type { ScalarType::Array(_) => datum.unwrap_array().elements(), ScalarType::List { .. } => datum.unwrap_list(), _ => unreachable!(), }; let values = list .into_iter() .map(|datum| { let datum = TypedDatum::new( datum, ColumnType { nullable: true, scalar_type: (**element_type).clone(), }, ); datum.avro() }) .collect(); Value::Array(values) } ScalarType::Map { value_type, .. } => { let map = datum.unwrap_map(); let elements = map .into_iter() .map(|(key, datum)| { let datum = TypedDatum::new( datum, ColumnType { nullable: true, scalar_type: (**value_type).clone(), }, ); let value = datum.avro(); (key.to_string(), value) }) .collect(); Value::Map(AvroMap(elements)) } ScalarType::Record { fields, .. } => { let list = datum.unwrap_list(); let fields = fields .iter() .zip(list.into_iter()) .map(|((name, typ), datum)| { let name = name.to_string(); let datum = TypedDatum::new(datum, typ.clone()); let value = datum.avro(); (name, value) }) .collect(); Value::Record(fields) } }; if typ.nullable { val = Value::Union { index: 1, inner: Box::new(val), n_variants: 2, null_variant: Some(0), }; } val } } } pub fn get_debezium_transaction_schema() -> &'static Schema { &DEBEZIUM_TRANSACTION_SCHEMA } pub fn encode_debezium_transaction_unchecked( schema_id: i32, collection: &str, id: &str, status: &str, message_count: Option<i64>, ) -> Vec<u8> { let mut buf = Vec::new(); encode_avro_header(&mut buf, schema_id); let transaction_id = Value::String(id.to_owned()); let status = Value::String(status.to_owned()); let event_count = match message_count { None => Value::Union { index: 0, inner: Box::new(Value::Null), n_variants: 2, null_variant: Some(0), }, Some(count) => Value::Union { index: 1, inner: Box::new(Value::Long(count)), n_variants: 2, null_variant: Some(0), }, }; let data_collections = if let Some(message_count) = message_count { let collection = Value::Record(vec![ ("data_collection".into(), Value::String(collection.into())), ("event_count".into(), Value::Long(message_count)), ]); Value::Union { index: 1, inner: Box::new(Value::Array(vec![collection])), n_variants: 2, null_variant: Some(0), } } else { Value::Union { index: 0, inner: Box::new(Value::Null), n_variants: 2, null_variant: Some(0), } }; let record_contents = vec![ ("id".into(), transaction_id), ("status".into(), status), ("event_count".into(), event_count), ("data_collections".into(), data_collections), ]; let avro = Value::Record(record_contents); debug_assert!(avro.validate(DEBEZIUM_TRANSACTION_SCHEMA.top_node())); mz_avro::encode_unchecked(&avro, &DEBEZIUM_TRANSACTION_SCHEMA, &mut buf); buf }
I: IntoIterator<Item = Datum<'a>>, { let value_fields: Vec<(String, Value)> = names_types .iter() .zip_eq(datums) .map(|((name, typ), datum)| { let name = name.as_str().to_owned(); use mz_avro::types::ToAvro; (name, TypedDatum::new(datum, typ.clone()).avro()) }) .collect(); let v = Value::Record(value_fields); v }
function_block-function_prefix_line
[ { "content": "/// Encode a `Value` into avro format.\n\n///\n\n/// **NOTE** This will not perform schema validation. The value is assumed to\n\n/// be valid with regards to the schema. Schema are needed only to guide the\n\n/// encoding for complex type values.\n\npub fn encode_ref(value: &Value, schema: Schema...
Rust
src/comglue/glue.rs
estokes/netidx-excel
959d7b8f02188970a26b8130a4072767b22124bb
use crate::{ comglue::{ dispatch::IRTDUpdateEventWrap, interface::{IDispatch, IRTDServer, IRTDUpdateEvent}, variant::{string_from_wstr, SafeArray, Variant}, }, server::{Server, TopicId}, }; use anyhow::{bail, Result}; use com::sys::{HRESULT, IID, NOERROR}; use log::{debug, error}; use netidx::{ path::Path, subscriber::{Event, Value}, }; use windows::Win32::System::Com::{ ITypeInfo, DISPPARAMS, EXCEPINFO, SAFEARRAY, SAFEARRAYBOUND, VARIANT, }; struct Params(*mut DISPPARAMS); impl Drop for Params { fn drop(&mut self) { unsafe { for i in 0..self.len() { if let Ok(v) = self.get_mut(i) { *v = Variant::new(); } } } } } impl Params { fn new(ptr: *mut DISPPARAMS) -> Result<Self> { if ptr.is_null() { bail!("invalid params") } Ok(Params(ptr)) } unsafe fn len(&self) -> usize { (*self.0).cArgs as usize } unsafe fn get(&self, i: usize) -> Result<&Variant> { if i < self.len() { Ok(Variant::ref_from_raw((*self.0).rgvarg.offset(i as isize))) } else { bail!("no param at index: {}", i) } } unsafe fn get_mut(&self, i: usize) -> Result<&mut Variant> { if i < self.len() { Ok(Variant::ref_from_raw_mut((*self.0).rgvarg.offset(i as isize))) } else { bail!("no param at index: {}", i) } } } unsafe fn dispatch_server_start(server: &Server, params: Params) -> Result<()> { server.server_start(IRTDUpdateEventWrap::new(params.get(0)?.try_into()?)?); Ok(()) } unsafe fn dispatch_connect_data(server: &Server, params: Params) -> Result<()> { let topic_id = TopicId(params.get(2)?.try_into()?); let topics: &SafeArray = params.get(1)?.try_into()?; let topics = topics.read()?; let path = match topics.iter()?.next() { None => bail!("not enough topics"), Some(v) => { let path: String = v.try_into()?; Path::from(path) } }; Ok(server.connect_data(topic_id, path)?) } fn variant_of_value(v: &Value) -> Variant { match v { Value::I32(v) | Value::Z32(v) => Variant::from(*v), Value::U32(v) | Value::V32(v) => Variant::from(*v), Value::I64(v) | Value::Z64(v) => Variant::from(*v), Value::U64(v) | Value::V64(v) => Variant::from(*v), Value::F32(v) => Variant::from(*v), Value::F64(v) => Variant::from(*v), Value::True => Variant::from(true), Value::False => Variant::from(false), Value::String(s) => Variant::from(&**s), Value::Bytes(_) => Variant::from("#BIN"), Value::Null => Variant::null(), Value::Ok => Variant::from("OK"), Value::Error(e) => Variant::from(&format!("#ERR {}", &**e)), Value::DateTime(d) => Variant::from(&d.to_string()), Value::Duration(d) => Variant::from(&format!("{}s", d.as_secs_f64())), Value::Array(_) => Variant::from(&format!("{}", v)), /* sadly this doesn't work { let mut res = SafeArray::new(&[ SAFEARRAYBOUND { lLbound: 0, cElements: a.len() as u32 }, ]); { let mut res = res.write().unwrap(); for (i, v) in a.iter().enumerate() { *res.get_mut(&[i as i32]).unwrap() = variant_of_value(v); } } Variant::from(res) }*/ } } fn variant_of_event(e: &Event) -> Variant { match e { Event::Unsubscribed => Variant::from("#SUB"), Event::Update(v) => variant_of_value(v), } } unsafe fn dispatch_refresh_data( server: &Server, params: Params, result: &mut Variant, ) -> Result<()> { let ntopics = params.get_mut(0)?; let ntopics: &mut i32 = ntopics.try_into()?; let mut updates = server.refresh_data(); let len = updates.len(); *ntopics = len as i32; let mut array = SafeArray::new(&[ SAFEARRAYBOUND { lLbound: 0, cElements: 2 }, SAFEARRAYBOUND { lLbound: 0, cElements: len as u32 }, ]); { let mut wh = array.write()?; for (i, (TopicId(tid), e)) in updates.drain().enumerate() { *wh.get_mut(&[0, i as i32])? = Variant::from(tid); *wh.get_mut(&[1, i as i32])? = variant_of_event(&e); } } *result = Variant::from(array); Ok(()) } unsafe fn dispatch_disconnect_data(server: &Server, params: Params) -> Result<()> { let topic_id = TopicId(params.get(0)?.try_into()?); Ok(server.disconnect_data(topic_id)) } com::class! { #[derive(Debug)] pub class NetidxRTD: IRTDServer(IDispatch) { server: Server, } impl IDispatch for NetidxRTD { fn get_type_info_count(&self, info: *mut u32) -> HRESULT { debug!("get_type_info_count(info: {})", unsafe { *info }); if !info.is_null() { unsafe { *info = 0; } } NOERROR } fn get_type_info(&self, _lcid: u32, _type_info: *mut *mut ITypeInfo) -> HRESULT { NOERROR } pub fn get_ids_of_names( &self, riid: *const IID, names: *const *mut u16, names_len: u32, lcid: u32, ids: *mut i32 ) -> HRESULT { debug!("get_ids_of_names(riid: {:?}, names: {:?}, names_len: {}, lcid: {}, ids: {:?})", riid, names, names_len, lcid, ids); if !ids.is_null() && !names.is_null() { for i in 0..names_len { let name = unsafe { string_from_wstr(*names.offset(i as isize)) }; let name = name.to_string_lossy(); debug!("name: {}", name); match &*name { "ServerStart" => unsafe { *ids.offset(i as isize) = 0; }, "ServerTerminate" => unsafe { *ids.offset(i as isize) = 1; } "ConnectData" => unsafe { *ids.offset(i as isize) = 2; } "RefreshData" => unsafe { *ids.offset(i as isize) = 3; } "DisconnectData" => unsafe { *ids.offset(i as isize) = 4; } "Heartbeat" => unsafe { *ids.offset(i as isize) = 5; } _ => debug!("unknown method: {}", name) } } } NOERROR } unsafe fn invoke( &self, id: i32, iid: *const IID, lcid: u32, flags: u16, params: *mut DISPPARAMS, result: *mut VARIANT, exception: *mut EXCEPINFO, arg_error: *mut u32 ) -> HRESULT { debug!( "invoke(id: {}, iid: {:?}, lcid: {}, flags: {}, params: {:?}, result: {:?}, exception: {:?}, arg_error: {:?})", id, iid, lcid, flags, params, result, exception, arg_error ); assert!(!params.is_null()); let result = Variant::ref_from_raw_mut(result); let params = match Params::new(params) { Ok(p) => p, Err(e) => { error!("failed to wrap params {}", e); *result = Variant::error(); return NOERROR; } }; match id { 0 => { debug!("ServerStart"); match dispatch_server_start(&self.server, params) { Ok(()) => { *result = Variant::from(1); }, Err(e) => { error!("server_start invalid arg {}", e); *result = Variant::error(); } } }, 1 => { debug!("ServerTerminate"); self.server.server_terminate(); *result = Variant::from(1); }, 2 => { debug!("ConnectData"); match dispatch_connect_data(&self.server, params) { Ok(()) => { *result = Variant::from(1); }, Err(e) => { error!("connect_data invalid arg {}", e); *result = Variant::error(); } } }, 3 => { debug!("RefreshData"); match dispatch_refresh_data(&self.server, params, result) { Ok(()) => (), Err(e) => { error!("refresh_data failed {}", e); *result = Variant::error(); } } }, 4 => { debug!("DisconnectData"); match dispatch_disconnect_data(&self.server, params) { Ok(()) => { *result = Variant::from(1); } Err(e) => { error!("disconnect_data invalid arg {}", e); *result = Variant::error() } } }, 5 => { debug!("Heartbeat"); *result = Variant::from(1); }, _ => { debug!("unknown method {} called", id) }, } NOERROR } } impl IRTDServer for NetidxRTD { fn server_start(&self, _cb: *const IRTDUpdateEvent, _res: *mut i32) -> HRESULT { debug!("ServerStart called directly"); NOERROR } fn connect_data(&self, _topic_id: i32, _topic: *const SAFEARRAY, _get_new_values: *mut VARIANT, _res: *mut VARIANT) -> HRESULT { debug!("ConnectData called directly"); NOERROR } fn refresh_data(&self, _topic_count: *mut i32, _data: *mut SAFEARRAY) -> HRESULT { debug!("RefreshData called directly"); NOERROR } fn disconnect_data(&self, _topic_id: i32) -> HRESULT { debug!("DisconnectData called directly"); NOERROR } fn heartbeat(&self, _res: *mut i32) -> HRESULT { debug!("Heartbeat called directly"); NOERROR } fn server_terminate(&self) -> HRESULT { debug!("ServerTerminate called directly"); NOERROR } } }
use crate::{ comglue::{ dispatch::IRTDUpdateEventWrap, interface::{IDispatch, IRTDServer, IRTDUpdateEvent}, variant::{string_from_wstr, SafeArray, Variant}, }, server::{Server, TopicId}, }; use anyhow::{bail, Result}; use com::sys::{HRESULT, IID, NOERROR}; use log::{debug, error}; use netidx::{ path::Path, subscriber::{Event, Value}, }; use windows::Win32::System::Com::{ ITypeInfo, DISPPARAMS, EXCEPINFO, SAFEARRAY, SAFEARRAYBOUND, VARIANT, }; struct Params(*mut DISPPARAMS); impl Drop for Params { fn drop(&mut self) { unsafe { for i in 0..self.len() { if let Ok(v) = self.get_mut(i) { *v = Variant::new(); } } } } } impl Params { fn new(ptr: *mut DISPPARAMS) -> Result<Self> { if ptr.is_null() { bail!("invalid params") } Ok(Params(ptr)) } unsafe fn len(&self) -> usize { (*self.0).cArgs as usize } unsafe fn get(&self, i: usize) -> Result<&Variant> { if i < self.len() { Ok(Variant::ref_from_raw((*self.0).rgvarg.offset(i as isize))) } else { bail!("no param at index: {}", i) } } unsafe fn get_mut(&self, i: usize) -> Result<&mut Variant> { if i < self.len() { Ok(Variant::ref_from_raw_mut((*self.0).rgvarg.offset(i as isize))) } else { bail!("no param at index: {}", i) } } } unsafe fn dispatch_server_start(server: &Server, params: Params) -> Result<()> { server.server_start(IRTDUpdateEventWrap::new(params.get(0)?.try_into()?)?); Ok(()) } unsafe fn dispatch_connect_data(server: &Server, params: Params) -> Result<()> { let topic_id = TopicId(params.get(2)?.try_into()?); let topics: &SafeArray = params.get(1)?.try_into()?; let topics = topics.read()?; let path = match topics.iter()?.next() { None => bail!("not enough topics"), Some(v) => { let path: String = v.try_into()?; Path::from(path) } }; Ok(server.connect_data(topic_id, path)?) } fn variant_of_value(v: &Value) -> Variant { match v { Value::I32(v) | Value::Z32(v) => Variant::from(*v), Value::U32(v) | Value::V32(v) => Variant::from(*v), Value::I64(v) | Value::Z64(v) => Variant::from(*v), Value::U64(v) | Value::V64(v) => Variant::from(*v), Value::F32(v) => Variant::from(*v), Value::F64(v) => Variant::from(*v), Value::True => Variant::from(true), Value::False => Variant::from(false), Value::String(s) => Variant::from(&**s), Value::Bytes(_) => Variant::from("#BIN"), Value::Null => Variant::null(), Value::Ok => Variant::from("OK"), Value::Error(e) => Variant::from(&format!("#ERR {}", &**e)), Value::DateTime(d) => Variant::from(&d.to_string()), Value::Duration(d) => Variant::from(&format!("{}s", d.as_secs_f64())), Value::Array(_) => Variant::from(&format!("{}", v)), /* sadly this doesn't work { let mut res = SafeArray::new(&[ SAFEARRAYBOUND { lLbound: 0, cElements: a.len() as u32 }, ]); { let mut res = res.write().unwrap(); for (i, v) in a.iter().enumerate() { *res.get_mut(&[i as i32]).unwrap() = variant_of_value(v); } } Variant::from(res) }*/ } } fn variant_of_event(e: &Event) -> Variant { match e { Event::Unsubscribed => Variant::from("#SUB"), Event::Update(v) => variant_of_value(v), } } unsafe fn dispatch_refresh_data( server: &Server, params: Params, result: &mut Variant, ) -> Result<()> { let ntopics = params.get_mut(0)?; let ntopics: &mut i32 = ntopics.try_into()?; let mut updates = server.refresh_data(); let len = updates.len(); *ntopics = len as i32; let mut array = SafeArray::new(&[ SAFEARRAYBOUND { lLbound: 0, cElements: 2 }, SAFEARRAYBOUND { lLbound: 0, cElements: len as u32 }, ]); { let mut wh = array.write()?; for (i, (TopicId(tid), e)) in updates.drain().enumerate()
}, } NOERROR } } impl IRTDServer for NetidxRTD { fn server_start(&self, _cb: *const IRTDUpdateEvent, _res: *mut i32) -> HRESULT { debug!("ServerStart called directly"); NOERROR } fn connect_data(&self, _topic_id: i32, _topic: *const SAFEARRAY, _get_new_values: *mut VARIANT, _res: *mut VARIANT) -> HRESULT { debug!("ConnectData called directly"); NOERROR } fn refresh_data(&self, _topic_count: *mut i32, _data: *mut SAFEARRAY) -> HRESULT { debug!("RefreshData called directly"); NOERROR } fn disconnect_data(&self, _topic_id: i32) -> HRESULT { debug!("DisconnectData called directly"); NOERROR } fn heartbeat(&self, _res: *mut i32) -> HRESULT { debug!("Heartbeat called directly"); NOERROR } fn server_terminate(&self) -> HRESULT { debug!("ServerTerminate called directly"); NOERROR } } }
{ *wh.get_mut(&[0, i as i32])? = Variant::from(tid); *wh.get_mut(&[1, i as i32])? = variant_of_event(&e); } } *result = Variant::from(array); Ok(()) } unsafe fn dispatch_disconnect_data(server: &Server, params: Params) -> Result<()> { let topic_id = TopicId(params.get(0)?.try_into()?); Ok(server.disconnect_data(topic_id)) } com::class! { #[derive(Debug)] pub class NetidxRTD: IRTDServer(IDispatch) { server: Server, } impl IDispatch for NetidxRTD { fn get_type_info_count(&self, info: *mut u32) -> HRESULT { debug!("get_type_info_count(info: {})", unsafe { *info }); if !info.is_null() { unsafe { *info = 0; } } NOERROR } fn get_type_info(&self, _lcid: u32, _type_info: *mut *mut ITypeInfo) -> HRESULT { NOERROR } pub fn get_ids_of_names( &self, riid: *const IID, names: *const *mut u16, names_len: u32, lcid: u32, ids: *mut i32 ) -> HRESULT { debug!("get_ids_of_names(riid: {:?}, names: {:?}, names_len: {}, lcid: {}, ids: {:?})", riid, names, names_len, lcid, ids); if !ids.is_null() && !names.is_null() { for i in 0..names_len { let name = unsafe { string_from_wstr(*names.offset(i as isize)) }; let name = name.to_string_lossy(); debug!("name: {}", name); match &*name { "ServerStart" => unsafe { *ids.offset(i as isize) = 0; }, "ServerTerminate" => unsafe { *ids.offset(i as isize) = 1; } "ConnectData" => unsafe { *ids.offset(i as isize) = 2; } "RefreshData" => unsafe { *ids.offset(i as isize) = 3; } "DisconnectData" => unsafe { *ids.offset(i as isize) = 4; } "Heartbeat" => unsafe { *ids.offset(i as isize) = 5; } _ => debug!("unknown method: {}", name) } } } NOERROR } unsafe fn invoke( &self, id: i32, iid: *const IID, lcid: u32, flags: u16, params: *mut DISPPARAMS, result: *mut VARIANT, exception: *mut EXCEPINFO, arg_error: *mut u32 ) -> HRESULT { debug!( "invoke(id: {}, iid: {:?}, lcid: {}, flags: {}, params: {:?}, result: {:?}, exception: {:?}, arg_error: {:?})", id, iid, lcid, flags, params, result, exception, arg_error ); assert!(!params.is_null()); let result = Variant::ref_from_raw_mut(result); let params = match Params::new(params) { Ok(p) => p, Err(e) => { error!("failed to wrap params {}", e); *result = Variant::error(); return NOERROR; } }; match id { 0 => { debug!("ServerStart"); match dispatch_server_start(&self.server, params) { Ok(()) => { *result = Variant::from(1); }, Err(e) => { error!("server_start invalid arg {}", e); *result = Variant::error(); } } }, 1 => { debug!("ServerTerminate"); self.server.server_terminate(); *result = Variant::from(1); }, 2 => { debug!("ConnectData"); match dispatch_connect_data(&self.server, params) { Ok(()) => { *result = Variant::from(1); }, Err(e) => { error!("connect_data invalid arg {}", e); *result = Variant::error(); } } }, 3 => { debug!("RefreshData"); match dispatch_refresh_data(&self.server, params, result) { Ok(()) => (), Err(e) => { error!("refresh_data failed {}", e); *result = Variant::error(); } } }, 4 => { debug!("DisconnectData"); match dispatch_disconnect_data(&self.server, params) { Ok(()) => { *result = Variant::from(1); } Err(e) => { error!("disconnect_data invalid arg {}", e); *result = Variant::error() } } }, 5 => { debug!("Heartbeat"); *result = Variant::from(1); }, _ => { debug!("unknown method {} called", id)
random
[ { "content": "fn next_index(bounds: &[SAFEARRAYBOUND], idx: &mut [i32]) -> bool {\n\n let mut i = 0;\n\n while i < bounds.len() {\n\n if idx[i] < (bounds[i].lLbound + bounds[i].cElements as i32) {\n\n idx[i] += 1;\n\n for j in 0..i {\n\n idx[j] = bounds[j].lLbou...
Rust
app/gui/src/presenter.rs
hubertp/enso
d3846578cceb4844f1f94d4e7ca51762bba3fada
pub mod code; pub mod graph; pub mod project; pub mod searcher; pub use code::Code; pub use graph::Graph; pub use project::Project; pub use searcher::Searcher; use crate::prelude::*; use crate::controller::ide::StatusNotification; use crate::executor::global::spawn_stream_handler; use crate::presenter; use enso_frp as frp; use ide_view as view; use ide_view::graph_editor::SharedHashMap; #[derive(Debug)] struct Model { logger: Logger, current_project: RefCell<Option<Project>>, controller: controller::Ide, view: view::root::View, } impl Model { fn setup_and_display_new_project(self: Rc<Self>) { *self.current_project.borrow_mut() = None; if let Some(project_model) = self.controller.current_project() { self.view.switch_view_to_project(); let project_view = self.view.project(); let status_bar = self.view.status_bar().clone_ref(); let breadcrumbs = &project_view.graph().model.breadcrumbs; breadcrumbs.project_name(project_model.name().to_string()); let status_notifications = self.controller.status_notifications().clone_ref(); let ide_controller = self.controller.clone_ref(); let project_controller = controller::Project::new(project_model, status_notifications.clone_ref()); executor::global::spawn(async move { match presenter::Project::initialize( ide_controller, project_controller, project_view, status_bar, ) .await { Ok(project) => { *self.current_project.borrow_mut() = Some(project); } Err(err) => { let err_msg = format!("Failed to initialize project: {}", err); error!(self.logger, "{err_msg}"); status_notifications.publish_event(err_msg) } } }); } } pub fn open_project(&self, project_name: String) { let logger = self.logger.clone_ref(); let controller = self.controller.clone_ref(); crate::executor::global::spawn(async move { if let Ok(managing_api) = controller.manage_projects() { if let Err(err) = managing_api.open_project_by_name(project_name).await { error!(logger, "Cannot open project by name: {err}."); } } else { warning!(logger, "Project opening failed: no ProjectManagingAPI available."); } }); } fn create_project(&self, template: Option<&str>) { let logger = self.logger.clone_ref(); let controller = self.controller.clone_ref(); let template = template.map(ToOwned::to_owned); crate::executor::global::spawn(async move { if let Ok(managing_api) = controller.manage_projects() { if let Err(err) = managing_api.create_new_project(template.clone()).await { if let Some(template) = template { error!( logger, "Could not create new project from template {template}: {err}." ); } else { error!(logger, "Could not create new project: {err}."); } } } else { warning!(logger, "Project creation failed: no ProjectManagingAPI available."); } }); } } #[derive(Clone, CloneRef, Debug)] pub struct Presenter { network: frp::Network, model: Rc<Model>, } impl Presenter { pub fn new(controller: controller::Ide, view: ide_view::root::View) -> Self { let logger = Logger::new("Presenter"); let current_project = default(); let model = Rc::new(Model { logger, controller, view, current_project }); frp::new_network! { network let welcome_view_frp = &model.view.welcome_screen().frp; eval welcome_view_frp.open_project((name) model.open_project(name.to_owned())); eval welcome_view_frp.create_project((templ) model.create_project(templ.as_deref())); let root_frp = &model.view.frp; root_frp.switch_view_to_project <+ welcome_view_frp.create_project.constant(()); root_frp.switch_view_to_project <+ welcome_view_frp.open_project.constant(()); } Self { model, network }.init() } fn init(self) -> Self { self.setup_status_bar_notification_handler(); self.setup_controller_notification_handler(); self.set_projects_list_on_welcome_screen(); self.model.clone_ref().setup_and_display_new_project(); self } fn setup_status_bar_notification_handler(&self) { use controller::ide::BackgroundTaskHandle as ControllerHandle; use ide_view::status_bar::process::Id as ViewHandle; let logger = self.model.logger.clone_ref(); let process_map = SharedHashMap::<ControllerHandle, ViewHandle>::new(); let status_bar = self.model.view.status_bar().clone_ref(); let status_notifications = self.model.controller.status_notifications().subscribe(); let weak = Rc::downgrade(&self.model); spawn_stream_handler(weak, status_notifications, move |notification, _| { match notification { StatusNotification::Event { label } => { status_bar.add_event(ide_view::status_bar::event::Label::new(label)); } StatusNotification::BackgroundTaskStarted { label, handle } => { status_bar.add_process(ide_view::status_bar::process::Label::new(label)); let view_handle = status_bar.last_process.value(); process_map.insert(handle, view_handle); } StatusNotification::BackgroundTaskFinished { handle } => { if let Some(view_handle) = process_map.remove(&handle) { status_bar.finish_process(view_handle); } else { warning!(logger, "Controllers finished process not displayed in view"); } } } futures::future::ready(()) }); } fn setup_controller_notification_handler(&self) { let stream = self.model.controller.subscribe(); let weak = Rc::downgrade(&self.model); spawn_stream_handler(weak, stream, move |notification, model| { match notification { controller::ide::Notification::NewProjectCreated | controller::ide::Notification::ProjectOpened => model.setup_and_display_new_project(), } futures::future::ready(()) }); } fn set_projects_list_on_welcome_screen(&self) { let controller = self.model.controller.clone_ref(); let welcome_view_frp = self.model.view.welcome_screen().frp.clone_ref(); let logger = self.model.logger.clone_ref(); crate::executor::global::spawn(async move { if let Ok(project_manager) = controller.manage_projects() { match project_manager.list_projects().await { Ok(projects) => { let names = projects.into_iter().map(|p| p.name.into()).collect::<Vec<_>>(); welcome_view_frp.set_projects_list(names); } Err(err) => { error!(logger, "Unable to get list of projects: {err}."); } } } }); } } #[allow(missing_docs)] impl Presenter { pub fn view(&self) -> &view::root::View { &self.model.view } pub fn controller(&self) -> &controller::Ide { &self.model.controller } }
pub mod code; pub mod graph; pub mod project; pub mod searcher; pub use code::Code; pub use graph::Graph; pub use project::Project; pub use searcher::Searcher; use crate::prelude::*; use crate::controller::ide::StatusNotification; use crate::executor::global::spawn_stream_handler; use crate::presenter; use enso_frp as frp; use ide_view as view; use ide_view::graph_editor::SharedHashMap; #[derive(Debug)] struct Model { logger: Logger, current_project: RefCell<Option<Project>>, controller: controller::Ide, view: view::root::View, } impl Model { fn setup_and_display_new_project(self: Rc<Self>) { *self.current_project.borrow_mut() = None; if let Some(project_model) = self.controller.current_project() { self.view.switch_view_to_project(); let project_view = self.view.project(); let status_bar = self.view.status_bar().clone_ref(); let breadcrumbs = &project_view.graph().model.breadcrumbs; breadcrumbs.project_name(project_model.name().to_string()); let status_notifications = self.controller.status_notifications().clone_ref(); let ide_controller = self.controller.clone_ref(); let project_controller = controller::Project::new(project_model, status_notifications.clone_ref()); executor::global::spawn(async move { match presenter::Project::initialize( ide_controller, project_controller, project_view, status_bar, ) .await { Ok(project) => { *self.current_project.borrow_mut() = Some(project); } Err(err) => { let err_msg = format!("Failed to initialize project: {}", err); error!(self.logger, "{err_msg}"); status_notifications.publish_event(err_msg) } } }); } } pub fn open_project(&self, project_name: String) { let logger = self.logger.clone_ref(); let controller = self.controller.clone_ref(); crate::executor::global::spawn(async move { if let Ok(managing_api) = controller.manage_projects() { if let Err(err) = managing_api.open_project_by_name(project_name).await { error!(logger, "Cannot open project by name: {err}."); } } else { warning!(logger, "Project opening failed: no ProjectManagingAPI available."); } }); } fn create_project(&self, template: Option<&str>) { let logger = self.logger.clone_ref(); let controller = self.controller.clone_ref(); let template = template.map(ToOwned::to_owned); crate::executor::global::spawn(async move { if let Ok(managing_api) = controller.manage_projects() { if let Err(err) = managing_api.create_new_project(template.clone()).await { if let Some(template) = template { error!( logger, "Could not create new project from template {template}: {err}." ); } else { error!(logger, "Could not create new project: {err}."); } } } else { warning!(logger, "Project creation failed: no ProjectManagingAPI available."); } }); } } #[derive(Clone, CloneRef, Debug)] pub struct Presenter { network: frp::Network, model: Rc<Model>, } impl Presenter { pub fn new(controller: controller::Ide, view: ide_view::root::View) -> Self { let logger = Logger::new("Presenter"); let current_project = default(); let model = Rc::new(Model { logger, controller, view, current_project }); frp::new_network! { network let welcome_view_frp = &model.view.welcome_screen().frp; eval welcome_view_frp.open_project((name) model.open_project(name.to_owned())); eval welcome_view_frp.create_project((templ) model.create_project(templ.as_deref())); let root_frp = &model.view.frp; root_frp.switch_view_to_project <+ welcome_view_frp.create_project.constant(()); root_frp.switch_view_to_project <+ welcome_view_frp.open_project.constant(()); } Self { model, network }.init() } fn init(self) -> Self { self.setup_status_bar_notification_handler();
fn setup_status_bar_notification_handler(&self) { use controller::ide::BackgroundTaskHandle as ControllerHandle; use ide_view::status_bar::process::Id as ViewHandle; let logger = self.model.logger.clone_ref(); let process_map = SharedHashMap::<ControllerHandle, ViewHandle>::new(); let status_bar = self.model.view.status_bar().clone_ref(); let status_notifications = self.model.controller.status_notifications().subscribe(); let weak = Rc::downgrade(&self.model); spawn_stream_handler(weak, status_notifications, move |notification, _| { match notification { StatusNotification::Event { label } => { status_bar.add_event(ide_view::status_bar::event::Label::new(label)); } StatusNotification::BackgroundTaskStarted { label, handle } => { status_bar.add_process(ide_view::status_bar::process::Label::new(label)); let view_handle = status_bar.last_process.value(); process_map.insert(handle, view_handle); } StatusNotification::BackgroundTaskFinished { handle } => { if let Some(view_handle) = process_map.remove(&handle) { status_bar.finish_process(view_handle); } else { warning!(logger, "Controllers finished process not displayed in view"); } } } futures::future::ready(()) }); } fn setup_controller_notification_handler(&self) { let stream = self.model.controller.subscribe(); let weak = Rc::downgrade(&self.model); spawn_stream_handler(weak, stream, move |notification, model| { match notification { controller::ide::Notification::NewProjectCreated | controller::ide::Notification::ProjectOpened => model.setup_and_display_new_project(), } futures::future::ready(()) }); } fn set_projects_list_on_welcome_screen(&self) { let controller = self.model.controller.clone_ref(); let welcome_view_frp = self.model.view.welcome_screen().frp.clone_ref(); let logger = self.model.logger.clone_ref(); crate::executor::global::spawn(async move { if let Ok(project_manager) = controller.manage_projects() { match project_manager.list_projects().await { Ok(projects) => { let names = projects.into_iter().map(|p| p.name.into()).collect::<Vec<_>>(); welcome_view_frp.set_projects_list(names); } Err(err) => { error!(logger, "Unable to get list of projects: {err}."); } } } }); } } #[allow(missing_docs)] impl Presenter { pub fn view(&self) -> &view::root::View { &self.model.view } pub fn controller(&self) -> &controller::Ide { &self.model.controller } }
self.setup_controller_notification_handler(); self.set_projects_list_on_welcome_screen(); self.model.clone_ref().setup_and_display_new_project(); self }
function_block-function_prefix_line
[ { "content": "/// Create providers from the current controller's action list.\n\npub fn create_providers_from_controller(logger: &Logger, controller: &controller::Searcher) -> Any {\n\n use controller::searcher::Actions;\n\n match controller.actions() {\n\n Actions::Loading => as_any(Rc::new(list_v...
Rust
examples/log-sensors.rs
quietlychris/f3
7ccc6f26fe16a4c053d09bcc61434c422f24d82f
#![deny(warnings)] #![no_main] #![no_std] extern crate panic_semihosting; use core::ptr; use aligned::Aligned; use byteorder::{ByteOrder, LE}; use cortex_m::{asm, itm}; use cortex_m_rt::entry; use f3::{ hal::{i2c::I2c, prelude::*, spi::Spi, stm32f30x, timer::Timer}, l3gd20::{self, Odr}, lsm303dlhc::{AccelOdr, MagOdr}, L3gd20, Lsm303dlhc, }; use nb::block; const FREQUENCY: u32 = 220; const NSAMPLES: u32 = 32 * FREQUENCY; #[entry] fn main() -> ! { let mut cp = cortex_m::Peripherals::take().unwrap(); let dp = stm32f30x::Peripherals::take().unwrap(); let mut flash = dp.FLASH.constrain(); let mut rcc = dp.RCC.constrain(); let clocks = rcc .cfgr .sysclk(64.mhz()) .pclk1(32.mhz()) .freeze(&mut flash.acr); unsafe { cp.DCB.demcr.modify(|r| r | (1 << 24)); let swo_freq = 2_000_000; cp.TPIU.acpr.write((clocks.sysclk().0 / swo_freq) - 1); cp.TPIU.sppr.write(2); cp.TPIU.ffcr.modify(|r| r & !(1 << 1)); const DBGMCU_CR: *mut u32 = 0xe0042004 as *mut u32; let r = ptr::read_volatile(DBGMCU_CR); ptr::write_volatile(DBGMCU_CR, r | (1 << 5)); cp.ITM.lar.write(0xC5ACCE55); cp.ITM.tcr.write( (0b000001 << 16) | (1 << 3) | (1 << 0), ); cp.ITM.ter[0].write(1); } let mut gpioa = dp.GPIOA.split(&mut rcc.ahb); let mut gpiob = dp.GPIOB.split(&mut rcc.ahb); let mut gpioe = dp.GPIOE.split(&mut rcc.ahb); let scl = gpiob.pb6.into_af4(&mut gpiob.moder, &mut gpiob.afrl); let sda = gpiob.pb7.into_af4(&mut gpiob.moder, &mut gpiob.afrl); let i2c = I2c::i2c1(dp.I2C1, (scl, sda), 400.khz(), clocks, &mut rcc.apb1); let mut lsm303dlhc = Lsm303dlhc::new(i2c).unwrap(); lsm303dlhc.accel_odr(AccelOdr::Hz400).unwrap(); lsm303dlhc.mag_odr(MagOdr::Hz220).unwrap(); let mut nss = gpioe .pe3 .into_push_pull_output(&mut gpioe.moder, &mut gpioe.otyper); nss.set_high(); let sck = gpioa.pa5.into_af5(&mut gpioa.moder, &mut gpioa.afrl); let miso = gpioa.pa6.into_af5(&mut gpioa.moder, &mut gpioa.afrl); let mosi = gpioa.pa7.into_af5(&mut gpioa.moder, &mut gpioa.afrl); let spi = Spi::spi1( dp.SPI1, (sck, miso, mosi), l3gd20::MODE, 1.mhz(), clocks, &mut rcc.apb2, ); let mut l3gd20 = L3gd20::new(spi, nss).unwrap(); l3gd20.set_odr(Odr::Hz380).unwrap(); let mut timer = Timer::tim2(dp.TIM2, FREQUENCY.hz(), clocks, &mut rcc.apb1); itm::write_all(&mut cp.ITM.stim[0], &[0]); let mut tx_buf: Aligned<u32, [u8; 20]> = Aligned([0; 20]); for _ in 0..NSAMPLES { block!(timer.wait()).unwrap(); let m = lsm303dlhc.mag().unwrap(); let ar = l3gd20.gyro().unwrap(); let g = lsm303dlhc.accel().unwrap(); let mut buf = [0; 18]; let mut start = 0; LE::write_i16(&mut buf[start..start + 2], m.x); start += 2; LE::write_i16(&mut buf[start..start + 2], m.y); start += 2; LE::write_i16(&mut buf[start..start + 2], m.z); start += 2; LE::write_i16(&mut buf[start..start + 2], ar.x); start += 2; LE::write_i16(&mut buf[start..start + 2], ar.y); start += 2; LE::write_i16(&mut buf[start..start + 2], ar.z); start += 2; LE::write_i16(&mut buf[start..start + 2], g.x); start += 2; LE::write_i16(&mut buf[start..start + 2], g.y); start += 2; LE::write_i16(&mut buf[start..start + 2], g.z); cobs::encode(&buf, &mut tx_buf); itm::write_aligned(&mut cp.ITM.stim[0], &tx_buf); } asm::bkpt(); loop {} }
#![deny(warnings)] #![no_main] #![no_std] extern crate panic_semihosting; use core::ptr; use aligned::Aligned; use byteorder::{ByteOrder, LE}; use cortex_m::{asm, itm}; use cortex_m_rt::entry; use f3::{ hal::{i2c::I2c, prelude::*, spi::Spi, stm32f30x, timer::Timer}, l3gd20::{self, Odr}, lsm303dlhc::{AccelOdr, MagOdr}, L3gd20, Lsm303dlhc, }; use nb::block; const FREQUENCY: u32 = 220; const NSAMPLES: u32 = 32 * FREQUENCY; #[entry] fn main() -> ! { let mut cp = cortex_m::Peripherals::take().unwrap(); let dp = stm32f30x::Peripherals::take().unwrap(); let mut flash = dp.FLASH.constrain(); let mut rcc = dp.RCC.constrain(); let clocks = rcc .cfgr .sysclk(64.mhz()) .pclk1(32.mhz()) .freeze(&mut flash.acr); unsafe { cp.DCB.demcr.modify(|r| r | (1 << 24)); let swo_freq = 2_000_000; cp.TPIU.acpr.write((clocks.sysclk().0 / swo_freq) - 1); cp.TPIU.sppr.write(2); cp.TPIU.ffcr.modify(|r| r & !(1 << 1)); const DBGMCU_CR: *mut u32 = 0xe0042004 as *mut u32; let r = ptr::read_volatile(DBGMCU_CR); ptr::write_volatile(DBGMCU_CR, r | (1 << 5)); cp.ITM.lar.write(0xC5ACCE55); cp.ITM.tcr.write( (0b000001 << 16) | (1 << 3) | (1 << 0), ); cp.ITM.ter[0].write(1); } let mut gpioa = dp.GPIOA.split(&mut rcc.ahb); let mut gpiob = dp.GPIOB.split(&mut rcc.ahb); let mut gpioe = dp.GPIOE.split(&mut rcc.ahb); let scl = gpiob.pb6.into_af4(&mut gpiob.moder, &mut gpiob.afrl); let sda = gpiob.pb7.into_af4(&mut gpiob.moder, &mut gpiob.afrl); let i2c = I2c::i2c1(dp.I2C1, (scl, sda), 400.khz(), clocks, &mut rcc.apb1); let mut lsm303dlhc = Lsm303dlhc::new(i2c).unwrap(); lsm303dlhc.accel_odr(AccelOdr::Hz400).unwrap(); lsm303dlhc.mag_odr(MagOdr::Hz220).unwrap(); let mut nss = gpioe .pe3 .into_push_pull_output(&mut gpioe.moder, &mut gpioe.otyper); nss.set_high(); let sck = gpioa.pa5.into_af5(&mut gpioa.moder, &mut gpioa.afrl); let miso = gpioa.pa6.into_af5(&mut gpioa.moder, &mut gpioa.afrl); let mosi = gpioa.pa7.into_af5(&mut gpioa.moder, &mut gpioa.afrl); let spi = Spi::spi1( dp.SPI1, (sck, miso, mosi), l3gd20::MODE, 1.mhz(), clocks, &mut rcc.apb2, ); let mut l3gd20 = L3gd20::new(spi, nss).unwrap(); l3gd20.set_odr(Odr::Hz380).unwrap(); let mut timer = Timer::tim2(dp.TIM2, FREQUENCY.hz(), clocks, &mut rcc.apb1); itm::write_all(&mut cp.ITM.stim[0], &[0]); let mut tx_buf: Aligned<u32, [u8; 20]> = Aligned([0; 20]); for _ in 0..NSAMPLES { block!(
LE::write_i16(&mut buf[start..start + 2], ar.x); start += 2; LE::write_i16(&mut buf[start..start + 2], ar.y); start += 2; LE::write_i16(&mut buf[start..start + 2], ar.z); start += 2; LE::write_i16(&mut buf[start..start + 2], g.x); start += 2; LE::write_i16(&mut buf[start..start + 2], g.y); start += 2; LE::write_i16(&mut buf[start..start + 2], g.z); cobs::encode(&buf, &mut tx_buf); itm::write_aligned(&mut cp.ITM.stim[0], &tx_buf); } asm::bkpt(); loop {} }
timer.wait()).unwrap(); let m = lsm303dlhc.mag().unwrap(); let ar = l3gd20.gyro().unwrap(); let g = lsm303dlhc.accel().unwrap(); let mut buf = [0; 18]; let mut start = 0; LE::write_i16(&mut buf[start..start + 2], m.x); start += 2; LE::write_i16(&mut buf[start..start + 2], m.y); start += 2; LE::write_i16(&mut buf[start..start + 2], m.z); start += 2;
random
[ { "content": "#[entry]\n\nfn main() -> ! {\n\n let p = cortex_m::Peripherals::take().unwrap();\n\n let mut itm = p.ITM;\n\n\n\n iprintln!(&mut itm.stim[0], \"Hello, world!\");\n\n\n\n asm::bkpt();\n\n\n\n loop {}\n\n}\n", "file_path": "examples/itm.rs", "rank": 0, "score": 89875.80130...
Rust
benchmark/src/main.rs
negamartin/midly
6881b0b1cf55ef5aa8e8573a9176f14334e02555
use std::{ env, fs, path::{Path, PathBuf}, time::Instant, }; const MIDI_DIR: &str = "../test-asset"; const MIDI_EXT: &[&str] = &["mid", "midi", "rmi"]; const PARSERS: &[(&str, fn(&Path) -> Result<usize, String>)] = &[ (&"midly", parse_midly), (&"nom-midi", parse_nom), (&"rimd", parse_rimd), ]; fn parse_midly(path: &Path) -> Result<usize, String> { let data = fs::read(path).map_err(|err| format!("{}", err))?; let smf = midly::Smf::parse(&data).map_err(|err| format!("{}", err))?; Ok(smf.tracks.len()) } fn parse_nom(path: &Path) -> Result<usize, String> { let data = fs::read(path).map_err(|err| format!("{}", err))?; let smf = nom_midi::parser::parse_smf(&data) .map_err(|err| format!("{}", err))? .1; Ok(smf.tracks.len()) } fn parse_rimd(path: &Path) -> Result<usize, String> { let smf = rimd::SMF::from_file(path).map_err(|err| format!("{}", err))?; Ok(smf.tracks.len()) } fn list_midis(dir: &Path) -> Vec<PathBuf> { let mut midis = Vec::new(); for entry in fs::read_dir(dir).unwrap() { let path = entry.unwrap().path(); if MIDI_EXT .iter() .any(|ext| path.extension() == Some(ext.as_ref())) { midis.push(path); } } midis } fn use_parser(parse: fn(&Path) -> Result<usize, String>, path: &Path) -> Result<(), String> { let round = |num: f64| (num * 100.0).round() / 100.0; let runtime = || -> Result<_, String> { let start = Instant::now(); let out = parse(path)?; let time = round((start.elapsed().as_micros() as f64) / 1000.0); Ok((out, time)) }; let (track_count, cold_time) = runtime()?; let runtime = || -> Result<_, String> { let (out, time) = runtime()?; assert_eq!( out, track_count, "parser is not consistent with track counts" ); Ok(time) }; let iters = (2000.0 / cold_time).floor() as u64 + 1; let mut total_time = 0.0; let mut max_time = cold_time; let mut min_time = cold_time; for _ in 0..iters { let time = runtime()?; total_time += time; max_time = max_time.max(time); min_time = min_time.min(time); } let avg_time = round(total_time / (iters as f64)); eprintln!( "{} tracks in {} iters / min {} / avg {} / max {}", track_count, iters, min_time, avg_time, max_time ); Ok(()) } fn main() { let midi_filter = env::args().nth(1).unwrap_or_default().to_lowercase(); let parser_filter = env::args().nth(2).unwrap_or_default().to_lowercase(); let midi_dir = env::args().nth(3).unwrap_or(MIDI_DIR.to_string()); let parsers = PARSERS .iter() .filter(|(name, _)| name.contains(&parser_filter)) .collect::<Vec<_>>(); if parsers.is_empty() { eprintln!("no parsers match the pattern \"{}\"", parser_filter); eprint!("available parsers: "); for (i, (name, _)) in PARSERS.iter().enumerate() { if i > 0 { eprint!(", "); } eprint!("{}", name); } } let unfiltered_midis = list_midis(midi_dir.as_ref()); let midis = unfiltered_midis .iter() .filter(|midi| { midi.file_name() .unwrap_or_default() .to_str() .expect("non-utf8 file") .to_lowercase() .contains(&midi_filter) }) .collect::<Vec<_>>(); if midis.is_empty() { eprintln!("no midi files match the pattern \"{}\"", midi_filter); eprintln!("available midi files:"); for file in unfiltered_midis.iter() { eprintln!(" {}", file.display()); } } else { for midi in midis { let size = std::fs::read(midi).map(|b| b.len()).unwrap_or(0); eprintln!("parsing file \"{}\" ({} KB)", midi.display(), size / 1024); for &(name, parse) in parsers.iter() { eprint!(" {}: ", name); match use_parser(*parse, &midi) { Ok(()) => {} Err(_err) => { eprintln!("parse error"); } } } eprintln!(); } } }
use std::{ env, fs, path::{Path, PathBuf}, time::Instant, }; const MIDI_DIR: &str = "../test-asset"; const MIDI_EXT: &[&str] = &["mid", "midi", "rmi"]; const PARSERS: &[(&str, fn(&Path) -> Result<usize, String>)] = &[ (&"midly", parse_midly), (&"nom-midi", parse_nom), (&"rimd", parse_rimd), ]; fn parse_midly(path: &Path) -> Result<usize, String> { let data = fs::read(path).map_err(|err| format!("{}", err))?; let smf = midly::Smf::parse(&data).map_err(|err| format!("{}", err))?; Ok(smf.tracks.len()) } fn parse_nom(path: &Path) -> Result<usize, String> { let data = fs::read(path).map_err(|err| format!("{}", err))?; let smf = nom_midi::parser::parse_smf(&data) .map_err(|err| format!("{}", err))? .1; Ok(smf.tracks.len()) } fn parse_rimd(path: &Path) -> Result<usize, String> { let smf = rimd::SMF::from_file(path).map_err(|err| format!("{}", err))?; Ok(smf.tracks.len()) } fn list_midis(dir: &Path) -> Vec<PathBuf> { let mut midis = Vec::new(); for entry in fs::read_dir(dir).unwrap() { let path = entry.unwrap().path(); if MIDI_EXT .iter() .any(|ext| path.extension() == Some(ext.as_ref())) { midis.push(path); } } midis } fn use_parser(parse: fn(&Path) -> Result<usize, String>, path: &Path) -> Result<(), String> { let round = |num: f64| (num * 100.0).round() / 100.0; let runtime = || -> Result<_, String> { let start = Instant::now(); let out = parse(path)?; let time = round((start.elapsed().as_micros() as f64) / 1000.0); Ok((out, time)) }; let (track_count, cold_time) = runtime()?; let runtime = || -> Result<_, String> { let (out, time) = runtime()?; assert_eq!( out, track_count, "parser is not consistent with track counts" ); Ok(time) }; let iters = (2000.0 / cold_time).floor() as u64 + 1; let mut total_time = 0.0; let mut max_time = cold_time; let mut min_time = cold_time; for _ in 0..iters { let time = runtime()?; total_time += time; max_time = max_time.max(time); min_time = min_time.min(time); }
fn main() { let midi_filter = env::args().nth(1).unwrap_or_default().to_lowercase(); let parser_filter = env::args().nth(2).unwrap_or_default().to_lowercase(); let midi_dir = env::args().nth(3).unwrap_or(MIDI_DIR.to_string()); let parsers = PARSERS .iter() .filter(|(name, _)| name.contains(&parser_filter)) .collect::<Vec<_>>(); if parsers.is_empty() { eprintln!("no parsers match the pattern \"{}\"", parser_filter); eprint!("available parsers: "); for (i, (name, _)) in PARSERS.iter().enumerate() { if i > 0 { eprint!(", "); } eprint!("{}", name); } } let unfiltered_midis = list_midis(midi_dir.as_ref()); let midis = unfiltered_midis .iter() .filter(|midi| { midi.file_name() .unwrap_or_default() .to_str() .expect("non-utf8 file") .to_lowercase() .contains(&midi_filter) }) .collect::<Vec<_>>(); if midis.is_empty() { eprintln!("no midi files match the pattern \"{}\"", midi_filter); eprintln!("available midi files:"); for file in unfiltered_midis.iter() { eprintln!(" {}", file.display()); } } else { for midi in midis { let size = std::fs::read(midi).map(|b| b.len()).unwrap_or(0); eprintln!("parsing file \"{}\" ({} KB)", midi.display(), size / 1024); for &(name, parse) in parsers.iter() { eprint!(" {}: ", name); match use_parser(*parse, &midi) { Ok(()) => {} Err(_err) => { eprintln!("parse error"); } } } eprintln!(); } } }
let avg_time = round(total_time / (iters as f64)); eprintln!( "{} tracks in {} iters / min {} / avg {} / max {}", track_count, iters, min_time, avg_time, max_time ); Ok(()) }
function_block-function_prefix_line
[ { "content": "#[cfg(feature = \"alloc\")]\n\nfn validate_smf(header: &Header, track_count_hint: u16, track_count: usize) -> Result<()> {\n\n if cfg!(feature = \"strict\") {\n\n ensure!(\n\n track_count_hint as usize == track_count,\n\n err_malformed!(\"file has a different amount...
Rust
crates/rust-analyzer/src/config.rs
theHamsta/rust-analyzer
f7f01dd5f0a8254abeefb0156e2c4ebe1447bfb6
use std::{ffi::OsString, path::PathBuf}; use lsp_types::ClientCapabilities; use ra_flycheck::FlycheckConfig; use ra_ide::{AssistConfig, CompletionConfig, InlayHintsConfig}; use ra_project_model::CargoConfig; use serde::Deserialize; #[derive(Debug, Clone)] pub struct Config { pub client_caps: ClientCapsConfig, pub with_sysroot: bool, pub publish_diagnostics: bool, pub lru_capacity: Option<usize>, pub proc_macro_srv: Option<(PathBuf, Vec<OsString>)>, pub files: FilesConfig, pub notifications: NotificationsConfig, pub cargo: CargoConfig, pub rustfmt: RustfmtConfig, pub check: Option<FlycheckConfig>, pub inlay_hints: InlayHintsConfig, pub completion: CompletionConfig, pub assist: AssistConfig, pub call_info_full: bool, pub lens: LensConfig, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct LensConfig { pub run: bool, pub debug: bool, pub impementations: bool, } impl Default for LensConfig { fn default() -> Self { Self { run: true, debug: true, impementations: true } } } impl LensConfig { pub const NO_LENS: LensConfig = Self { run: false, debug: false, impementations: false }; pub fn any(&self) -> bool { self.impementations || self.runnable() } pub fn none(&self) -> bool { !self.any() } pub fn runnable(&self) -> bool { self.run || self.debug } } #[derive(Debug, Clone)] pub struct FilesConfig { pub watcher: FilesWatcher, pub exclude: Vec<String>, } #[derive(Debug, Clone)] pub enum FilesWatcher { Client, Notify, } #[derive(Debug, Clone)] pub struct NotificationsConfig { pub cargo_toml_not_found: bool, } #[derive(Debug, Clone)] pub enum RustfmtConfig { Rustfmt { extra_args: Vec<String>, }, #[allow(unused)] CustomCommand { command: String, args: Vec<String>, }, } #[derive(Debug, Clone, Default)] pub struct ClientCapsConfig { pub location_link: bool, pub line_folding_only: bool, pub hierarchical_symbols: bool, pub code_action_literals: bool, pub work_done_progress: bool, pub code_action_group: bool, } impl Default for Config { fn default() -> Self { Config { client_caps: ClientCapsConfig::default(), with_sysroot: true, publish_diagnostics: true, lru_capacity: None, proc_macro_srv: None, files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() }, notifications: NotificationsConfig { cargo_toml_not_found: true }, cargo: CargoConfig::default(), rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() }, check: Some(FlycheckConfig::CargoCommand { command: "check".to_string(), all_targets: true, all_features: true, extra_args: Vec::new(), }), inlay_hints: InlayHintsConfig { type_hints: true, parameter_hints: true, chaining_hints: true, max_length: None, }, completion: CompletionConfig { enable_postfix_completions: true, add_call_parenthesis: true, add_call_argument_snippets: true, ..CompletionConfig::default() }, assist: AssistConfig::default(), call_info_full: true, lens: LensConfig::default(), } } } impl Config { #[rustfmt::skip] pub fn update(&mut self, value: &serde_json::Value) { log::info!("Config::update({:#})", value); let client_caps = self.client_caps.clone(); *self = Default::default(); self.client_caps = client_caps; set(value, "/withSysroot", &mut self.with_sysroot); set(value, "/diagnostics/enable", &mut self.publish_diagnostics); set(value, "/lruCapacity", &mut self.lru_capacity); self.files.watcher = match get(value, "/files/watcher") { Some("client") => FilesWatcher::Client, Some("notify") | _ => FilesWatcher::Notify }; set(value, "/notifications/cargoTomlNotFound", &mut self.notifications.cargo_toml_not_found); set(value, "/cargo/noDefaultFeatures", &mut self.cargo.no_default_features); set(value, "/cargo/allFeatures", &mut self.cargo.all_features); set(value, "/cargo/features", &mut self.cargo.features); set(value, "/cargo/loadOutDirsFromCheck", &mut self.cargo.load_out_dirs_from_check); set(value, "/cargo/target", &mut self.cargo.target); match get(value, "/procMacro/enable") { Some(true) => { if let Ok(path) = std::env::current_exe() { self.proc_macro_srv = Some((path, vec!["proc-macro".into()])); } } _ => self.proc_macro_srv = None, } match get::<Vec<String>>(value, "/rustfmt/overrideCommand") { Some(mut args) if !args.is_empty() => { let command = args.remove(0); self.rustfmt = RustfmtConfig::CustomCommand { command, args, } } _ => { if let RustfmtConfig::Rustfmt { extra_args } = &mut self.rustfmt { set(value, "/rustfmt/extraArgs", extra_args); } } }; if let Some(false) = get(value, "/checkOnSave/enable") { self.check = None; } else { match get::<Vec<String>>(value, "/checkOnSave/overrideCommand") { Some(mut args) if !args.is_empty() => { let command = args.remove(0); self.check = Some(FlycheckConfig::CustomCommand { command, args, }); } _ => { if let Some(FlycheckConfig::CargoCommand { command, extra_args, all_targets, all_features }) = &mut self.check { set(value, "/checkOnSave/extraArgs", extra_args); set(value, "/checkOnSave/command", command); set(value, "/checkOnSave/allTargets", all_targets); set(value, "/checkOnSave/allFeatures", all_features); } } }; } set(value, "/inlayHints/typeHints", &mut self.inlay_hints.type_hints); set(value, "/inlayHints/parameterHints", &mut self.inlay_hints.parameter_hints); set(value, "/inlayHints/chainingHints", &mut self.inlay_hints.chaining_hints); set(value, "/inlayHints/maxLength", &mut self.inlay_hints.max_length); set(value, "/completion/postfix/enable", &mut self.completion.enable_postfix_completions); set(value, "/completion/addCallParenthesis", &mut self.completion.add_call_parenthesis); set(value, "/completion/addCallArgumentSnippets", &mut self.completion.add_call_argument_snippets); set(value, "/callInfo/full", &mut self.call_info_full); let mut lens_enabled = true; set(value, "/lens/enable", &mut lens_enabled); if lens_enabled { set(value, "/lens/run", &mut self.lens.run); set(value, "/lens/debug", &mut self.lens.debug); set(value, "/lens/implementations", &mut self.lens.impementations); } else { self.lens = LensConfig::NO_LENS; } log::info!("Config::update() = {:#?}", self); fn get<'a, T: Deserialize<'a>>(value: &'a serde_json::Value, pointer: &str) -> Option<T> { value.pointer(pointer).and_then(|it| T::deserialize(it).ok()) } fn set<'a, T: Deserialize<'a>>(value: &'a serde_json::Value, pointer: &str, slot: &mut T) { if let Some(new_value) = get(value, pointer) { *slot = new_value } } } pub fn update_caps(&mut self, caps: &ClientCapabilities) { if let Some(doc_caps) = caps.text_document.as_ref() { if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) { self.client_caps.location_link = value; } if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only) { self.client_caps.line_folding_only = value } if let Some(value) = doc_caps .document_symbol .as_ref() .and_then(|it| it.hierarchical_document_symbol_support) { self.client_caps.hierarchical_symbols = value } if let Some(value) = doc_caps.code_action.as_ref().map(|it| it.code_action_literal_support.is_some()) { self.client_caps.code_action_literals = value; } self.completion.allow_snippets(false); if let Some(completion) = &doc_caps.completion { if let Some(completion_item) = &completion.completion_item { if let Some(value) = completion_item.snippet_support { self.completion.allow_snippets(value); } } } } if let Some(window_caps) = caps.window.as_ref() { if let Some(value) = window_caps.work_done_progress { self.client_caps.work_done_progress = value; } } self.assist.allow_snippets(false); if let Some(experimental) = &caps.experimental { let snippet_text_edit = experimental.get("snippetTextEdit").and_then(|it| it.as_bool()) == Some(true); self.assist.allow_snippets(snippet_text_edit); let code_action_group = experimental.get("codeActionGroup").and_then(|it| it.as_bool()) == Some(true); self.client_caps.code_action_group = code_action_group } } }
use std::{ffi::OsString, path::PathBuf}; use lsp_types::ClientCapabilities; use ra_flycheck::FlycheckConfig; use ra_ide::{AssistConfig, CompletionConfig, InlayHintsConfig}; use ra_project_model::CargoConfig; use serde::Deserialize; #[derive(Debug, Clone)] pub struct Config { pub client_caps: ClientCapsConfig, pub with_sysroot: bool, pub publish_diagnostics: bool, pub lru_capacity: Option<usize>, pub proc_macro_srv: Option<(PathBuf, Vec<OsString>)>, pub files: FilesConfig, pub notifications: NotificationsConfig, pub cargo: CargoConfig, pub rustfmt: RustfmtConfig, pub check: Option<FlycheckConfig>, pub inlay_hints: InlayHintsConfig, pub completion: CompletionConfig, pub assist: AssistConfig, pub call_info_full: bool, pub lens: LensConfig, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct LensConfig { pub run: bool, pub debug: bool, pub impementations: bool, } impl Default for LensConfig { fn default() -> Self { Self { run: true, debug: true, impementations: true } } } impl LensConfig { pub const NO_LENS: LensConfig = Self { run: false, debug: false, impementations: false }; pub fn any(&self) -> bool { self.impementations || self.runnable() } pub fn none(&self) -> bool { !self.any() } pub fn runnable(&self) -> bool { self.run || self.debug } } #[derive(Debug, Clone)] pub struct FilesConfig { pub watcher: FilesWatcher, pub exclude: Vec<String>, } #[derive(Debug, Clone)] pub enum FilesWatcher { Client, Notify, } #[derive(Debug, Clone)] pub struct NotificationsConfig { pub cargo_toml_not_found: bool, } #[derive(Debug, Clone)] pub enum RustfmtConfig { Rustfmt { extra_args: Vec<String>, }, #[allow(unused)] CustomCommand { command: String, args: Vec<String>, }, } #[derive(Debug, Clone, Default)] pub struct ClientCapsConfig { pub location_link: bool, pub line_folding_only: bool, pub hierarchical_symbols: bool, pub code_action_literals: bool, pub work_done_progress: bool, pub code_action_group: bool, } impl Default for Config { fn default() -> Self { Config { client_caps: ClientCapsConfig::default(), with_sysroot: true, publish_diagnostics: true, lru_capacity: None, proc_macro_srv: None, files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() }, notifications: NotificationsConfig { cargo_toml_not_found: true },
} impl Config { #[rustfmt::skip] pub fn update(&mut self, value: &serde_json::Value) { log::info!("Config::update({:#})", value); let client_caps = self.client_caps.clone(); *self = Default::default(); self.client_caps = client_caps; set(value, "/withSysroot", &mut self.with_sysroot); set(value, "/diagnostics/enable", &mut self.publish_diagnostics); set(value, "/lruCapacity", &mut self.lru_capacity); self.files.watcher = match get(value, "/files/watcher") { Some("client") => FilesWatcher::Client, Some("notify") | _ => FilesWatcher::Notify }; set(value, "/notifications/cargoTomlNotFound", &mut self.notifications.cargo_toml_not_found); set(value, "/cargo/noDefaultFeatures", &mut self.cargo.no_default_features); set(value, "/cargo/allFeatures", &mut self.cargo.all_features); set(value, "/cargo/features", &mut self.cargo.features); set(value, "/cargo/loadOutDirsFromCheck", &mut self.cargo.load_out_dirs_from_check); set(value, "/cargo/target", &mut self.cargo.target); match get(value, "/procMacro/enable") { Some(true) => { if let Ok(path) = std::env::current_exe() { self.proc_macro_srv = Some((path, vec!["proc-macro".into()])); } } _ => self.proc_macro_srv = None, } match get::<Vec<String>>(value, "/rustfmt/overrideCommand") { Some(mut args) if !args.is_empty() => { let command = args.remove(0); self.rustfmt = RustfmtConfig::CustomCommand { command, args, } } _ => { if let RustfmtConfig::Rustfmt { extra_args } = &mut self.rustfmt { set(value, "/rustfmt/extraArgs", extra_args); } } }; if let Some(false) = get(value, "/checkOnSave/enable") { self.check = None; } else { match get::<Vec<String>>(value, "/checkOnSave/overrideCommand") { Some(mut args) if !args.is_empty() => { let command = args.remove(0); self.check = Some(FlycheckConfig::CustomCommand { command, args, }); } _ => { if let Some(FlycheckConfig::CargoCommand { command, extra_args, all_targets, all_features }) = &mut self.check { set(value, "/checkOnSave/extraArgs", extra_args); set(value, "/checkOnSave/command", command); set(value, "/checkOnSave/allTargets", all_targets); set(value, "/checkOnSave/allFeatures", all_features); } } }; } set(value, "/inlayHints/typeHints", &mut self.inlay_hints.type_hints); set(value, "/inlayHints/parameterHints", &mut self.inlay_hints.parameter_hints); set(value, "/inlayHints/chainingHints", &mut self.inlay_hints.chaining_hints); set(value, "/inlayHints/maxLength", &mut self.inlay_hints.max_length); set(value, "/completion/postfix/enable", &mut self.completion.enable_postfix_completions); set(value, "/completion/addCallParenthesis", &mut self.completion.add_call_parenthesis); set(value, "/completion/addCallArgumentSnippets", &mut self.completion.add_call_argument_snippets); set(value, "/callInfo/full", &mut self.call_info_full); let mut lens_enabled = true; set(value, "/lens/enable", &mut lens_enabled); if lens_enabled { set(value, "/lens/run", &mut self.lens.run); set(value, "/lens/debug", &mut self.lens.debug); set(value, "/lens/implementations", &mut self.lens.impementations); } else { self.lens = LensConfig::NO_LENS; } log::info!("Config::update() = {:#?}", self); fn get<'a, T: Deserialize<'a>>(value: &'a serde_json::Value, pointer: &str) -> Option<T> { value.pointer(pointer).and_then(|it| T::deserialize(it).ok()) } fn set<'a, T: Deserialize<'a>>(value: &'a serde_json::Value, pointer: &str, slot: &mut T) { if let Some(new_value) = get(value, pointer) { *slot = new_value } } } pub fn update_caps(&mut self, caps: &ClientCapabilities) { if let Some(doc_caps) = caps.text_document.as_ref() { if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) { self.client_caps.location_link = value; } if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only) { self.client_caps.line_folding_only = value } if let Some(value) = doc_caps .document_symbol .as_ref() .and_then(|it| it.hierarchical_document_symbol_support) { self.client_caps.hierarchical_symbols = value } if let Some(value) = doc_caps.code_action.as_ref().map(|it| it.code_action_literal_support.is_some()) { self.client_caps.code_action_literals = value; } self.completion.allow_snippets(false); if let Some(completion) = &doc_caps.completion { if let Some(completion_item) = &completion.completion_item { if let Some(value) = completion_item.snippet_support { self.completion.allow_snippets(value); } } } } if let Some(window_caps) = caps.window.as_ref() { if let Some(value) = window_caps.work_done_progress { self.client_caps.work_done_progress = value; } } self.assist.allow_snippets(false); if let Some(experimental) = &caps.experimental { let snippet_text_edit = experimental.get("snippetTextEdit").and_then(|it| it.as_bool()) == Some(true); self.assist.allow_snippets(snippet_text_edit); let code_action_group = experimental.get("codeActionGroup").and_then(|it| it.as_bool()) == Some(true); self.client_caps.code_action_group = code_action_group } } }
cargo: CargoConfig::default(), rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() }, check: Some(FlycheckConfig::CargoCommand { command: "check".to_string(), all_targets: true, all_features: true, extra_args: Vec::new(), }), inlay_hints: InlayHintsConfig { type_hints: true, parameter_hints: true, chaining_hints: true, max_length: None, }, completion: CompletionConfig { enable_postfix_completions: true, add_call_parenthesis: true, add_call_argument_snippets: true, ..CompletionConfig::default() }, assist: AssistConfig::default(), call_info_full: true, lens: LensConfig::default(), } }
function_block-function_prefix_line
[ { "content": "pub fn run_dist(nightly: bool, client_version: Option<String>) -> Result<()> {\n\n let dist = project_root().join(\"dist\");\n\n rm_rf(&dist)?;\n\n fs2::create_dir_all(&dist)?;\n\n\n\n if let Some(version) = client_version {\n\n let release_tag = if nightly { \"nightly\".to_stri...
Rust
wasm/src/context.rs
PoiScript/blog
e6b08531d30bcb41a5fde53bfe07eb20f2a152c8
use chrono::serde::{ts_milliseconds, ts_milliseconds_option}; use chrono::{DateTime, Utc}; use maud::Markup; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use wasm_bindgen::prelude::*; #[derive(Debug, Serialize, Deserialize)] pub struct OrgMeta { pub slug: String, pub title: String, #[serde(with = "ts_milliseconds")] pub published: DateTime<Utc>, #[serde(default, with = "ts_milliseconds_option")] pub updated: Option<DateTime<Utc>>, pub tags: Vec<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct ImgMeta { pub slug: String, pub width: u32, pub height: u32, } #[wasm_bindgen(typescript_custom_section)] const HIGHLIGHTER_STYLE: &'static str = r#" interface Highlighter { highlight(code: string, lang: string): string; } "#; #[wasm_bindgen] extern "C" { #[wasm_bindgen(typescript_type = "Highlighter")] pub type Highlighter; #[wasm_bindgen(method)] pub fn highlight(this: &Highlighter, code: &str, lang: &str) -> String; } #[wasm_bindgen] pub struct Context { pub(crate) base_url: String, pub(crate) content: Content, pub(crate) highlighter: Highlighter, pub(crate) org_meta: HashMap<String, OrgMeta>, pub(crate) img_meta: HashMap<String, ImgMeta>, } pub enum Content { Txt { status: u32, body: String, }, Amp { status: u32, head: Markup, body: Markup, }, Html { status: u32, head: Markup, body: Markup, }, Rss { status: u32, body: Markup, }, } #[wasm_bindgen] impl Context { #[wasm_bindgen(constructor)] pub fn new(mut base_url: String, highlighter: Highlighter) -> Context { let len = base_url.trim_end_matches('/').len(); base_url.truncate(len); Context { base_url, highlighter, content: Content::Txt { status: 404, body: String::new(), }, org_meta: HashMap::new(), img_meta: HashMap::new(), } } #[wasm_bindgen] pub fn get_type(&self) -> String { match self.content { Content::Txt { .. } => "txt", Content::Amp { .. } => "amp", Content::Html { .. } => "html", Content::Rss { .. } => "rss", } .into() } #[wasm_bindgen] pub fn get_status(&self) -> u32 { match self.content { Content::Amp { status, .. } => status, Content::Html { status, .. } => status, Content::Rss { status, .. } => status, Content::Txt { status, .. } => status, } } #[wasm_bindgen] pub fn get_head(&self) -> Option<String> { match &self.content { Content::Amp { head, .. } => Some(head.0.clone()), Content::Html { head, .. } => Some(head.0.clone()), _ => None, } } #[wasm_bindgen] pub fn get_body(&self) -> Option<String> { match &self.content { Content::Amp { body, .. } => Some(body.0.clone()), Content::Html { body, .. } => Some(body.0.clone()), Content::Rss { body, .. } => Some(body.0.clone()), Content::Txt { body, .. } => Some(body.clone()), } } #[wasm_bindgen] pub fn get_version(&self) -> String { concat!( "Solomon ", env!("CARGO_PKG_VERSION"), " (", env!("CARGO_GIT_HASH"), "): ", env!("CARGO_BUILD_TIME") ) .into() } } impl Context { pub fn find_prev_and_next(&self, date: &DateTime<Utc>) -> (Option<&OrgMeta>, Option<&OrgMeta>) { ( self.org_meta .values() .filter(|org| org.slug.starts_with("/post/") && org.published < *date) .min_by(|a, b| b.published.cmp(&a.published)), self.org_meta .values() .filter(|org| org.slug.starts_with("/post/") && org.published > *date) .min_by(|a, b| b.published.cmp(&a.published)), ) } pub async fn load_org(&self, slug: &str) -> Result<String, JsValue> { let url = format!("{}.org", slug.trim_start_matches('/')); let text = self.load(&url).await?; Ok(text) } pub async fn load_org_meta(&mut self) -> Result<(), JsValue> { if !self.org_meta.is_empty() { return Ok(()); } let text = self.load("org-meta.json").await?; self.org_meta = serde_json::from_str(&text) .map_err(|err| JsValue::from_str(&format!("seder error: {}", err)))?; Ok(()) } pub async fn load_img_meta(&mut self) -> Result<(), JsValue> { if !self.img_meta.is_empty() { return Ok(()); } let text = self.load("img-meta.json").await?; self.img_meta = serde_json::from_str(&text) .map_err(|err| JsValue::from_str(&format!("seder error: {}", err)))?; Ok(()) } async fn load(&self, path: &str) -> Result<String, JsValue> { if cfg!(feature = "worker") { #[wasm_bindgen] extern "C" { #[wasm_bindgen(catch, js_namespace = SOLOMON_KV, js_name = "get")] async fn kv_get(key: &str) -> Result<JsValue, JsValue>; } let text = kv_get(path).await?; let text = text.as_string().unwrap(); Ok(text) } else { use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; use web_sys::Response; let window = web_sys::window().unwrap(); let url = format!("{}/{}", self.base_url, path); let response = JsFuture::from(window.fetch_with_str(&url)).await?; assert!(response.is_instance_of::<Response>()); let response: Response = response.dyn_into().unwrap(); let text = JsFuture::from(response.text()?).await?; let text = text.as_string().unwrap(); Ok(text) } } }
use chrono::serde::{ts_milliseconds, ts_milliseconds_option}; use chrono::{DateTime, Utc}; use maud::Markup; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use wasm_bindgen::prelude::*; #[derive(Debug, Serialize, Deserialize)] pub struct OrgMeta { pub slug: String, pub title: String, #[serde(with = "ts_milliseconds")] pub published: DateTime<Utc>, #[serde(default, with = "ts_milliseconds_option")] pub updated: Option<DateTime<Utc>>, pub tags: Vec<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct ImgMeta { pub slug: String, pub width: u32, pub height: u32, } #[wasm_bindgen(typescript_custom_section)] const HIGHLIGHTER_STYLE: &'static str = r#" interface Highlighter { highlight(code: string, lang: string): string; } "#; #[wasm_bindgen] extern "C" { #[wasm_bindgen(typescript_type = "Highlighter")] pub type Highlighter; #[wasm_bindgen(method)] pub fn highlight(this: &Highlighter, code: &str, lang: &str) -> String; } #[wasm_bindgen] pub struct Context { pub(crate) base_url: String, pub(crate) content: Content, pub(crate) highlighter: Highlighter, pub(crate) org_meta: HashMap<String, OrgMeta>, pub(crate) img_meta: HashMap<String, ImgMeta>, } pub enum Content { Txt { status: u32, body: String, }, Amp { status: u32, head: Markup, body: Markup, }, Html { status: u32, head: Markup, body: Markup, }, Rss { status: u32, body: Markup, }, } #[wasm_bindgen] impl Context { #[wasm_bindgen(constructor)] pub fn new(mut base_url: String, highlighter: Highlighter) -> Context { let len = base_url.trim_end_matches('/').len(); base_url.truncate(len); Context { base_url, highlighter, content: Content::Txt { status: 404, body: String::new(), }, org_meta: HashMap::new(), img_meta: HashMap::new(), } } #[wasm_bindgen]
#[wasm_bindgen] pub fn get_status(&self) -> u32 { match self.content { Content::Amp { status, .. } => status, Content::Html { status, .. } => status, Content::Rss { status, .. } => status, Content::Txt { status, .. } => status, } } #[wasm_bindgen] pub fn get_head(&self) -> Option<String> { match &self.content { Content::Amp { head, .. } => Some(head.0.clone()), Content::Html { head, .. } => Some(head.0.clone()), _ => None, } } #[wasm_bindgen] pub fn get_body(&self) -> Option<String> { match &self.content { Content::Amp { body, .. } => Some(body.0.clone()), Content::Html { body, .. } => Some(body.0.clone()), Content::Rss { body, .. } => Some(body.0.clone()), Content::Txt { body, .. } => Some(body.clone()), } } #[wasm_bindgen] pub fn get_version(&self) -> String { concat!( "Solomon ", env!("CARGO_PKG_VERSION"), " (", env!("CARGO_GIT_HASH"), "): ", env!("CARGO_BUILD_TIME") ) .into() } } impl Context { pub fn find_prev_and_next(&self, date: &DateTime<Utc>) -> (Option<&OrgMeta>, Option<&OrgMeta>) { ( self.org_meta .values() .filter(|org| org.slug.starts_with("/post/") && org.published < *date) .min_by(|a, b| b.published.cmp(&a.published)), self.org_meta .values() .filter(|org| org.slug.starts_with("/post/") && org.published > *date) .min_by(|a, b| b.published.cmp(&a.published)), ) } pub async fn load_org(&self, slug: &str) -> Result<String, JsValue> { let url = format!("{}.org", slug.trim_start_matches('/')); let text = self.load(&url).await?; Ok(text) } pub async fn load_org_meta(&mut self) -> Result<(), JsValue> { if !self.org_meta.is_empty() { return Ok(()); } let text = self.load("org-meta.json").await?; self.org_meta = serde_json::from_str(&text) .map_err(|err| JsValue::from_str(&format!("seder error: {}", err)))?; Ok(()) } pub async fn load_img_meta(&mut self) -> Result<(), JsValue> { if !self.img_meta.is_empty() { return Ok(()); } let text = self.load("img-meta.json").await?; self.img_meta = serde_json::from_str(&text) .map_err(|err| JsValue::from_str(&format!("seder error: {}", err)))?; Ok(()) } async fn load(&self, path: &str) -> Result<String, JsValue> { if cfg!(feature = "worker") { #[wasm_bindgen] extern "C" { #[wasm_bindgen(catch, js_namespace = SOLOMON_KV, js_name = "get")] async fn kv_get(key: &str) -> Result<JsValue, JsValue>; } let text = kv_get(path).await?; let text = text.as_string().unwrap(); Ok(text) } else { use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; use web_sys::Response; let window = web_sys::window().unwrap(); let url = format!("{}/{}", self.base_url, path); let response = JsFuture::from(window.fetch_with_str(&url)).await?; assert!(response.is_instance_of::<Response>()); let response: Response = response.dyn_into().unwrap(); let text = JsFuture::from(response.text()?).await?; let text = text.as_string().unwrap(); Ok(text) } } }
pub fn get_type(&self) -> String { match self.content { Content::Txt { .. } => "txt", Content::Amp { .. } => "amp", Content::Html { .. } => "html", Content::Rss { .. } => "rss", } .into() }
function_block-function_prefix_line
[ { "content": "pub fn get_id(n: usize, s: &str) -> String {\n\n let mut hasher = DefaultHasher::new();\n\n\n\n for c in s.chars() {\n\n hasher.write_u32(c as u32);\n\n }\n\n\n\n format!(\"{n:02x}{:.6x}\", hasher.finish() as u32)\n\n}\n", "file_path": "wasm/src/utils.rs", "rank": 0, ...
Rust
tests/poll.rs
Licenser/mio
0d8f48d24c577e5379c936e72610a997aa716e8c
use mio::net::{TcpListener, TcpStream}; use mio::*; use std::net; use std::sync::{Arc, Barrier}; use std::thread::{self, sleep}; use std::time::Duration; mod util; use util::{any_local_address, assert_send, assert_sync, init}; #[test] fn is_send_and_sync() { assert_sync::<Poll>(); assert_send::<Poll>(); assert_sync::<Registry>(); assert_send::<Registry>(); } #[test] fn run_once_with_nothing() { init(); let mut events = Events::with_capacity(16); let mut poll = Poll::new().unwrap(); poll.poll(&mut events, Some(Duration::from_millis(100))) .unwrap(); } #[test] fn add_then_drop() { init(); let mut events = Events::with_capacity(16); let l = TcpListener::bind(any_local_address()).unwrap(); let mut poll = Poll::new().unwrap(); poll.registry() .register(&l, Token(1), Interests::READABLE | Interests::WRITABLE) .unwrap(); drop(l); poll.poll(&mut events, Some(Duration::from_millis(100))) .unwrap(); } #[test] fn zero_duration_polls_events() { init(); let mut poll = Poll::new().unwrap(); let mut events = Events::with_capacity(16); let listener = net::TcpListener::bind(any_local_address()).unwrap(); let addr = listener.local_addr().unwrap(); let streams: Vec<TcpStream> = (0..3) .map(|n| { let stream = TcpStream::connect(addr).unwrap(); poll.registry() .register(&stream, Token(n), Interests::WRITABLE) .unwrap(); stream }) .collect(); sleep(Duration::from_millis(10)); poll.poll(&mut events, Some(Duration::from_nanos(0))) .unwrap(); assert!(!events.is_empty()); drop(streams); drop(listener); } #[test] fn test_poll_closes_fd() { init(); for _ in 0..2000 { let mut poll = Poll::new().unwrap(); let mut events = Events::with_capacity(4); poll.poll(&mut events, Some(Duration::from_millis(0))) .unwrap(); drop(poll); } } #[test] fn test_drop_cancels_interest_and_shuts_down() { init(); use mio::net::TcpStream; use std::io; use std::io::Read; use std::net::TcpListener; use std::thread; let l = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = l.local_addr().unwrap(); let t = thread::spawn(move || { let mut s = l.incoming().next().unwrap().unwrap(); s.set_read_timeout(Some(Duration::from_secs(5))) .expect("set_read_timeout"); let r = s.read(&mut [0; 16]); match r { Ok(_) => (), Err(e) => { if e.kind() != io::ErrorKind::UnexpectedEof { panic!(e); } } } }); let mut poll = Poll::new().unwrap(); let mut s = TcpStream::connect(addr).unwrap(); poll.registry() .register(&s, Token(1), Interests::READABLE | Interests::WRITABLE) .unwrap(); let mut events = Events::with_capacity(16); 'outer: loop { poll.poll(&mut events, None).unwrap(); for event in &events { if event.token() == Token(1) { break 'outer; } } } let mut b = [0; 1024]; match s.read(&mut b) { Ok(_) => panic!("unexpected ok"), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => (), Err(e) => panic!("unexpected error: {:?}", e), } drop(s); t.join().unwrap(); } #[test] fn test_registry_behind_arc() { init(); let mut poll = Poll::new().unwrap(); let registry = Arc::new(poll.registry().try_clone().unwrap()); let mut events = Events::with_capacity(128); let listener = TcpListener::bind(any_local_address()).unwrap(); let addr = listener.local_addr().unwrap(); let barrier = Arc::new(Barrier::new(3)); let registry2 = Arc::clone(&registry); let registry3 = Arc::clone(&registry); let barrier2 = Arc::clone(&barrier); let barrier3 = Arc::clone(&barrier); let handle1 = thread::spawn(move || { registry2 .register(&listener, Token(0), Interests::READABLE) .unwrap(); barrier2.wait(); }); let handle2 = thread::spawn(move || { let stream = TcpStream::connect(addr).unwrap(); registry3 .register(&stream, Token(1), Interests::READABLE | Interests::WRITABLE) .unwrap(); barrier3.wait(); }); poll.poll(&mut events, Some(Duration::from_millis(1000))) .unwrap(); assert!(events.iter().count() >= 1); barrier.wait(); handle1.join().unwrap(); handle2.join().unwrap(); } #[test] #[cfg(any(target_os = "linux", target_os = "windows"))] pub fn test_double_register() { init(); let poll = Poll::new().unwrap(); let l = TcpListener::bind("127.0.0.1:0".parse().unwrap()).unwrap(); poll.registry() .register(&l, Token(0), Interests::READABLE) .unwrap(); assert!(poll .registry() .register(&l, Token(1), Interests::READABLE) .is_err()); }
use mio::net::{TcpListener, TcpStream}; use mio::*; use std::net; use std::sync::{Arc, Barrier}; use std::thread::{self, sleep}; use std::time::Duration; mod util; use util::{any_local_address, assert_send, assert_sync, init}; #[test] fn is_send_and_sync() { assert_sync::<Poll>(); assert_send::<Poll>(); assert_sync::<Registry>(); assert_send::<Registry>(); } #[test]
#[test] fn add_then_drop() { init(); let mut events = Events::with_capacity(16); let l = TcpListener::bind(any_local_address()).unwrap(); let mut poll = Poll::new().unwrap(); poll.registry() .register(&l, Token(1), Interests::READABLE | Interests::WRITABLE) .unwrap(); drop(l); poll.poll(&mut events, Some(Duration::from_millis(100))) .unwrap(); } #[test] fn zero_duration_polls_events() { init(); let mut poll = Poll::new().unwrap(); let mut events = Events::with_capacity(16); let listener = net::TcpListener::bind(any_local_address()).unwrap(); let addr = listener.local_addr().unwrap(); let streams: Vec<TcpStream> = (0..3) .map(|n| { let stream = TcpStream::connect(addr).unwrap(); poll.registry() .register(&stream, Token(n), Interests::WRITABLE) .unwrap(); stream }) .collect(); sleep(Duration::from_millis(10)); poll.poll(&mut events, Some(Duration::from_nanos(0))) .unwrap(); assert!(!events.is_empty()); drop(streams); drop(listener); } #[test] fn test_poll_closes_fd() { init(); for _ in 0..2000 { let mut poll = Poll::new().unwrap(); let mut events = Events::with_capacity(4); poll.poll(&mut events, Some(Duration::from_millis(0))) .unwrap(); drop(poll); } } #[test] fn test_drop_cancels_interest_and_shuts_down() { init(); use mio::net::TcpStream; use std::io; use std::io::Read; use std::net::TcpListener; use std::thread; let l = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = l.local_addr().unwrap(); let t = thread::spawn(move || { let mut s = l.incoming().next().unwrap().unwrap(); s.set_read_timeout(Some(Duration::from_secs(5))) .expect("set_read_timeout"); let r = s.read(&mut [0; 16]); match r { Ok(_) => (), Err(e) => { if e.kind() != io::ErrorKind::UnexpectedEof { panic!(e); } } } }); let mut poll = Poll::new().unwrap(); let mut s = TcpStream::connect(addr).unwrap(); poll.registry() .register(&s, Token(1), Interests::READABLE | Interests::WRITABLE) .unwrap(); let mut events = Events::with_capacity(16); 'outer: loop { poll.poll(&mut events, None).unwrap(); for event in &events { if event.token() == Token(1) { break 'outer; } } } let mut b = [0; 1024]; match s.read(&mut b) { Ok(_) => panic!("unexpected ok"), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => (), Err(e) => panic!("unexpected error: {:?}", e), } drop(s); t.join().unwrap(); } #[test] fn test_registry_behind_arc() { init(); let mut poll = Poll::new().unwrap(); let registry = Arc::new(poll.registry().try_clone().unwrap()); let mut events = Events::with_capacity(128); let listener = TcpListener::bind(any_local_address()).unwrap(); let addr = listener.local_addr().unwrap(); let barrier = Arc::new(Barrier::new(3)); let registry2 = Arc::clone(&registry); let registry3 = Arc::clone(&registry); let barrier2 = Arc::clone(&barrier); let barrier3 = Arc::clone(&barrier); let handle1 = thread::spawn(move || { registry2 .register(&listener, Token(0), Interests::READABLE) .unwrap(); barrier2.wait(); }); let handle2 = thread::spawn(move || { let stream = TcpStream::connect(addr).unwrap(); registry3 .register(&stream, Token(1), Interests::READABLE | Interests::WRITABLE) .unwrap(); barrier3.wait(); }); poll.poll(&mut events, Some(Duration::from_millis(1000))) .unwrap(); assert!(events.iter().count() >= 1); barrier.wait(); handle1.join().unwrap(); handle2.join().unwrap(); } #[test] #[cfg(any(target_os = "linux", target_os = "windows"))] pub fn test_double_register() { init(); let poll = Poll::new().unwrap(); let l = TcpListener::bind("127.0.0.1:0".parse().unwrap()).unwrap(); poll.registry() .register(&l, Token(0), Interests::READABLE) .unwrap(); assert!(poll .registry() .register(&l, Token(1), Interests::READABLE) .is_err()); }
fn run_once_with_nothing() { init(); let mut events = Events::with_capacity(16); let mut poll = Poll::new().unwrap(); poll.poll(&mut events, Some(Duration::from_millis(100))) .unwrap(); }
function_block-full_function
[ { "content": "pub fn init() {\n\n static INIT: Once = Once::new();\n\n\n\n INIT.call_once(|| {\n\n env_logger::try_init().expect(\"unable to initialise logger\");\n\n })\n\n}\n\n\n", "file_path": "tests/util/mod.rs", "rank": 0, "score": 197869.68898741424 }, { "content": "///...
Rust
src/direct.rs
passcod/streampager
b562cb044029a9f67512d4a5ca8bf6fd3a490f30
use crate::config::{InterfaceMode, WrappingMode}; use crate::event::{Event, EventStream}; use crate::file::File; use crate::line::Line; use crate::progress::Progress; use anyhow::Result; use bit_set::BitSet; use std::time::{Duration, Instant}; use termwiz::input::InputEvent; use termwiz::surface::change::Change; use termwiz::surface::Position; use termwiz::terminal::Terminal; use vec_map::VecMap; #[derive(Debug)] pub(crate) enum Outcome { RenderIncomplete, RenderNothing, RenderComplete, Interrupted, } pub(crate) fn direct<T: Terminal>( term: &mut T, output_files: &[File], error_files: &[File], progress: Option<&Progress>, events: &mut EventStream, mode: InterfaceMode, ) -> Result<Outcome> { if mode == InterfaceMode::FullScreen { return Ok(Outcome::RenderNothing); } let delayed_deadline = match mode { InterfaceMode::Delayed(duration) => Some(Instant::now() + duration), _ => None, }; let mut loading = BitSet::with_capacity(output_files.len() + error_files.len()); for file in output_files.iter().chain(error_files.iter()) { loading.insert(file.index()); } let mut last_read = VecMap::new(); let mut collect_unread = |files: &[File], max_lines: usize| -> Vec<Vec<u8>> { let mut result = Vec::new(); for file in files.iter() { let index = file.index(); let mut lines = file.lines(); let last = last_read.get(index).cloned().unwrap_or(0); file.set_needed_lines(last + max_lines); if lines > 0 && !file.loaded() && file .with_line(lines - 1, |l| !l.ends_with(b"\n")) .unwrap_or(true) { lines -= 1; } if lines >= last { let lines = (last + max_lines).min(lines); result.reserve(lines - last); for i in last..lines { file.with_line(i, |l| result.push(l.to_vec())); } last_read.insert(index, lines); } } result }; let read_progress_lines = || -> Vec<Vec<u8>> { let line_count = progress.map(|p| p.lines()).unwrap_or(0); (0..line_count) .filter_map(|i| progress.and_then(|p| p.with_line(i, |l| l.to_vec()))) .collect::<Vec<_>>() }; let mut state = StreamingLines::default(); let delayed = delayed_deadline.is_some(); let has_one_screen_limit = match mode { InterfaceMode::Direct => false, _ => true, }; let mut render = |term: &mut T, h: usize, w: usize| -> Result<Option<Outcome>> { let append_output_lines = collect_unread(output_files, h + 2); let append_error_lines = collect_unread(error_files, h + 2); let progress_lines = read_progress_lines(); state.add_lines(append_output_lines, append_error_lines, progress_lines); if delayed { if has_one_screen_limit && state.height(w) >= h { return Ok(Some(Outcome::RenderNothing)); } } else { if has_one_screen_limit && state.height(w) >= h { return Ok(Some(Outcome::RenderIncomplete)); } let changes = state.render_pending_lines(w)?; term.render(&changes)?; } Ok(None) }; let mut size = term.get_screen_size()?; let mut loaded = BitSet::with_capacity(loading.capacity()); let mut remaining = output_files.len() + error_files.len(); while remaining > 0 { match events.get(term, Some(Duration::from_millis(10)))? { Some(Event::Loaded(i)) => { if loading.contains(i) && loaded.insert(i) { remaining -= 1; } } Some(Event::Input(InputEvent::Resized { .. })) => { size = term.get_screen_size()?; } Some(Event::Input(InputEvent::Key(key))) => { use termwiz::input::{KeyCode::Char, Modifiers}; match (key.modifiers, key.key) { (Modifiers::NONE, Char('q')) | (Modifiers::CTRL, Char('C')) => { return Ok(Outcome::Interrupted); } (Modifiers::NONE, Char('f')) | (Modifiers::NONE, Char(' ')) => { let outcome = if delayed { Outcome::RenderNothing } else { Outcome::RenderIncomplete }; return Ok(outcome); } _ => (), } } _ => (), } if let Some(deadline) = delayed_deadline { if deadline <= Instant::now() { return Ok(Outcome::RenderNothing); } } if let Some(outcome) = render(term, size.rows, size.cols)? { return Ok(outcome); } } if delayed { term.render(&state.render_pending_lines(size.cols)?)?; } Ok(Outcome::RenderComplete) } #[derive(Default)] struct StreamingLines { past_output_row_count: usize, new_output_lines: Vec<Vec<u8>>, error_lines: Vec<Vec<u8>>, progress_lines: Vec<Vec<u8>>, erase_row_count: usize, pending_changes: bool, } impl StreamingLines { fn add_lines( &mut self, mut append_output_lines: Vec<Vec<u8>>, mut append_error_lines: Vec<Vec<u8>>, replace_progress_lines: Vec<Vec<u8>>, ) { if append_output_lines.is_empty() && append_error_lines.is_empty() && replace_progress_lines == self.progress_lines { return; } self.new_output_lines.append(&mut append_output_lines); self.error_lines.append(&mut append_error_lines); self.progress_lines = replace_progress_lines; self.pending_changes = true; } fn render_pending_lines(&mut self, terminal_width: usize) -> Result<Vec<Change>> { if !self.pending_changes { return Ok(Vec::new()); } let line_count = self.new_output_lines.len() + self.error_lines.len() + self.progress_lines.len(); let mut changes = Vec::with_capacity(line_count * 2 + 2); if self.erase_row_count > 0 { let dy = -(self.erase_row_count as isize); changes.push(Change::CursorPosition { x: Position::Relative(0), y: Position::Relative(dy), }); changes.push(Change::ClearToEndOfScreen(Default::default())); } let mut render = |lines| -> Result<_> { let mut row_count = 0; for line in lines { let line = Line::new(0, line); let height = line.height(terminal_width, WrappingMode::GraphemeBoundary); for row in 0..height { line.render_wrapped( &mut changes, row, terminal_width, WrappingMode::GraphemeBoundary, None, )?; changes.push(Change::CursorPosition { x: Position::Absolute(0), y: Position::Relative(1), }); } row_count += height; } Ok(row_count) }; let new_output_row_count = render(self.new_output_lines.iter())?; let error_row_count = render(self.error_lines.iter())?; let progress_row_count = render(self.progress_lines.iter())?; self.past_output_row_count += new_output_row_count; self.new_output_lines.clear(); self.erase_row_count = error_row_count + progress_row_count; self.pending_changes = false; Ok(changes) } fn height(&self, terminal_width: usize) -> usize { let mut row_count = self.past_output_row_count; for line in self .new_output_lines .iter() .chain(self.error_lines.iter()) .chain(self.progress_lines.iter()) { let line = Line::new(0, line); row_count += line.height(terminal_width, WrappingMode::GraphemeBoundary); } row_count } }
use crate::config::{InterfaceMode, WrappingMode}; use crate::event::{Event, EventStream}; use crate::file::File; use crate::line::Line; use crate::progress::Progress; use anyhow::Result; use bit_set::BitSet; use std::time::{Duration, Instant}; use termwiz::input::InputEvent; use termwiz::surface::change::Change; use termwiz::surface::Position; use termwiz::terminal::Terminal; use vec_map::VecMap; #[derive(Debug)] pub(crate) enum Outcome { RenderIncomplete, RenderNothing, RenderComplete, Interrupted, } pub(crate) fn direct<T: Terminal>( term: &mut T, output_files: &[File], error_files: &[File], progress: Option<&Progress>, events: &mut EventStream, mode: InterfaceMode, ) -> Result<Outcome> { if mode == InterfaceMode::FullScreen { return Ok(Outcome::RenderNothing); } let delayed_deadline = match mode { InterfaceMode::Delayed(duration) => Some(Instant::now() + duration), _ => None, }; let mut loading = BitSet::with_capacity(output_files.len() + error_files.len()); for file in output_files.iter().chain(error_files.iter()) { loading.insert(file.index()); } let mut last_read = VecMap::new(); let mut collect_unread = |files: &[File], max_lines: usize| -> Vec<Vec<u8>> { let mut result = Vec::new(); for file in files.iter() { let index = file.index(); let mut lines = file.lines(); let last = last_read.get(index).cloned().unwrap_or(0); file.set_needed_lines(last + max_lines); if lines > 0 && !file.loaded() && file .with_line(lines - 1, |l| !l.ends_with(b"\n")) .unwrap_or(true) { lines -= 1; } if lines >= last { let lines = (last + max_lines).min(lines); result.reserve(lines - last); for i in last..lines { file.with_line(i, |l| result.push(l.to_vec())); } last_read.insert(index, lines); } } result }; let read_progress_lines = || -> Vec<Vec<u8>> { let line_count = progress.map(|p| p.lines()).unwrap_or(0); (0..line_count) .filter_map(|i| progress.and_then(|p| p.with_line(i, |l| l.to_vec()))) .collect::<Vec<_>>() }; let mut state = StreamingLines::default(); let delayed = delayed_deadline.is_some(); let has_one_screen_limit = match mode { InterfaceMode::Direct => false, _ => true, }; let mut render = |term: &mut T, h: usize, w: usize| -> Result<Option<Outcome>> { let append_output_lines = collect_unread(output_files, h + 2); let append_error_lines = collect_unread(error_files, h + 2); let progress_lines = read_progress_lines(); state.add_lines(append_output_lines, append_error_lines, progress_lines); if delayed { if has_one_screen_limit && state.height(w) >= h { return Ok(Some(Outcome::RenderNothing)); } } else { if has_one_screen_limit && state.height(w) >= h { return Ok(Some(Outcome::RenderIncomplete)); } let changes = state.render_pending_lines(w)?; term.render(&changes)?; } Ok(None) }; let mut size = term.get_screen_size()?; let mut loaded = BitSet::with_capacity(loading.capacity()); let mut remaining = output_files.len() + error_files.len(); while remaining > 0 { match events.get(term, Some(Duration::from_millis(10)))? { Some(Event::Loaded(i)) => { if loading.contains(i) && loaded.insert(i) { remaining -= 1; } } Some(Event::Input(InputEvent::Resized { .. })) => { size = term.get_screen_size()?; } Some(Event::Input(InputEvent::Key(key))) => { use termwiz::input::{KeyCode::Char, Modifiers}; match (key.modifiers, key.key) { (Modifiers::NONE, Char('q')) | (Modifiers::CTRL, Char('C')) => { return Ok(Outcome::Interrupted); } (Modifiers::NONE, Char('f')) | (Modifiers::NONE, Char(' ')) => { let outcome = if delayed { Outcome::RenderNothing } else { Outcome::RenderIncomplete }; return Ok(outcom
#[derive(Default)] struct StreamingLines { past_output_row_count: usize, new_output_lines: Vec<Vec<u8>>, error_lines: Vec<Vec<u8>>, progress_lines: Vec<Vec<u8>>, erase_row_count: usize, pending_changes: bool, } impl StreamingLines { fn add_lines( &mut self, mut append_output_lines: Vec<Vec<u8>>, mut append_error_lines: Vec<Vec<u8>>, replace_progress_lines: Vec<Vec<u8>>, ) { if append_output_lines.is_empty() && append_error_lines.is_empty() && replace_progress_lines == self.progress_lines { return; } self.new_output_lines.append(&mut append_output_lines); self.error_lines.append(&mut append_error_lines); self.progress_lines = replace_progress_lines; self.pending_changes = true; } fn render_pending_lines(&mut self, terminal_width: usize) -> Result<Vec<Change>> { if !self.pending_changes { return Ok(Vec::new()); } let line_count = self.new_output_lines.len() + self.error_lines.len() + self.progress_lines.len(); let mut changes = Vec::with_capacity(line_count * 2 + 2); if self.erase_row_count > 0 { let dy = -(self.erase_row_count as isize); changes.push(Change::CursorPosition { x: Position::Relative(0), y: Position::Relative(dy), }); changes.push(Change::ClearToEndOfScreen(Default::default())); } let mut render = |lines| -> Result<_> { let mut row_count = 0; for line in lines { let line = Line::new(0, line); let height = line.height(terminal_width, WrappingMode::GraphemeBoundary); for row in 0..height { line.render_wrapped( &mut changes, row, terminal_width, WrappingMode::GraphemeBoundary, None, )?; changes.push(Change::CursorPosition { x: Position::Absolute(0), y: Position::Relative(1), }); } row_count += height; } Ok(row_count) }; let new_output_row_count = render(self.new_output_lines.iter())?; let error_row_count = render(self.error_lines.iter())?; let progress_row_count = render(self.progress_lines.iter())?; self.past_output_row_count += new_output_row_count; self.new_output_lines.clear(); self.erase_row_count = error_row_count + progress_row_count; self.pending_changes = false; Ok(changes) } fn height(&self, terminal_width: usize) -> usize { let mut row_count = self.past_output_row_count; for line in self .new_output_lines .iter() .chain(self.error_lines.iter()) .chain(self.progress_lines.iter()) { let line = Line::new(0, line); row_count += line.height(terminal_width, WrappingMode::GraphemeBoundary); } row_count } }
e); } _ => (), } } _ => (), } if let Some(deadline) = delayed_deadline { if deadline <= Instant::now() { return Ok(Outcome::RenderNothing); } } if let Some(outcome) = render(term, size.rows, size.cols)? { return Ok(outcome); } } if delayed { term.render(&state.render_pending_lines(size.cols)?)?; } Ok(Outcome::RenderComplete) }
function_block-function_prefixed
[ { "content": "/// Determine the rendering width for a character.\n\nfn render_width(c: char) -> usize {\n\n if c < ' ' || c == '\\x7F' {\n\n // Render as <XX>\n\n 4\n\n } else if let Some(w) = c.width() {\n\n // Render as the character itself\n\n w\n\n } else {\n\n //...
Rust
automerge-backend/src/backend.rs
gterzian/automerge-rs
a81a37dfb4eef71dbdf5016cd65289b652f19c38
use crate::actor_map::ActorMap; use crate::change::encode_document; use crate::error::AutomergeError; use crate::internal::ObjectId; use crate::op_handle::OpHandle; use crate::op_set::OpSet; use crate::pending_diff::PendingDiff; use crate::Change; use automerge_protocol as amp; use core::cmp::max; use std::collections::{HashMap, HashSet}; #[derive(Debug, PartialEq, Clone)] pub struct Backend { queue: Vec<Change>, op_set: OpSet, states: HashMap<amp::ActorId, Vec<Change>>, actors: ActorMap, hashes: HashMap<amp::ChangeHash, Change>, history: Vec<amp::ChangeHash>, } impl Backend { pub fn init() -> Backend { let op_set = OpSet::init(); Backend { op_set, queue: Vec::new(), actors: ActorMap::new(), states: HashMap::new(), history: Vec::new(), hashes: HashMap::new(), } } fn make_patch( &self, diffs: Option<amp::Diff>, actor_seq: Option<(amp::ActorId, u64)>, ) -> Result<amp::Patch, AutomergeError> { let mut deps: Vec<_> = if let Some((ref actor, ref seq)) = actor_seq { let last_hash = self.get_hash(actor, *seq)?; self.op_set .deps .iter() .cloned() .filter(|dep| dep != &last_hash) .collect() } else { self.op_set.deps.iter().cloned().collect() }; deps.sort_unstable(); Ok(amp::Patch { diffs, deps, max_op: self.op_set.max_op, clock: self .states .iter() .map(|(k, v)| (k.clone(), v.len() as u64)) .collect(), actor: actor_seq.clone().map(|(actor, _)| actor), seq: actor_seq.map(|(_, seq)| seq), }) } pub fn load_changes(&mut self, changes: Vec<Change>) -> Result<(), AutomergeError> { self.apply(changes, None)?; Ok(()) } pub fn apply_changes( &mut self, changes: Vec<Change>, ) -> Result<amp::Patch, AutomergeError> { self.apply(changes, None) } pub fn get_heads(&self) -> Vec<amp::ChangeHash> { self.op_set.heads() } fn apply( &mut self, changes: Vec<Change>, actor: Option<(amp::ActorId, u64)>, ) -> Result<amp::Patch, AutomergeError> { let mut pending_diffs = HashMap::new(); for change in changes.into_iter() { self.add_change(change, actor.is_some(), &mut pending_diffs)?; } let op_set = &mut self.op_set; let diffs = op_set.finalize_diffs(pending_diffs, &self.actors)?; self.make_patch(diffs, actor) } fn get_hash(&self, actor: &amp::ActorId, seq: u64) -> Result<amp::ChangeHash, AutomergeError> { self.states .get(actor) .and_then(|v| v.get(seq as usize - 1)) .map(|c| c.hash) .ok_or(AutomergeError::InvalidSeq(seq)) } pub fn apply_local_change( &mut self, mut change: amp::UncompressedChange, ) -> Result<(amp::Patch, Change), AutomergeError> { self.check_for_duplicate(&change)?; let actor_seq = (change.actor_id.clone(), change.seq); if change.seq > 1 { let last_hash = self.get_hash(&change.actor_id, change.seq - 1)?; if !change.deps.contains(&last_hash) { change.deps.push(last_hash) } } let bin_change: Change = change.into(); let patch: amp::Patch = self.apply(vec![bin_change.clone()], Some(actor_seq))?; Ok((patch, bin_change)) } fn check_for_duplicate(&self, change: &amp::UncompressedChange) -> Result<(), AutomergeError> { if self .states .get(&change.actor_id) .map(|v| v.len() as u64) .unwrap_or(0) >= change.seq { return Err(AutomergeError::DuplicateChange(format!( "Change request has already been applied {}:{}", change.actor_id.to_hex_string(), change.seq ))); } Ok(()) } fn add_change( &mut self, change: Change, local: bool, diffs: &mut HashMap<ObjectId, Vec<PendingDiff>>, ) -> Result<(), AutomergeError> { if local { self.apply_change(change, diffs) } else { self.queue.push(change); self.apply_queued_ops(diffs) } } fn apply_queued_ops( &mut self, diffs: &mut HashMap<ObjectId, Vec<PendingDiff>>, ) -> Result<(), AutomergeError> { while let Some(next_change) = self.pop_next_causally_ready_change() { self.apply_change(next_change, diffs)?; } Ok(()) } fn apply_change( &mut self, change: Change, diffs: &mut HashMap<ObjectId, Vec<PendingDiff>>, ) -> Result<(), AutomergeError> { if self.hashes.contains_key(&change.hash) { return Ok(()); } self.update_history(&change); let op_set = &mut self.op_set; let start_op = change.start_op; op_set.update_deps(&change); let ops = OpHandle::extract(change, &mut self.actors); op_set.max_op = max(op_set.max_op, start_op + (ops.len() as u64) - 1); op_set.apply_ops(ops, diffs, &mut self.actors)?; Ok(()) } fn update_history(&mut self, change: &Change) { self.states .entry(change.actor_id().clone()) .or_default() .push(change.clone()); self.history.push(change.hash); self.hashes.insert(change.hash, change.clone()); } fn pop_next_causally_ready_change(&mut self) -> Option<Change> { let mut index = 0; while index < self.queue.len() { let change = self.queue.get(index).unwrap(); if change.deps.iter().all(|d| self.hashes.contains_key(d)) { return Some(self.queue.remove(index)); } index += 1 } None } pub fn get_patch(&self) -> Result<amp::Patch, AutomergeError> { let diffs = self .op_set .construct_object(&ObjectId::Root, &self.actors)?; self.make_patch(Some(diffs), None) } pub fn get_changes_for_actor_id( &self, actor_id: &amp::ActorId, ) -> Result<Vec<&Change>, AutomergeError> { Ok(self .states .get(actor_id) .map(|vec| vec.iter().collect()) .unwrap_or_default()) } pub fn get_changes(&self, have_deps: &[amp::ChangeHash]) -> Vec<&Change> { let mut stack = have_deps.to_owned(); let mut has_seen = HashSet::new(); while let Some(hash) = stack.pop() { if let Some(change) = self.hashes.get(&hash) { stack.extend(change.deps.clone()); } has_seen.insert(hash); } self.history .iter() .filter(|hash| !has_seen.contains(hash)) .filter_map(|hash| self.hashes.get(hash)) .collect() } pub fn save(&self) -> Result<Vec<u8>, AutomergeError> { let changes: Vec<amp::UncompressedChange> = self .history .iter() .filter_map(|hash| self.hashes.get(&hash)) .map(|r| r.into()) .collect(); encode_document(changes) } pub fn load(data: Vec<u8>) -> Result<Self, AutomergeError> { let changes = Change::load_document(&data)?; let mut backend = Self::init(); backend.load_changes(changes)?; Ok(backend) } pub fn get_missing_deps(&self) -> Vec<amp::ChangeHash> { let in_queue: Vec<_> = self.queue.iter().map(|change| &change.hash).collect(); self.queue .iter() .flat_map(|change| change.deps.clone()) .filter(|h| !in_queue.contains(&h)) .collect() } }
use crate::actor_map::ActorMap; use crate::change::encode_document; use crate::error::AutomergeError; use crate::internal::ObjectId; use crate::op_handle::OpHandle; use crate::op_set::OpSet; use crate::pending_diff::PendingDiff; use crate::Change; use automerge_protocol as amp; use core::cmp::max; use std::collections::{HashMap, HashSet}; #[derive(Debug, PartialEq, Clone)] pub struct Backend { queue: Vec<Change>, op_set: OpSet, states: HashMap<amp::ActorId, Vec<Change>>, actors: ActorMap, hashes: HashMap<amp::ChangeHash, Change>, history: Vec<amp::ChangeHash>, } impl Backend { pub fn init() -> Backend { let op_set = OpSet::init(); Backend { op_set, queue: Vec::new(), actors: ActorMap::new(), states: HashMap::new(), history: Vec::new(), hashes: HashMap::new(), } } fn make_patch( &self, diffs: Option<amp::Diff>, actor_seq: Option<(amp::ActorId, u64)>, ) -> Result<amp::Patch, AutomergeError> { let mut deps: Vec<_> = if let Some((ref actor, ref seq)) = actor_seq { let last_hash = self.get_hash(actor, *seq)?; self.op_set .deps .iter() .cloned() .filter(|
pub fn load_changes(&mut self, changes: Vec<Change>) -> Result<(), AutomergeError> { self.apply(changes, None)?; Ok(()) } pub fn apply_changes( &mut self, changes: Vec<Change>, ) -> Result<amp::Patch, AutomergeError> { self.apply(changes, None) } pub fn get_heads(&self) -> Vec<amp::ChangeHash> { self.op_set.heads() } fn apply( &mut self, changes: Vec<Change>, actor: Option<(amp::ActorId, u64)>, ) -> Result<amp::Patch, AutomergeError> { let mut pending_diffs = HashMap::new(); for change in changes.into_iter() { self.add_change(change, actor.is_some(), &mut pending_diffs)?; } let op_set = &mut self.op_set; let diffs = op_set.finalize_diffs(pending_diffs, &self.actors)?; self.make_patch(diffs, actor) } fn get_hash(&self, actor: &amp::ActorId, seq: u64) -> Result<amp::ChangeHash, AutomergeError> { self.states .get(actor) .and_then(|v| v.get(seq as usize - 1)) .map(|c| c.hash) .ok_or(AutomergeError::InvalidSeq(seq)) } pub fn apply_local_change( &mut self, mut change: amp::UncompressedChange, ) -> Result<(amp::Patch, Change), AutomergeError> { self.check_for_duplicate(&change)?; let actor_seq = (change.actor_id.clone(), change.seq); if change.seq > 1 { let last_hash = self.get_hash(&change.actor_id, change.seq - 1)?; if !change.deps.contains(&last_hash) { change.deps.push(last_hash) } } let bin_change: Change = change.into(); let patch: amp::Patch = self.apply(vec![bin_change.clone()], Some(actor_seq))?; Ok((patch, bin_change)) } fn check_for_duplicate(&self, change: &amp::UncompressedChange) -> Result<(), AutomergeError> { if self .states .get(&change.actor_id) .map(|v| v.len() as u64) .unwrap_or(0) >= change.seq { return Err(AutomergeError::DuplicateChange(format!( "Change request has already been applied {}:{}", change.actor_id.to_hex_string(), change.seq ))); } Ok(()) } fn add_change( &mut self, change: Change, local: bool, diffs: &mut HashMap<ObjectId, Vec<PendingDiff>>, ) -> Result<(), AutomergeError> { if local { self.apply_change(change, diffs) } else { self.queue.push(change); self.apply_queued_ops(diffs) } } fn apply_queued_ops( &mut self, diffs: &mut HashMap<ObjectId, Vec<PendingDiff>>, ) -> Result<(), AutomergeError> { while let Some(next_change) = self.pop_next_causally_ready_change() { self.apply_change(next_change, diffs)?; } Ok(()) } fn apply_change( &mut self, change: Change, diffs: &mut HashMap<ObjectId, Vec<PendingDiff>>, ) -> Result<(), AutomergeError> { if self.hashes.contains_key(&change.hash) { return Ok(()); } self.update_history(&change); let op_set = &mut self.op_set; let start_op = change.start_op; op_set.update_deps(&change); let ops = OpHandle::extract(change, &mut self.actors); op_set.max_op = max(op_set.max_op, start_op + (ops.len() as u64) - 1); op_set.apply_ops(ops, diffs, &mut self.actors)?; Ok(()) } fn update_history(&mut self, change: &Change) { self.states .entry(change.actor_id().clone()) .or_default() .push(change.clone()); self.history.push(change.hash); self.hashes.insert(change.hash, change.clone()); } fn pop_next_causally_ready_change(&mut self) -> Option<Change> { let mut index = 0; while index < self.queue.len() { let change = self.queue.get(index).unwrap(); if change.deps.iter().all(|d| self.hashes.contains_key(d)) { return Some(self.queue.remove(index)); } index += 1 } None } pub fn get_patch(&self) -> Result<amp::Patch, AutomergeError> { let diffs = self .op_set .construct_object(&ObjectId::Root, &self.actors)?; self.make_patch(Some(diffs), None) } pub fn get_changes_for_actor_id( &self, actor_id: &amp::ActorId, ) -> Result<Vec<&Change>, AutomergeError> { Ok(self .states .get(actor_id) .map(|vec| vec.iter().collect()) .unwrap_or_default()) } pub fn get_changes(&self, have_deps: &[amp::ChangeHash]) -> Vec<&Change> { let mut stack = have_deps.to_owned(); let mut has_seen = HashSet::new(); while let Some(hash) = stack.pop() { if let Some(change) = self.hashes.get(&hash) { stack.extend(change.deps.clone()); } has_seen.insert(hash); } self.history .iter() .filter(|hash| !has_seen.contains(hash)) .filter_map(|hash| self.hashes.get(hash)) .collect() } pub fn save(&self) -> Result<Vec<u8>, AutomergeError> { let changes: Vec<amp::UncompressedChange> = self .history .iter() .filter_map(|hash| self.hashes.get(&hash)) .map(|r| r.into()) .collect(); encode_document(changes) } pub fn load(data: Vec<u8>) -> Result<Self, AutomergeError> { let changes = Change::load_document(&data)?; let mut backend = Self::init(); backend.load_changes(changes)?; Ok(backend) } pub fn get_missing_deps(&self) -> Vec<amp::ChangeHash> { let in_queue: Vec<_> = self.queue.iter().map(|change| &change.hash).collect(); self.queue .iter() .flat_map(|change| change.deps.clone()) .filter(|h| !in_queue.contains(&h)) .collect() } }
dep| dep != &last_hash) .collect() } else { self.op_set.deps.iter().cloned().collect() }; deps.sort_unstable(); Ok(amp::Patch { diffs, deps, max_op: self.op_set.max_op, clock: self .states .iter() .map(|(k, v)| (k.clone(), v.len() as u64)) .collect(), actor: actor_seq.clone().map(|(actor, _)| actor), seq: actor_seq.map(|(_, seq)| seq), }) }
function_block-function_prefixed
[ { "content": "#[wasm_bindgen(js_name = initSyncState)]\n\npub fn init_sync_state() -> SyncState {\n\n SyncState(am::sync::State::new())\n\n}\n\n\n\n// this is needed to be compatible with the automerge-js api\n", "file_path": "rust/automerge-wasm/src/lib.rs", "rank": 0, "score": 207346.0183412675...
Rust
src/options.rs
Mange/graceful-shutdown
c99fb299c07611c9c57526f9be59080500094b39
extern crate structopt; extern crate termion; extern crate users; use matcher::MatchMode; use signal::Signal; use std::time::Duration; use structopt::clap::Shell; #[derive(Debug, Clone, Copy)] pub enum OutputMode { Normal, Verbose, Quiet, } #[derive(Debug, Clone, Copy)] enum ColorMode { Auto, Always, Never, } #[derive(StructOpt, Debug)] #[structopt(raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] pub struct CliOptions { #[structopt(short = "w", long = "wait-time", default_value = "5.0", value_name = "SECONDS")] wait_time: f64, #[structopt(long = "no-kill")] no_kill: bool, #[structopt( short = "s", long = "terminate-signal", default_value = "term", value_name = "SIGNAL", parse(try_from_str = "parse_signal") )] terminate_signal: Signal, #[structopt( long = "kill-signal", default_value = "kill", value_name = "SIGNAL", parse(try_from_str = "parse_signal") )] kill_signal: Signal, #[structopt(short = "W", long = "whole-command", visible_alias = "whole")] match_whole: bool, #[structopt(short = "u", long = "user", value_name = "USER", overrides_with = "mine")] user: Option<String>, #[structopt(short = "m", long = "mine", overrides_with = "user")] mine: bool, #[structopt(short = "n", long = "dry-run")] dry_run: bool, #[structopt(short = "v", long = "verbose", overrides_with = "quiet")] verbose: bool, #[structopt(short = "q", long = "quiet", overrides_with = "verbose")] quiet: bool, #[structopt( long = "color", default_value = "auto", raw(possible_values = "&ColorMode::variants()") )] color_mode: ColorMode, #[structopt(long = "list-signals")] pub list_signals: bool, #[structopt( long = "generate-completions", value_name = "SHELL", raw(possible_values = "&Shell::variants()") )] pub generate_completions: Option<Shell>, } #[derive(Debug)] pub struct Options { pub dry_run: bool, pub kill: bool, pub kill_signal: Signal, pub match_mode: MatchMode, pub output_mode: OutputMode, pub terminate_signal: Signal, pub colors: Colors, pub user_mode: UserMode, pub wait_time: Option<Duration>, } #[derive(Debug)] pub enum UserMode { Everybody, OnlyMe, Only(String), } #[derive(Debug)] pub struct Colors { enabled: bool, } impl From<CliOptions> for Options { fn from(cli_options: CliOptions) -> Options { let wait_time = if cli_options.wait_time > 0.0 { Some(duration_from_secs_float(cli_options.wait_time)) } else { None }; let user_mode = match (cli_options.user, cli_options.mine) { (Some(name), false) => UserMode::Only(name), (None, true) => UserMode::OnlyMe, (None, false) => UserMode::Everybody, (Some(_), true) => unreachable!("Should not happen because of overrides_with"), }; let match_mode = if cli_options.match_whole { MatchMode::Commandline } else { MatchMode::Basename }; let output_mode = match (cli_options.dry_run, cli_options.verbose, cli_options.quiet) { (true, _, _) => OutputMode::Verbose, (false, false, false) => OutputMode::Normal, (false, true, false) => OutputMode::Verbose, (false, false, true) => OutputMode::Quiet, (false, true, true) => unreachable!("Should not happen due to overrides_with option"), }; let use_color = match cli_options.color_mode { ColorMode::Never => false, ColorMode::Always => true, ColorMode::Auto => termion::is_tty(&::std::io::stdout()), }; Options { dry_run: cli_options.dry_run, kill: !cli_options.no_kill, kill_signal: cli_options.kill_signal, match_mode, output_mode, terminate_signal: cli_options.terminate_signal, colors: Colors { enabled: use_color }, user_mode, wait_time, } } } impl OutputMode { pub fn show_normal(self) -> bool { match self { OutputMode::Verbose | OutputMode::Normal => true, OutputMode::Quiet => false, } } pub fn show_verbose(self) -> bool { match self { OutputMode::Verbose => true, OutputMode::Normal | OutputMode::Quiet => false, } } } impl ColorMode { fn variants() -> [&'static str; 3] { ["auto", "always", "never"] } } impl ::std::str::FromStr for ColorMode { type Err = &'static str; fn from_str(string: &str) -> Result<ColorMode, Self::Err> { match string { "auto" => Ok(ColorMode::Auto), "always" => Ok(ColorMode::Always), "never" => Ok(ColorMode::Never), _ => Err("Not a valid color mode"), } } } impl Colors { pub fn reset(&self) -> String { if self.enabled { format!( "{}{}", termion::color::Fg(termion::color::Reset), termion::style::Reset, ) } else { String::new() } } pub fn red(&self) -> String { if self.enabled { termion::color::Fg(termion::color::Red).to_string() } else { String::new() } } pub fn yellow(&self) -> String { if self.enabled { termion::color::Fg(termion::color::Yellow).to_string() } else { String::new() } } pub fn green(&self) -> String { if self.enabled { termion::color::Fg(termion::color::Green).to_string() } else { String::new() } } pub fn faded(&self) -> String { if self.enabled { termion::style::Faint.to_string() } else { String::new() } } } fn parse_signal(sig: &str) -> Result<Signal, String> { sig.parse() .map_err(|_| format!("Failed to parse \"{}\" as a signal name.", sig)) } fn duration_from_secs_float(float: f64) -> Duration { let whole_seconds = float.floor(); let sec_frac = float - whole_seconds; let nanos = (sec_frac * 1e9).round(); Duration::new(whole_seconds as u64, nanos as u32) }
extern crate structopt; extern crate termion; extern crate users; use matcher::MatchMode; use signal::Signal; use std::time::Duration; use structopt::clap::Shell; #[derive(Debug, Clone, Copy)] pub enum OutputMode { Normal, Verbose, Quiet, } #[derive(Debug, Clone, Copy)] enum ColorMode { Auto, Always, Never, } #[derive(StructOpt, Debug)] #[structopt(raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] pub struct CliOptions { #[structopt(short = "w", long = "wait-time", default_value = "5.0", value_name = "SECONDS")] wait_time: f64, #[structopt(long = "no-kill")] no_kill: bool, #[structopt( short = "s", long = "terminate-signal", default_value = "term", value_name = "SIGNAL", parse(try_from_str = "parse_signal") )] terminate_signal: Signal, #[structopt( long = "kill-signal", default_value = "kill", value_name = "SIGNAL", parse(try_from_str = "parse_signal") )] kill_signal: Signal, #[structopt(short = "W", long = "whole-command", visible_alias = "whole")] match_whole: bool, #[structopt(short = "u", long = "user", value_name = "USER", overrides_with = "mine")] user: Option<String>, #[structopt(short = "m", long = "mine", overrides_with = "user")] mine: bool, #[structopt(short = "n", long = "dry-run")] dry_run: bool, #[structopt(short = "v", long = "verbose", overrides_with = "quiet")] verbose: bool, #[structopt(short = "q", long = "quiet", overrides_with = "verbose")] quiet: bool, #[structopt( long = "color", default_value = "auto", raw(possible_values = "&ColorMode::variants()") )] color_mode: ColorMode, #[structopt(long = "list-signals")] pub list_signals: bool, #[structopt( long = "generate-completions", value_name = "SHELL", raw(possible_values = "&Shell::variants()") )] pub generate_completions: Option<Shell>, } #[derive(Debug)] pub struct Options { pub dry_run: bool, pub kill: bool, pub kill_signal: Signal, pub match_mode: MatchMode, pub output_mode: OutputMode, pub terminate_signal: Signal, pub colors: Colors, pub user_mode: UserMode, pub wait_time: Option<Duration>, } #[derive(Debug)] pub enum UserMode { Everybody, OnlyMe, Only(String), } #[derive(Debug)] pub struct Colors { enabled: bool, } impl From<CliOptions> for Options {
} impl OutputMode { pub fn show_normal(self) -> bool { match self { OutputMode::Verbose | OutputMode::Normal => true, OutputMode::Quiet => false, } } pub fn show_verbose(self) -> bool { match self { OutputMode::Verbose => true, OutputMode::Normal | OutputMode::Quiet => false, } } } impl ColorMode { fn variants() -> [&'static str; 3] { ["auto", "always", "never"] } } impl ::std::str::FromStr for ColorMode { type Err = &'static str; fn from_str(string: &str) -> Result<ColorMode, Self::Err> { match string { "auto" => Ok(ColorMode::Auto), "always" => Ok(ColorMode::Always), "never" => Ok(ColorMode::Never), _ => Err("Not a valid color mode"), } } } impl Colors { pub fn reset(&self) -> String { if self.enabled { format!( "{}{}", termion::color::Fg(termion::color::Reset), termion::style::Reset, ) } else { String::new() } } pub fn red(&self) -> String { if self.enabled { termion::color::Fg(termion::color::Red).to_string() } else { String::new() } } pub fn yellow(&self) -> String { if self.enabled { termion::color::Fg(termion::color::Yellow).to_string() } else { String::new() } } pub fn green(&self) -> String { if self.enabled { termion::color::Fg(termion::color::Green).to_string() } else { String::new() } } pub fn faded(&self) -> String { if self.enabled { termion::style::Faint.to_string() } else { String::new() } } } fn parse_signal(sig: &str) -> Result<Signal, String> { sig.parse() .map_err(|_| format!("Failed to parse \"{}\" as a signal name.", sig)) } fn duration_from_secs_float(float: f64) -> Duration { let whole_seconds = float.floor(); let sec_frac = float - whole_seconds; let nanos = (sec_frac * 1e9).round(); Duration::new(whole_seconds as u64, nanos as u32) }
fn from(cli_options: CliOptions) -> Options { let wait_time = if cli_options.wait_time > 0.0 { Some(duration_from_secs_float(cli_options.wait_time)) } else { None }; let user_mode = match (cli_options.user, cli_options.mine) { (Some(name), false) => UserMode::Only(name), (None, true) => UserMode::OnlyMe, (None, false) => UserMode::Everybody, (Some(_), true) => unreachable!("Should not happen because of overrides_with"), }; let match_mode = if cli_options.match_whole { MatchMode::Commandline } else { MatchMode::Basename }; let output_mode = match (cli_options.dry_run, cli_options.verbose, cli_options.quiet) { (true, _, _) => OutputMode::Verbose, (false, false, false) => OutputMode::Normal, (false, true, false) => OutputMode::Verbose, (false, false, true) => OutputMode::Quiet, (false, true, true) => unreachable!("Should not happen due to overrides_with option"), }; let use_color = match cli_options.color_mode { ColorMode::Never => false, ColorMode::Always => true, ColorMode::Auto => termion::is_tty(&::std::io::stdout()), }; Options { dry_run: cli_options.dry_run, kill: !cli_options.no_kill, kill_signal: cli_options.kill_signal, match_mode, output_mode, terminate_signal: cli_options.terminate_signal, colors: Colors { enabled: use_color }, user_mode, wait_time, } }
function_block-full_function
[ { "content": "#[must_use]\n\nfn send_with_error_handling(signal: Signal, options: &Options, process: &Process) -> bool {\n\n match process.send(signal) {\n\n Ok(_) => true,\n\n // Process quit before we had time to signal it? That should be fine. The next steps will\n\n // verify that it...
Rust
src/structs/types/system_boot_information.rs
alesharik/smbios-lib
27dc2fa78afa2163763207165c31a900f72a02e1
use crate::{SMBiosStruct, UndefinedStruct}; use serde::{ser::SerializeStruct, Serialize, Serializer}; use core::{fmt, any}; pub struct SMBiosSystemBootInformation<'a> { parts: &'a UndefinedStruct, } impl<'a> SMBiosStruct<'a> for SMBiosSystemBootInformation<'a> { const STRUCT_TYPE: u8 = 32u8; fn new(parts: &'a UndefinedStruct) -> Self { Self { parts } } fn parts(&self) -> &'a UndefinedStruct { self.parts } } impl<'a> SMBiosSystemBootInformation<'a> { const BOOT_STATUS_OFFSET: usize = 0x0A; const BOOT_STATUS_MAX_SIZE: usize = 0x0A; pub fn boot_status_data(&self) -> Option<SystemBootStatusData<'_>> { let struct_length = self.parts.header.length() as usize; if struct_length < Self::BOOT_STATUS_OFFSET + 1 { return None; } let end_index: usize; if struct_length < Self::BOOT_STATUS_OFFSET + Self::BOOT_STATUS_MAX_SIZE { end_index = struct_length; } else { end_index = Self::BOOT_STATUS_OFFSET + Self::BOOT_STATUS_MAX_SIZE; } self.parts .get_field_data(Self::BOOT_STATUS_OFFSET, end_index) .map(|raw| SystemBootStatusData { raw }) } } impl fmt::Debug for SMBiosSystemBootInformation<'_> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct(any::type_name::<SMBiosSystemBootInformation<'_>>()) .field("header", &self.parts.header) .field("boot_status_data", &self.boot_status_data()) .finish() } } impl Serialize for SMBiosSystemBootInformation<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("SMBiosSystemBootInformation", 2)?; state.serialize_field("header", &self.parts.header)?; state.serialize_field("boot_status_data", &self.boot_status_data())?; state.end() } } pub struct SystemBootStatusData<'a> { pub raw: &'a [u8], } impl<'a> SystemBootStatusData<'a> { pub fn system_boot_status(&self) -> SystemBootStatus { debug_assert!(self.raw.len() > 0); match self.raw[0] { 0x00 => SystemBootStatus::NoErrors, 0x01 => SystemBootStatus::NoBootableMedia, 0x02 => SystemBootStatus::NormalOSFailedToLoad, 0x03 => SystemBootStatus::FirmwareDetectedFailure, 0x04 => SystemBootStatus::OSDetectedFailure, 0x05 => SystemBootStatus::UserRequestedBoot, 0x06 => SystemBootStatus::SystemSecurityViolation, 0x07 => SystemBootStatus::PreviouslyRequestedImage, 0x08 => SystemBootStatus::SystemWatchdogTimerExpired, _ => SystemBootStatus::None, } } } impl fmt::Debug for SystemBootStatusData<'_> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct(any::type_name::<SMBiosSystemBootInformation<'_>>()) .field("system_boot_status", &self.system_boot_status()) .finish() } } impl Serialize for SystemBootStatusData<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("SystemBootStatusData", 1)?; state.serialize_field("system_boot_status", &self.system_boot_status())?; state.end() } } #[derive(Serialize, Debug, PartialEq, Eq)] pub enum SystemBootStatus { NoErrors, NoBootableMedia, NormalOSFailedToLoad, FirmwareDetectedFailure, OSDetectedFailure, UserRequestedBoot, SystemSecurityViolation, PreviouslyRequestedImage, SystemWatchdogTimerExpired, None, } #[cfg(test)] mod tests { use super::*; #[test] fn unit_test() { let struct_type32 = vec![ 0x20, 0x14, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let parts = UndefinedStruct::new(&struct_type32); let test_struct = SMBiosSystemBootInformation::new(&parts); let boot_status_data = test_struct.boot_status_data().unwrap(); assert_eq!( boot_status_data.raw, &[0x00u8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] as &[u8] ); assert_eq!( boot_status_data.system_boot_status(), SystemBootStatus::NoErrors ); let struct_type32 = vec![ 0x20, 0x0C, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, ]; let parts = UndefinedStruct::new(&struct_type32); let test_struct = SMBiosSystemBootInformation::new(&parts); let boot_status_data = test_struct.boot_status_data().unwrap(); assert_eq!(boot_status_data.raw, &[0x02u8, 0x01] as &[u8]); assert_eq!( boot_status_data.system_boot_status(), SystemBootStatus::NormalOSFailedToLoad ); let struct_type32 = vec![ 0x20, 0x0F, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, ]; let parts = UndefinedStruct::new(&struct_type32); let test_struct = SMBiosSystemBootInformation::new(&parts); assert!(test_struct.boot_status_data().is_none()); } }
use crate::{SMBiosStruct, UndefinedStruct}; use serde::{ser::SerializeStruct, Serialize, Serializer}; use core::{fmt, any}; pub struct SMBiosSystemBootInformation<'a> { parts: &'a UndefinedStruct, } impl<'a> SMBiosStruct<'a> for SMBiosSystemBootInformation<'a> { const STRUCT_TYPE: u8 = 32u8; fn new(parts: &'a UndefinedStruct) -> Self { Self { parts } } fn parts(&self) -> &'a UndefinedStruct { self.parts } } impl<'a> SMBiosSystemBootInformation<'a> { const BOOT_STATUS_OFFSET: usize = 0x0A; const BOOT_STATUS_MAX_SIZE: usize = 0x0A; pub fn boot_status_data(&self) -> Option<SystemBootStatusData<'_>> { let struct_length = self.parts.header.length() as usize; if struct_length < Self::BOOT_STATUS_OFFSET + 1 { return None; } let end_index: usize; if struct_length < Self::BOOT_STATUS_OFFSET + Self::BOOT_STATUS_MAX_SIZE { end_index = struct_length; } else { end_index = Self::BOOT_STATUS_OFFSET + Self::BOOT_STATUS_MAX_SIZE; } self.parts .get_field_data(Self::BOOT_STATUS_OFFSET, end_index) .map(|raw| SystemBootStatusData { raw }) } } impl fmt::Debug for SMBiosSystemBootInformation<'_> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct(any::type_name::<SMBiosSystemBootInformation<'_>>()) .field("header", &self.parts.header) .field("boot_status_data", &self.boot_status_data()) .finish() } } impl Serialize for SMBiosSystemBootInformation<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("SMBiosSystemBootInformation", 2)?; state.serialize_field("header", &self.parts.header)?; state.serialize_field("boot_status_data", &self.boot_status_data())?; state.end() } } pub struct SystemBootStatusData<'a> { pub raw: &'a [u8], } impl<'a> SystemBootStatusData<'a> { pub fn system_boot_status(&self) -> SystemBootStatus { debug_assert!(self.raw.len() > 0); match self.raw[0] { 0x00 => SystemBootStatus::NoErrors, 0x01 => SystemBootStatus::NoBootableMedia, 0x02 => SystemBootStatus::NormalOSFailedToLoad, 0x03 => SystemBootStatus::FirmwareDetectedFailure, 0x04 => SystemBootStatus::OSDetectedFailure, 0x05 => SystemBootStatus::UserRequestedBoot, 0x06 => SystemBootStatus::SystemSecurityViolation, 0x07 => SystemBootStatus::PreviouslyRequestedImage, 0x08 => SystemBootStatus::SystemWatchdogTimerExpired, _ => SystemBootStatus::None, } } } impl fmt::Debug for SystemBootStatusData<'_> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct(any::type_name::<SMBiosSystemBootInformation<'_>>()) .field("system_boot_status", &self.system_boot_status()) .finish() } } impl Serialize for SystemBootStatusData<'_> {
} #[derive(Serialize, Debug, PartialEq, Eq)] pub enum SystemBootStatus { NoErrors, NoBootableMedia, NormalOSFailedToLoad, FirmwareDetectedFailure, OSDetectedFailure, UserRequestedBoot, SystemSecurityViolation, PreviouslyRequestedImage, SystemWatchdogTimerExpired, None, } #[cfg(test)] mod tests { use super::*; #[test] fn unit_test() { let struct_type32 = vec![ 0x20, 0x14, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let parts = UndefinedStruct::new(&struct_type32); let test_struct = SMBiosSystemBootInformation::new(&parts); let boot_status_data = test_struct.boot_status_data().unwrap(); assert_eq!( boot_status_data.raw, &[0x00u8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] as &[u8] ); assert_eq!( boot_status_data.system_boot_status(), SystemBootStatus::NoErrors ); let struct_type32 = vec![ 0x20, 0x0C, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, ]; let parts = UndefinedStruct::new(&struct_type32); let test_struct = SMBiosSystemBootInformation::new(&parts); let boot_status_data = test_struct.boot_status_data().unwrap(); assert_eq!(boot_status_data.raw, &[0x02u8, 0x01] as &[u8]); assert_eq!( boot_status_data.system_boot_status(), SystemBootStatus::NormalOSFailedToLoad ); let struct_type32 = vec![ 0x20, 0x0F, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, ]; let parts = UndefinedStruct::new(&struct_type32); let test_struct = SMBiosSystemBootInformation::new(&parts); assert!(test_struct.boot_status_data().is_none()); } }
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("SystemBootStatusData", 1)?; state.serialize_field("system_boot_status", &self.system_boot_status())?; state.end() }
function_block-full_function
[ { "content": "/// Returns smbios raw data\n\npub fn raw_smbios_from_device() -> Result<Vec<u8>, Error> {\n\n Ok(try_load_macos_table()?)\n\n}\n", "file_path": "src/macos/platform.rs", "rank": 0, "score": 173349.63818810516 }, { "content": "/// Returns smbios raw data\n\npub fn raw_smbios_...
Rust
dbcrossbarlib/src/drivers/postgres_shared/table.rs
faradayio/schemaconv
eeb808354af7d58f1782927eaa9e754d59544011
use itertools::Itertools; use std::{ collections::{HashMap, HashSet}, fmt, }; use super::{PgColumn, PgDataType, PgName, PgScalarDataType}; use crate::common::*; use crate::schema::Column; use crate::separator::Separator; #[derive(Debug)] pub(crate) enum CheckCatalog { Yes, No, } impl From<&IfExists> for CheckCatalog { fn from(if_exists: &IfExists) -> CheckCatalog { match if_exists { IfExists::Error | IfExists::Overwrite => CheckCatalog::No, IfExists::Append | IfExists::Upsert(_) => CheckCatalog::Yes, } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct PgCreateTable { pub(crate) name: PgName, pub(crate) columns: Vec<PgColumn>, pub(crate) if_not_exists: bool, pub(crate) temporary: bool, } impl PgCreateTable { pub(crate) fn from_name_and_columns( schema: &Schema, table_name: PgName, columns: &[Column], ) -> Result<PgCreateTable> { let pg_columns = columns .iter() .map(|c| PgColumn::from_column(schema, c)) .collect::<Result<Vec<PgColumn>>>()?; Ok(PgCreateTable { name: table_name, columns: pg_columns, if_not_exists: false, temporary: false, }) } pub(crate) fn to_table(&self) -> Result<Table> { let columns = self .columns .iter() .map(|c| c.to_column()) .collect::<Result<Vec<Column>>>()?; Ok(Table { name: self.name.unquoted(), columns, }) } pub(crate) fn aligned_with( &self, other_table: &PgCreateTable, ) -> Result<PgCreateTable> { let column_map = self .columns .iter() .map(|c| (&c.name[..], c)) .collect::<HashMap<_, _>>(); Ok(PgCreateTable { name: self.name.clone(), columns: other_table .columns .iter() .map(|c| { if let Some(&col) = column_map.get(&c.name[..]) { Ok(col.to_owned()) } else { Err(format_err!( "could not find column {} in destination table: {}", c.name, column_map.keys().join(", "), )) } }) .collect::<Result<Vec<_>>>()?, if_not_exists: self.if_not_exists, temporary: self.temporary, }) } pub(crate) fn named_type_names(&self) -> HashSet<&PgName> { let mut names = HashSet::new(); for col in &self.columns { let scalar_ty = match &col.data_type { PgDataType::Array { ty, .. } => ty, PgDataType::Scalar(ty) => ty, }; if let PgScalarDataType::Named(name) = scalar_ty { names.insert(name); } } names } pub(crate) fn write_export_sql( &self, f: &mut dyn Write, source_args: &SourceArguments<Verified>, ) -> Result<()> { write!(f, "COPY (")?; self.write_export_select_sql(f, source_args)?; write!(f, ") TO STDOUT WITH CSV HEADER")?; Ok(()) } pub(crate) fn write_export_select_sql( &self, f: &mut dyn Write, source_args: &SourceArguments<Verified>, ) -> Result<()> { write!(f, "SELECT ")?; if self.columns.is_empty() { return Err(format_err!("cannot export 0 columns")); } let mut sep = Separator::new(","); for col in &self.columns { write!(f, "{}", sep.display())?; col.write_export_select_expr(f)?; } write!(f, " FROM {}", &self.name.quoted())?; if let Some(where_clause) = source_args.where_clause() { write!(f, " WHERE ({})", where_clause)?; } Ok(()) } pub(crate) fn write_count_sql( &self, f: &mut dyn Write, source_args: &SourceArguments<Verified>, ) -> Result<()> { writeln!(f, "SELECT COUNT(*)")?; writeln!(f, " FROM {}", &self.name.quoted())?; if let Some(where_clause) = source_args.where_clause() { writeln!(f, " WHERE ({})", where_clause)?; } Ok(()) } } impl fmt::Display for PgCreateTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CREATE")?; if self.temporary { write!(f, " TEMPORARY")?; } write!(f, " TABLE")?; if self.if_not_exists { write!(f, " IF NOT EXISTS")?; } writeln!(f, " {} (", &self.name.quoted())?; for (idx, col) in self.columns.iter().enumerate() { write!(f, " {}", col)?; if idx + 1 == self.columns.len() { writeln!(f)?; } else { writeln!(f, ",")?; } } writeln!(f, ");")?; Ok(()) } }
use itertools::Itertools; use std::{ collections::{HashMap, HashSet}, fmt, }; use super::{PgColumn, PgDataType, PgName, PgScalarDataType}; use crate::common::*; use crate::schema::Column; use crate::separator::Separator; #[derive(Debug)] pub(crate) enum CheckCatalog { Yes, No, } impl From<&IfExists> for CheckCatalog { fn from(if_exists: &IfExists) -> CheckCatalog { match if_exists { IfExists::Error | IfExists::Overwrite => CheckCatalog::No, IfExists::Append | IfExists::Upsert(_) => CheckCatalog::Yes, } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct PgCreateTable { pub(crate) name: PgName, pub(crate) columns: Vec<PgColumn>, pub(crate) if_not_exists: bool, pub(crate) temporary: bool, } impl PgCreateTable { pub(crate) fn from_name_and_columns( schema: &Schema, table_name: PgName, columns: &[Column], ) -> Result<PgCreateTable> { let pg_columns = columns .iter() .map(|c| PgColumn::from_column(schema, c)) .collect::<Result<Vec<PgColumn>>>()?; Ok(PgCreateTable { name: table_name, columns: pg_columns, if_not_exists: false, temporary: false, }) } pub(crate) fn to_table(&self) -> Result<Table> { let columns = self .columns .iter() .map(|c| c.to_column()) .collect::<Result<Vec<Column>>>()?; Ok(Table { name: self.name.unquoted(), columns, }) }
pub(crate) fn named_type_names(&self) -> HashSet<&PgName> { let mut names = HashSet::new(); for col in &self.columns { let scalar_ty = match &col.data_type { PgDataType::Array { ty, .. } => ty, PgDataType::Scalar(ty) => ty, }; if let PgScalarDataType::Named(name) = scalar_ty { names.insert(name); } } names } pub(crate) fn write_export_sql( &self, f: &mut dyn Write, source_args: &SourceArguments<Verified>, ) -> Result<()> { write!(f, "COPY (")?; self.write_export_select_sql(f, source_args)?; write!(f, ") TO STDOUT WITH CSV HEADER")?; Ok(()) } pub(crate) fn write_export_select_sql( &self, f: &mut dyn Write, source_args: &SourceArguments<Verified>, ) -> Result<()> { write!(f, "SELECT ")?; if self.columns.is_empty() { return Err(format_err!("cannot export 0 columns")); } let mut sep = Separator::new(","); for col in &self.columns { write!(f, "{}", sep.display())?; col.write_export_select_expr(f)?; } write!(f, " FROM {}", &self.name.quoted())?; if let Some(where_clause) = source_args.where_clause() { write!(f, " WHERE ({})", where_clause)?; } Ok(()) } pub(crate) fn write_count_sql( &self, f: &mut dyn Write, source_args: &SourceArguments<Verified>, ) -> Result<()> { writeln!(f, "SELECT COUNT(*)")?; writeln!(f, " FROM {}", &self.name.quoted())?; if let Some(where_clause) = source_args.where_clause() { writeln!(f, " WHERE ({})", where_clause)?; } Ok(()) } } impl fmt::Display for PgCreateTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CREATE")?; if self.temporary { write!(f, " TEMPORARY")?; } write!(f, " TABLE")?; if self.if_not_exists { write!(f, " IF NOT EXISTS")?; } writeln!(f, " {} (", &self.name.quoted())?; for (idx, col) in self.columns.iter().enumerate() { write!(f, " {}", col)?; if idx + 1 == self.columns.len() { writeln!(f)?; } else { writeln!(f, ",")?; } } writeln!(f, ");")?; Ok(()) } }
pub(crate) fn aligned_with( &self, other_table: &PgCreateTable, ) -> Result<PgCreateTable> { let column_map = self .columns .iter() .map(|c| (&c.name[..], c)) .collect::<HashMap<_, _>>(); Ok(PgCreateTable { name: self.name.clone(), columns: other_table .columns .iter() .map(|c| { if let Some(&col) = column_map.get(&c.name[..]) { Ok(col.to_owned()) } else { Err(format_err!( "could not find column {} in destination table: {}", c.name, column_map.keys().join(", "), )) } }) .collect::<Result<Vec<_>>>()?, if_not_exists: self.if_not_exists, temporary: self.temporary, }) }
function_block-full_function
[ { "content": "/// Specify the the location of data or a schema.\n\npub trait Locator: fmt::Debug + fmt::Display + Send + Sync + 'static {\n\n /// Provide a mechanism for casting a `dyn Locator` back to the underlying,\n\n /// concrete locator type using Rust's `Any` type.\n\n ///\n\n /// See [this S...
Rust
src/apu/dmc.rs
zeta0134/rusticnes-core
de44cda41670c8902e96f9f5f7b624b6cf1d8ac1
use mmc::mapper::Mapper; use super::audio_channel::AudioChannelState; use super::ring_buffer::RingBuffer; pub struct DmcState { pub name: String, pub chip: String, pub debug_disable: bool, pub debug_buffer: Vec<i16>, pub output_buffer: RingBuffer, pub looping: bool, pub period_initial: u16, pub period_current: u16, pub output_level: u8, pub starting_address: u16, pub sample_length: u16, pub current_address: u16, pub sample_buffer: u8, pub shift_register: u8, pub sample_buffer_empty: bool, pub bits_remaining: u8, pub bytes_remaining: u16, pub silence_flag: bool, pub interrupt_enabled: bool, pub interrupt_flag: bool, pub rdy_line: bool, pub rdy_delay: u8, } impl DmcState { pub fn new(channel_name: &str, chip_name: &str) -> DmcState { return DmcState { name: String::from(channel_name), chip: String::from(chip_name), debug_disable: false, debug_buffer: vec!(0i16; 4096), output_buffer: RingBuffer::new(32768), looping: false, period_initial: 428, period_current: 0, output_level: 0, starting_address: 0, sample_length: 0, current_address: 0, sample_buffer: 0, shift_register: 0, sample_buffer_empty: true, bits_remaining: 8, bytes_remaining: 0, silence_flag: false, interrupt_enabled: true, interrupt_flag: false, rdy_line: false, rdy_delay: 0, } } pub fn debug_status(&self) -> String { return format!("Rate: {:3} - Divisor: {:3} - Start: {:04X} - Current: {:04X} - Length: {:4} - R.Bytes: {:4} - R.Bits: {:1}", self.period_initial, self.period_current, self.starting_address, self.current_address, self.sample_length, self.bytes_remaining, self.bits_remaining); } pub fn read_next_sample(&mut self, mapper: &mut dyn Mapper) { match mapper.read_cpu(0x8000 | (self.current_address & 0x7FFF)) { Some(byte) => self.sample_buffer = byte, None => self.sample_buffer = 0, } self.current_address = self.current_address.wrapping_add(1); self.bytes_remaining -= 1; if self.bytes_remaining == 0 { if self.looping { self.current_address = self.starting_address; self.bytes_remaining = self.sample_length; } else { if self.interrupt_enabled { self.interrupt_flag = true; } } } self.sample_buffer_empty = false; self.rdy_line = false; self.rdy_delay = 0; } pub fn begin_output_cycle(&mut self) { self.bits_remaining = 8; if self.sample_buffer_empty { self.silence_flag = true; } else { self.silence_flag = false; self.shift_register = self.sample_buffer; self.sample_buffer_empty = true; } } pub fn update_output_unit(&mut self) { if !(self.silence_flag) { let mut target_output = self.output_level; if (self.shift_register & 0b1) == 0 { if self.output_level >= 2 { target_output -= 2; } } else { if self.output_level <= 125 { target_output += 2; } } self.output_level = target_output; } self.shift_register = self.shift_register >> 1; self.bits_remaining -= 1; if self.bits_remaining == 0 { self.begin_output_cycle(); } } pub fn clock(&mut self, mapper: &mut dyn Mapper) { if self.period_current == 0 { self.period_current = self.period_initial - 1; self.update_output_unit(); } else { self.period_current -= 1; } if self.sample_buffer_empty && self.bytes_remaining > 0 { self.rdy_line = true; self.rdy_delay += 1; if self.rdy_delay > 2 { self.read_next_sample(mapper); } } else { self.rdy_line = false; self.rdy_delay = 0; } } pub fn output(&self) -> i16 { return self.output_level as i16; } } impl AudioChannelState for DmcState { fn name(&self) -> String { return self.name.clone(); } fn chip(&self) -> String { return self.chip.clone(); } fn sample_buffer(&self) -> &RingBuffer { return &self.output_buffer; } fn record_current_output(&mut self) { self.output_buffer.push(self.output()); } fn min_sample(&self) -> i16 { return 0; } fn max_sample(&self) -> i16 { return 127; } fn muted(&self) -> bool { return self.debug_disable; } fn mute(&mut self) { self.debug_disable = true; } fn unmute(&mut self) { self.debug_disable = false; } fn playing(&self) -> bool { return true; } fn amplitude(&self) -> f64 { let buffer = self.output_buffer.buffer(); let mut index = (self.output_buffer.index() - 256) % buffer.len(); let mut max = buffer[index]; let mut min = buffer[index]; for _i in 0 .. 256 { if buffer[index] > max {max = buffer[index];} if buffer[index] < min {min = buffer[index];} index += 1; index = index % buffer.len(); } return (max - min) as f64 / 64.0; } }
use mmc::mapper::Mapper; use super::audio_channel::AudioChannelState; use super::ring_buffer::RingBuffer; pub struct DmcState { pub name: String, pub chip: String, pub debug_disable: bool, pub debug_buffer: Vec<i16>, pub output_buffer: RingBuffer, pub looping: bool, pub period_initial: u16, pub period_current: u16, pub output_level: u8, pub starting_address: u16, pub sample_length: u16, pub current_address: u16, pub sample_buffer: u8, pub shift_register: u8, pub sample_buffer_empty: bool, pub bits_remaining: u8, pub bytes_remaining: u16, pub silence_flag: bool, pub interrupt_enabled: bool, pub interrupt_flag: bool, pub rdy_line: bool, pub rdy_delay: u8, } impl DmcState { pub fn new(channel_name: &str, chip_name: &str) -> DmcState { return DmcState { name: String::from(channel_name), chip: String::from(chip_name), debug_disable: false, debug_buffer: vec!(0i16; 4096), output_buffer: RingBuffer::new(32768), looping: false, period_initial: 428, period_current: 0, output_level: 0, starting_address: 0, sample_length: 0, current_address: 0, sample_buffer: 0, shift_register: 0, sample_buffer_empty: true, bits_remaining: 8, bytes_remaining: 0, silence_flag: false, interrupt_enabled: true, interrupt_flag: false, rdy_line: false, rdy_delay: 0, } } pub fn debug_status(&self) -> String { return format!("Rate: {:3} - Divisor: {:3} - Start: {:04X} - Current: {:04X} - Length: {:4} - R.Bytes: {:4} - R.Bits: {:1}", self.period_initial, self.period_current, self.starting_address, self.current_address, self.sample_length, self.bytes_remaining, self.bits_remaining); } pub fn read_next_sample(&mut self, mapper: &mut dyn Mapper) { match mapper.read_cpu(0x8000 | (self.current_address & 0x7FFF)) { Some(byte) => self.sample_buffer = byte, None => self.sample_buffer = 0, } self.current_address = self.current_address.wrapping_add(1); self.bytes_remaining -= 1; if self.bytes_remaining == 0 { if self.looping { self.current_address = self.starting_address; self.bytes_remaining = self.sample_length; } else { if self.interrupt_enabled { self.interrupt_flag = true; } } } self.sample_buffer_empty = false; self.rdy_line = false; self.rdy_delay = 0; } pub fn begin_output_cycle(&mut self) { self.bits_remaining = 8; if self.sample_buffer_empty { self.silence_flag = true; } else { self.silence_flag = false; self.shift_register = self.sample_buffer; self.sample_buffer_empty = true; } }
pub fn clock(&mut self, mapper: &mut dyn Mapper) { if self.period_current == 0 { self.period_current = self.period_initial - 1; self.update_output_unit(); } else { self.period_current -= 1; } if self.sample_buffer_empty && self.bytes_remaining > 0 { self.rdy_line = true; self.rdy_delay += 1; if self.rdy_delay > 2 { self.read_next_sample(mapper); } } else { self.rdy_line = false; self.rdy_delay = 0; } } pub fn output(&self) -> i16 { return self.output_level as i16; } } impl AudioChannelState for DmcState { fn name(&self) -> String { return self.name.clone(); } fn chip(&self) -> String { return self.chip.clone(); } fn sample_buffer(&self) -> &RingBuffer { return &self.output_buffer; } fn record_current_output(&mut self) { self.output_buffer.push(self.output()); } fn min_sample(&self) -> i16 { return 0; } fn max_sample(&self) -> i16 { return 127; } fn muted(&self) -> bool { return self.debug_disable; } fn mute(&mut self) { self.debug_disable = true; } fn unmute(&mut self) { self.debug_disable = false; } fn playing(&self) -> bool { return true; } fn amplitude(&self) -> f64 { let buffer = self.output_buffer.buffer(); let mut index = (self.output_buffer.index() - 256) % buffer.len(); let mut max = buffer[index]; let mut min = buffer[index]; for _i in 0 .. 256 { if buffer[index] > max {max = buffer[index];} if buffer[index] < min {min = buffer[index];} index += 1; index = index % buffer.len(); } return (max - min) as f64 / 64.0; } }
pub fn update_output_unit(&mut self) { if !(self.silence_flag) { let mut target_output = self.output_level; if (self.shift_register & 0b1) == 0 { if self.output_level >= 2 { target_output -= 2; } } else { if self.output_level <= 125 { target_output += 2; } } self.output_level = target_output; } self.shift_register = self.shift_register >> 1; self.bits_remaining -= 1; if self.bits_remaining == 0 { self.begin_output_cycle(); } }
function_block-full_function
[ { "content": "pub fn mapper_from_file(file_data: &[u8]) -> Result<Box<dyn Mapper>, String> {\n\n let mut file_reader = file_data;\n\n return mapper_from_reader(&mut file_reader);\n\n}", "file_path": "src/cartridge.rs", "rank": 0, "score": 278454.8317243863 }, { "content": "pub fn mappe...
Rust
src/lib.rs
ravenexp/python3-dll-a
3735d6543ced976ab9405fdda3f010243c7fe551
#![deny(missing_docs)] #![allow(clippy::needless_doctest_main)] use std::env; use std::fs::{create_dir_all, write}; use std::io::{Error, ErrorKind, Result}; use std::path::{Path, PathBuf}; use std::process::Command; const IMPLIB_EXT_GNU: &str = ".dll.a"; const IMPLIB_EXT_MSVC: &str = ".lib"; const DLLTOOL_GNU: &str = "x86_64-w64-mingw32-dlltool"; const DLLTOOL_GNU_32: &str = "i686-w64-mingw32-dlltool"; const DLLTOOL_MSVC: &str = "llvm-dlltool"; #[cfg(windows)] const LIB_MSVC: &str = "lib.exe"; #[derive(Debug, Clone)] pub struct ImportLibraryGenerator { arch: String, env: String, version: Option<(u8, u8)>, } impl ImportLibraryGenerator { pub fn new(arch: &str, env: &str) -> Self { Self { arch: arch.to_string(), env: env.to_string(), version: None, } } pub fn version(&mut self, version: Option<(u8, u8)>) -> &mut Self { self.version = version; self } pub fn generate(&self, out_dir: &Path) -> Result<()> { create_dir_all(out_dir)?; let defpath = self.write_def_file(out_dir)?; let dlltool_command = DllToolCommand::find_for_target(&self.arch, &self.env)?; let implib_ext = dlltool_command.implib_file_ext(); let implib_file = self.implib_file_path(out_dir, implib_ext); let mut command = dlltool_command.build(&defpath, &implib_file); let status = command.status().map_err(|e| { let msg = format!("{:?} failed with {}", command, e); Error::new(e.kind(), msg) })?; if status.success() { Ok(()) } else { let msg = format!("{:?} failed with {}", command, status); Err(Error::new(ErrorKind::Other, msg)) } } fn write_def_file(&self, out_dir: &Path) -> Result<PathBuf> { let (def_file, def_file_content) = match self.version { None => ("python3.def", include_str!("python3.def")), Some((3, 7)) => ("python37.def", include_str!("python37.def")), Some((3, 8)) => ("python38.def", include_str!("python38.def")), Some((3, 9)) => ("python39.def", include_str!("python39.def")), Some((3, 10)) => ("python310.def", include_str!("python310.def")), Some((3, 11)) => ("python311.def", include_str!("python311.def")), _ => return Err(Error::new(ErrorKind::Other, "Unsupported Python version")), }; let mut defpath = out_dir.to_owned(); defpath.push(def_file); write(&defpath, def_file_content)?; Ok(defpath) } fn implib_file_path(&self, out_dir: &Path, libext: &str) -> PathBuf { let libname = match self.version { Some((major, minor)) => { format!("python{}{}{}", major, minor, libext) } None => format!("python3{}", libext), }; let mut libpath = out_dir.to_owned(); libpath.push(libname); libpath } } pub fn generate_implib_for_target(out_dir: &Path, arch: &str, env: &str) -> Result<()> { ImportLibraryGenerator::new(arch, env).generate(out_dir) } #[derive(Debug)] enum DllToolCommand { Mingw { command: Command }, Llvm { command: Command, machine: String }, LibExe { command: Command, machine: String }, Zig { command: Command, machine: String }, } impl DllToolCommand { fn find_for_target(arch: &str, env: &str) -> Result<DllToolCommand> { let machine = match arch { "x86_64" => "i386:x86-64", "x86" => "i386", "aarch64" => "arm64", arch => arch, } .to_owned(); if let Some(command) = find_zig() { return Ok(DllToolCommand::Zig { command, machine }); } match (arch, env) { ("x86_64", "gnu") => Ok(DllToolCommand::Mingw { command: Command::new(DLLTOOL_GNU), }), ("x86", "gnu") => Ok(DllToolCommand::Mingw { command: Command::new(DLLTOOL_GNU_32), }), (_, "msvc") => { if let Some(command) = find_lib_exe(arch) { let machine = match arch { "x86_64" => "X64", "x86" => "X86", "aarch64" => "ARM64", arch => arch, } .to_owned(); Ok(DllToolCommand::LibExe { command, machine }) } else { let command = Command::new(DLLTOOL_MSVC); Ok(DllToolCommand::Llvm { command, machine }) } } _ => { let msg = format!("Unsupported target arch '{}' or env ABI '{}'", arch, env); Err(Error::new(ErrorKind::Other, msg)) } } } fn implib_file_ext(&self) -> &'static str { if let DllToolCommand::Mingw { .. } = self { IMPLIB_EXT_GNU } else { IMPLIB_EXT_MSVC } } fn build(self, defpath: &Path, libpath: &Path) -> Command { match self { Self::Mingw { mut command } => { command .arg("--input-def") .arg(defpath) .arg("--output-lib") .arg(libpath); command } Self::Llvm { mut command, machine, } => { command .arg("-m") .arg(machine) .arg("-d") .arg(defpath) .arg("-l") .arg(libpath); command } Self::LibExe { mut command, machine, } => { command .arg(format!("/MACHINE:{}", machine)) .arg(format!("/DEF:{}", defpath.display())) .arg(format!("/OUT:{}", libpath.display())); command } Self::Zig { mut command, machine, } => { command .arg("dlltool") .arg("-m") .arg(machine) .arg("-d") .arg(defpath) .arg("-l") .arg(libpath); command } } } } fn find_zig() -> Option<Command> { let zig_command = env::var("ZIG_COMMAND").ok()?; let mut zig_cmdlet = zig_command.split_ascii_whitespace(); let mut zig = Command::new(zig_cmdlet.next()?); zig.args(zig_cmdlet); Some(zig) } #[cfg(windows)] fn find_lib_exe(arch: &str) -> Option<Command> { let target = match arch { "x86_64" => "x86_64-pc-windows-msvc", "x86" => "i686-pc-windows-msvc", "aarch64" => "aarch64-pc-windows-msvc", _ => return None, }; cc::windows_registry::find(target, LIB_MSVC) } #[cfg(not(windows))] fn find_lib_exe(_arch: &str) -> Option<Command> { None } #[cfg(test)] mod tests { use std::path::PathBuf; use super::*; #[cfg(unix)] #[test] fn generate() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("x86_64-pc-windows-gnu"); dir.push("python3-dll"); ImportLibraryGenerator::new("x86_64", "gnu") .generate(&dir) .unwrap(); for minor in 7..=11 { ImportLibraryGenerator::new("x86_64", "gnu") .version(Some((3, minor))) .generate(&dir) .unwrap(); } } #[cfg(unix)] #[test] fn generate_gnu32() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("i686-pc-windows-gnu"); dir.push("python3-dll"); generate_implib_for_target(&dir, "x86", "gnu").unwrap(); } #[test] fn generate_msvc() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("x86_64-pc-windows-msvc"); dir.push("python3-dll"); ImportLibraryGenerator::new("x86_64", "msvc") .generate(&dir) .unwrap(); for minor in 7..=11 { ImportLibraryGenerator::new("x86_64", "msvc") .version(Some((3, minor))) .generate(&dir) .unwrap(); } } #[test] fn generate_msvc32() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("i686-pc-windows-msvc"); dir.push("python3-dll"); generate_implib_for_target(&dir, "x86", "msvc").unwrap(); } #[test] fn generate_msvc_arm64() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("aarch64-pc-windows-msvc"); dir.push("python3-dll"); generate_implib_for_target(&dir, "aarch64", "msvc").unwrap(); } }
#![deny(missing_docs)] #![allow(clippy::needless_doctest_main)] use std::env; use std::fs::{create_dir_all, write}; use std::io::{Error, ErrorKind, Result}; use std::path::{Path, PathBuf}; use std::process::Command; const IMPLIB_EXT_GNU: &str = ".dll.a"; const IMPLIB_EXT_MSVC: &str = ".lib"; const DLLTOOL_GNU: &str = "x86_64-w64-mingw32-dlltool"; const DLLTOOL_GNU_32: &str = "i686-w64-mingw32-dlltool"; const DLLTOOL_MSVC: &str = "llvm-dlltool"; #[cfg(windows)] const LIB_MSVC: &str = "lib.exe"; #[derive(Debug, Clone)] pub struct ImportLibraryGenerator { arch: String, env: String, version: Option<(u8, u8)>, } impl ImportLibraryGenerator { pub fn new(arch: &str, env: &str) -> Self { Self { arch: arch.to_string(), env: env.to_string(), version: None, } } pub fn version(&mut self, version: Option<(u8, u8)>) -> &mut Self { self.version = version; self } pub fn generate(&self, out_dir: &Path) -> Result<()> { create_dir_all(out_dir)?; let defpath = self.write_def_file(out_dir)?; let dlltool_command = DllToolCommand::find_for_target(&self.arch, &self.env)?; let implib_ext = dlltool_command.implib_file_ext(); let implib_file = self.implib_file_path(out_dir, implib_ext); let mut command = dlltool_command.build(&defpath, &implib_file); let status = command.status().map_err(|e| { let msg = format!("{:?} failed with {}", command, e); Error::new(e.kind(), msg) })?; if status.success() { Ok(()) } else { let msg = format!("{:?} failed with {}", command, status); Err(Error::new(ErrorKind::Other, msg)) } } fn write_def_file(&self, out_dir: &Path) -> Result<PathBuf> { let (def_file, def_file_content) = match self.version { None => ("python3.def", include_str!("python3.def")), Some((3, 7)) => ("python37.def", include_str!("python37.def")), Some((3, 8)) => ("python38.def", include_str!("python38.def")), Some((3, 9)) => ("python39.def", include_str!("python39.def")), Some((3, 10)) => ("python310.def", include_str!("python310.def")), Some((3, 11)) => ("python311.def", include_str!("python311.def")), _ => return Err(Error::new(ErrorKind::Other, "Unsupported Python version")), }; let mut defpath = out_dir.to_owned(); defpath.push(def_file); write(&defpath, def_file_content)?; Ok(defpath) } fn implib_file_path(&self, out_dir: &Path, libext: &str) -> PathBuf { let libname = match self.version { Some((major, minor)) => { format!("python{}{}{}", major, minor, libext) } None => format!("python3{}", libext), }; let mut libpath = out_dir.to_owned(); libpath.push(libname); libpath } } pub fn generate_implib_for_target(out_dir: &Path, arch: &str, env: &str) -> Result<()> { ImportLibraryGenerator::new(arch, env).generate(out_dir) } #[derive(Debug)] enum DllToolCommand { Mingw { command: Command }, Llvm { command: Command, machine: String }, LibExe { command: Command, machine: String }, Zig { command: Command, machine: String }, } impl DllToolCommand { fn find_for_target(arch: &str, env: &str) -> Result<DllToolCommand> { let machine = match arch { "x86_64" => "i386:x86-64", "x86" => "i386", "aarch64" => "arm64", arch => arch, } .to_owned(); if let Some(command) = find_zig() { return Ok(DllToolCommand::Zig { command, machine }); } match (arch, env) { ("x86_64", "gnu") => Ok(DllToolCommand::Mingw { command: Command::new(DLLTOOL_GNU), }), ("x86", "gnu") => Ok(DllToolCommand::Mingw { command: Command::new(DLLTOOL_GNU_32), }), (_, "msvc") => { if let Some(command) = find_lib_exe(arch) { let machine = match arch { "x86_64" => "X64", "x86" => "X86", "aarch64" => "ARM64", arch => arch, } .to_owned(); Ok(DllToolCommand::LibExe { command, machine }) } else { let command = Command::new(DLLTOOL_MSVC); Ok(DllToolCommand::Llvm { command, machine }) } } _ => { let msg = format!("Unsupported target arch '{}' or env ABI '{}'", arch, env); Err(Error::new(ErrorKind::Other, msg)) } } } fn implib_file_ext(&self) -> &'static str { if let DllToolCommand::Mingw { .. } = self { IMPLIB_EXT_GNU } else { IMPLIB_EXT_MSVC } } fn build(self, defpath: &Path, libpath: &Path) -> Command { match self { Self::Mingw { mut command } => { command .arg("--input-def") .arg(defpath) .arg("--output-lib") .arg(libpath); command } Self::Llvm { mut command, machine, } => { command .arg("-m") .arg(machine) .arg("-d") .arg(defpath) .arg("-l") .arg(libpath); command } Self::LibExe { mut command, machine, } => { command .arg(format!("/MACHINE:{}", machine)) .arg(format!("/DEF:{}", defpath.display())) .arg(format!("/OUT:{}", libpath.display())); command } Self::Zig { mut command, machine, } => { command .arg("dlltool") .arg("-m") .arg(machine) .arg("-d") .arg(defpath) .arg("-l") .arg(libpath); command } } } } fn find_zig() -> Option<Command> { let zig_command = env::var("ZIG_COMMAND").ok()?; let mut zig_cmdlet = zig_command.split_ascii_whitespace(); let mut zig = Command::new(zig_cmdlet.next()?); zig.args(zig_cmdlet); Some(zig) } #[cfg(windows)] fn find_lib_exe(arch: &str) -> Option<Command> { let target = match arch { "x86_64" => "x86_64-pc-windows-msvc", "x86" => "i686-pc-windows-msvc", "aarch64" => "aarch64-pc-windows-msvc", _ => return None, }; cc::windows_registry::find(target, LIB_MSVC) } #[cfg(not(windows))] fn find_lib_exe(_arch: &str) -> Option<Command> { None } #[cfg(test)] mod tests { use std::path::PathBuf; use super::*; #[cfg(unix)] #[test] fn generate() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("x86_64-pc-windows-gnu"); dir.push("python3-dll"); ImportLibraryGenerator::new("x86_64", "gnu") .generate(&dir) .unwrap(); for minor in 7..=11 { ImportLibraryGenerator::new("x86_64", "gnu") .version(Some((3, minor))) .generate(&dir) .unwrap(); } } #[cfg(unix)] #[test]
#[test] fn generate_msvc() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("x86_64-pc-windows-msvc"); dir.push("python3-dll"); ImportLibraryGenerator::new("x86_64", "msvc") .generate(&dir) .unwrap(); for minor in 7..=11 { ImportLibraryGenerator::new("x86_64", "msvc") .version(Some((3, minor))) .generate(&dir) .unwrap(); } } #[test] fn generate_msvc32() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("i686-pc-windows-msvc"); dir.push("python3-dll"); generate_implib_for_target(&dir, "x86", "msvc").unwrap(); } #[test] fn generate_msvc_arm64() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("aarch64-pc-windows-msvc"); dir.push("python3-dll"); generate_implib_for_target(&dir, "aarch64", "msvc").unwrap(); } }
fn generate_gnu32() { let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); dir.push("target"); dir.push("i686-pc-windows-gnu"); dir.push("python3-dll"); generate_implib_for_target(&dir, "x86", "gnu").unwrap(); }
function_block-full_function
[ { "content": "#!/usr/bin/env python3\n\n# Parses Python Stable ABI symbol definitions from the manifest in the CPython repository located at https://github.com/python/cpython/blob/main/Misc/stable_abi.toml\n\n# and produces a definition file following the format described at https://docs.microsoft.com/en-us/cpp...
Rust
src/lib.rs
Ekleog/libtest-mimic
f902a460e6b951af824ba5f1a5fed5602cbd0314
extern crate crossbeam_channel; extern crate rayon; #[macro_use] extern crate structopt; extern crate termcolor; use std::{ process, }; use rayon::prelude::*; mod args; mod printer; pub use args::{Arguments, ColorSetting, FormatSetting}; #[derive(Clone, Debug)] pub struct Test<D = ()> { pub name: String, pub kind: String, pub is_ignored: bool, pub is_bench: bool, pub data: D, } impl<D: Default> Test<D> { pub fn test(name: impl Into<String>) -> Self { Self { name: name.into(), kind: String::new(), is_ignored: false, is_bench: false, data: D::default(), } } pub fn bench(name: impl Into<String>) -> Self { Self { name: name.into(), kind: String::new(), is_ignored: false, is_bench: true, data: D::default(), } } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Outcome { Passed, Failed { msg: Option<String>, }, Ignored, Measured { avg: u64, variance: u64, }, } #[derive(Debug)] pub enum RunnerEvent<D> { Started { name: String, kind: String, }, Completed { test: Test<D>, outcome: Outcome, }, } #[derive(Clone, Debug)] #[must_use] pub struct Conclusion { has_failed: bool, num_filtered_out: u64, num_passed: u64, num_failed: u64, num_ignored: u64, num_benches: u64, } impl Conclusion { pub fn exit(&self) -> ! { self.exit_if_failed(); process::exit(0); } pub fn exit_if_failed(&self) { if self.has_failed { process::exit(101) } } pub fn has_failed(&self) -> bool { self.has_failed } pub fn num_filtered_out(&self) -> u64 { self.num_filtered_out } pub fn num_passed(&self) -> u64 { self.num_passed } pub fn num_failed(&self) -> u64 { self.num_failed } pub fn num_ignored(&self) -> u64 { self.num_ignored } pub fn num_benches(&self) -> u64 { self.num_benches } } fn run_tests_threaded<D: 'static + Send + Sync>( args: &Arguments, tests: Vec<Test<D>>, run_test: impl Fn(&Test<D>) -> Outcome + 'static + Send + Sync, ) -> impl IntoIterator<Item = RunnerEvent<D>> { let mut builder = rayon::ThreadPoolBuilder::new(); if let Some(n) = args.num_threads { builder = builder.num_threads(n); } let pool = builder.build().expect("Unable to spawn threads"); let args = args.clone(); let (send, recv) = crossbeam_channel::bounded(0); pool.spawn(move || { tests.into_par_iter().for_each(|test| { let _ = send.send(RunnerEvent::Started { name: test.name.clone(), kind: test.kind.clone(), }); let is_ignored = (test.is_ignored && !args.ignored) || (test.is_bench && args.test) || (!test.is_bench && args.bench); let outcome = if is_ignored { Outcome::Ignored } else { run_test(&test) }; let _ = send.send(RunnerEvent::Completed { test, outcome }); }); }); recv } pub fn run_tests<D: 'static + Send + Sync>( args: &Arguments, tests: Vec<Test<D>>, run_test: impl Fn(&Test<D>) -> Outcome + 'static + Send + Sync, ) -> Conclusion { let (tests, num_filtered_out) = if args.filter_string.is_some() || !args.skip.is_empty() { let len_before = tests.len() as u64; let mut tests = tests; tests.retain(|t| { if let Some(filter) = &args.filter_string { match args.exact { true if &t.name != filter => return false, false if !t.name.contains(filter) => return false, _ => {} }; } for skip_filter in &args.skip { match args.exact { true if &t.name == skip_filter => return false, false if t.name.contains(skip_filter) => return false, _ => {} } } true }); let num_filtered_out = len_before - tests.len() as u64; (tests, num_filtered_out) } else { (tests, 0) }; let mut printer = printer::Printer::new(args, &tests); if args.list { printer.print_list(&tests); return Conclusion { has_failed: false, num_filtered_out: 0, num_passed: 0, num_failed: 0, num_ignored: 0, num_benches: 0, }; } printer.print_title(tests.len() as u64); let mut failed_tests = Vec::new(); let mut num_ignored = 0; let mut num_benches = 0; let mut num_passed = 0; for event in run_tests_threaded(args, tests, run_test) { match event { RunnerEvent::Started { name, kind } => { if args.num_threads == Some(1) { printer.print_test(&name, &kind); } } RunnerEvent::Completed { test, outcome } => { if args.num_threads != Some(1) { printer.print_test(&test.name, &test.kind); } printer.print_single_outcome(&outcome); if test.is_bench { num_benches += 1; } match outcome { Outcome::Passed => num_passed += 1, Outcome::Failed { msg } => failed_tests.push((test, msg)), Outcome::Ignored => num_ignored += 1, Outcome::Measured { .. } => {} } } } } if !failed_tests.is_empty() { printer.print_failures(&failed_tests); } let num_failed = failed_tests.len() as u64; let conclusion = Conclusion { has_failed: num_failed != 0, num_filtered_out, num_passed, num_failed, num_ignored, num_benches, }; printer.print_summary(&conclusion); conclusion }
extern crate crossbeam_channel; extern crate rayon; #[macro_use] extern crate structopt; extern crate termcolor; use std::{ process, }; use rayon::prelude::*; mod args; mod printer; pub use args::{Arguments, ColorSetting, FormatSetting}; #[derive(Clone, Debug)] pub struct Test<
inter.print_title(tests.len() as u64); let mut failed_tests = Vec::new(); let mut num_ignored = 0; let mut num_benches = 0; let mut num_passed = 0; for event in run_tests_threaded(args, tests, run_test) { match event { RunnerEvent::Started { name, kind } => { if args.num_threads == Some(1) { printer.print_test(&name, &kind); } } RunnerEvent::Completed { test, outcome } => { if args.num_threads != Some(1) { printer.print_test(&test.name, &test.kind); } printer.print_single_outcome(&outcome); if test.is_bench { num_benches += 1; } match outcome { Outcome::Passed => num_passed += 1, Outcome::Failed { msg } => failed_tests.push((test, msg)), Outcome::Ignored => num_ignored += 1, Outcome::Measured { .. } => {} } } } } if !failed_tests.is_empty() { printer.print_failures(&failed_tests); } let num_failed = failed_tests.len() as u64; let conclusion = Conclusion { has_failed: num_failed != 0, num_filtered_out, num_passed, num_failed, num_ignored, num_benches, }; printer.print_summary(&conclusion); conclusion }
D = ()> { pub name: String, pub kind: String, pub is_ignored: bool, pub is_bench: bool, pub data: D, } impl<D: Default> Test<D> { pub fn test(name: impl Into<String>) -> Self { Self { name: name.into(), kind: String::new(), is_ignored: false, is_bench: false, data: D::default(), } } pub fn bench(name: impl Into<String>) -> Self { Self { name: name.into(), kind: String::new(), is_ignored: false, is_bench: true, data: D::default(), } } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Outcome { Passed, Failed { msg: Option<String>, }, Ignored, Measured { avg: u64, variance: u64, }, } #[derive(Debug)] pub enum RunnerEvent<D> { Started { name: String, kind: String, }, Completed { test: Test<D>, outcome: Outcome, }, } #[derive(Clone, Debug)] #[must_use] pub struct Conclusion { has_failed: bool, num_filtered_out: u64, num_passed: u64, num_failed: u64, num_ignored: u64, num_benches: u64, } impl Conclusion { pub fn exit(&self) -> ! { self.exit_if_failed(); process::exit(0); } pub fn exit_if_failed(&self) { if self.has_failed { process::exit(101) } } pub fn has_failed(&self) -> bool { self.has_failed } pub fn num_filtered_out(&self) -> u64 { self.num_filtered_out } pub fn num_passed(&self) -> u64 { self.num_passed } pub fn num_failed(&self) -> u64 { self.num_failed } pub fn num_ignored(&self) -> u64 { self.num_ignored } pub fn num_benches(&self) -> u64 { self.num_benches } } fn run_tests_threaded<D: 'static + Send + Sync>( args: &Arguments, tests: Vec<Test<D>>, run_test: impl Fn(&Test<D>) -> Outcome + 'static + Send + Sync, ) -> impl IntoIterator<Item = RunnerEvent<D>> { let mut builder = rayon::ThreadPoolBuilder::new(); if let Some(n) = args.num_threads { builder = builder.num_threads(n); } let pool = builder.build().expect("Unable to spawn threads"); let args = args.clone(); let (send, recv) = crossbeam_channel::bounded(0); pool.spawn(move || { tests.into_par_iter().for_each(|test| { let _ = send.send(RunnerEvent::Started { name: test.name.clone(), kind: test.kind.clone(), }); let is_ignored = (test.is_ignored && !args.ignored) || (test.is_bench && args.test) || (!test.is_bench && args.bench); let outcome = if is_ignored { Outcome::Ignored } else { run_test(&test) }; let _ = send.send(RunnerEvent::Completed { test, outcome }); }); }); recv } pub fn run_tests<D: 'static + Send + Sync>( args: &Arguments, tests: Vec<Test<D>>, run_test: impl Fn(&Test<D>) -> Outcome + 'static + Send + Sync, ) -> Conclusion { let (tests, num_filtered_out) = if args.filter_string.is_some() || !args.skip.is_empty() { let len_before = tests.len() as u64; let mut tests = tests; tests.retain(|t| { if let Some(filter) = &args.filter_string { match args.exact { true if &t.name != filter => return false, false if !t.name.contains(filter) => return false, _ => {} }; } for skip_filter in &args.skip { match args.exact { true if &t.name == skip_filter => return false, false if t.name.contains(skip_filter) => return false, _ => {} } } true }); let num_filtered_out = len_before - tests.len() as u64; (tests, num_filtered_out) } else { (tests, 0) }; let mut printer = printer::Printer::new(args, &tests); if args.list { printer.print_list(&tests); return Conclusion { has_failed: false, num_filtered_out: 0, num_passed: 0, num_failed: 0, num_ignored: 0, num_benches: 0, }; } pr
random
[ { "content": "/// Performs a couple of tidy tests.\n\nfn run_test(test: &Test<PathBuf>) -> Outcome {\n\n let path = &test.data;\n\n let content = fs::read(path).expect(\"io error\");\n\n\n\n // Check that the file is valid UTF-8\n\n let content = match String::from_utf8(content) {\n\n Err(_) ...
Rust
src/indicators/woodies_cci.rs
b100pro/yata
18bf83e134e5a89bc57e58b39d0cff9d098c9543
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use super::commodity_channel_index::CommodityChannelIndexInstance; use super::CommodityChannelIndex; use crate::core::{Action, Error, Method, PeriodType, ValueType, Window, OHLC}; use crate::core::{IndicatorConfig, IndicatorInitializer, IndicatorInstance, IndicatorResult}; use crate::helpers::signi; use crate::methods::{Cross, CrossAbove, CrossUnder, SMA}; #[derive(Debug, Clone, Copy)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct WoodiesCCI { pub period1: PeriodType, pub period2: PeriodType, pub signal1_period: PeriodType, pub signal2_bars_count: isize, pub signal3_zone: ValueType, } impl IndicatorConfig for WoodiesCCI { const NAME: &'static str = "WoodiesCCI"; fn validate(&self) -> bool { self.period1 > self.period2 } fn set(&mut self, name: &str, value: String) -> Option<Error> { match name { "period1" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.period1 = value, }, "period2" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.period2 = value, }, "signal1_period" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.signal1_period = value, }, "signal1_bars_count" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.signal2_bars_count = value, }, "signal3_zone" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.signal3_zone = value, }, _ => { return Some(Error::ParameterParse(name.to_string(), value)); } }; None } fn size(&self) -> (u8, u8) { (2, 3) } } impl<T: OHLC> IndicatorInitializer<T> for WoodiesCCI { type Instance = WoodiesCCIInstance; fn init(self, candle: T) -> Result<Self::Instance, Error> where Self: Sized, { if !self.validate() { return Err(Error::WrongConfig); } let cfg = self; let mut cci1 = CommodityChannelIndex::default(); cci1.period = cfg.period1; let mut cci2 = CommodityChannelIndex::default(); cci2.period = cfg.period2; Ok(Self::Instance { cci1: cci1.init(candle)?, cci2: cci2.init(candle)?, sma: SMA::new(cfg.signal1_period, 0.)?, cross1: Cross::default(), cross2: Cross::default(), s2_sum: 0, s3_sum: 0., s3_count: 0, window: Window::new(cfg.signal2_bars_count as PeriodType, 0), cross_above: CrossAbove::default(), cross_under: CrossUnder::default(), cfg, }) } } impl Default for WoodiesCCI { fn default() -> Self { Self { period1: 14, period2: 6, signal1_period: 9, signal2_bars_count: 6, signal3_zone: 0.2, } } } #[derive(Debug)] pub struct WoodiesCCIInstance { cfg: WoodiesCCI, cci1: CommodityChannelIndexInstance, cci2: CommodityChannelIndexInstance, sma: SMA, cross1: Cross, cross2: Cross, s2_sum: isize, s3_sum: ValueType, s3_count: PeriodType, window: Window<i8>, cross_above: CrossAbove, cross_under: CrossUnder, } impl<T: OHLC> IndicatorInstance<T> for WoodiesCCIInstance { type Config = WoodiesCCI; fn config(&self) -> &Self::Config { &self.cfg } fn next(&mut self, candle: T) -> IndicatorResult { let cci1 = self.cci1.next(candle).value(0); let cci2 = self.cci2.next(candle).value(0); let cci1_sign = signi(cci1); let d_cci = cci1 - cci2; let sma = self.sma.next(d_cci); let s1 = self.cross1.next((sma, 0.)); let s0 = self.cross2.next((cci1, 0.)); self.s2_sum += (cci1_sign - self.window.push(cci1_sign)) as isize; let s2 = (self.s2_sum >= self.cfg.signal2_bars_count) as i8 - (self.s2_sum <= -self.cfg.signal2_bars_count) as i8; let is_none = s0.is_none(); self.s3_sum *= is_none as i8 as ValueType; self.s3_count *= is_none as PeriodType; self.s3_sum += cci1; self.s3_count += 1; let s3v = self.s3_sum / self.s3_count as ValueType; let s3 = self.cross_above.next((s3v, self.cfg.signal3_zone)) - self.cross_under.next((s3v, -self.cfg.signal3_zone)); IndicatorResult::new(&[cci1, cci2], &[s1, Action::from(s2), s3]) } }
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use super::commodity_channel_index::CommodityChannelIndexInstance; use super::CommodityChannelIndex; use crate::core::{Action, Error, Method, PeriodType, ValueType, Window, OHLC}; use crate::core::{IndicatorConfig, IndicatorInitializer, IndicatorInstance, IndicatorResult}; use crate::helpers::signi; use crate::methods::{Cross, CrossAbove, CrossUnder, SMA}; #[derive(Debug, Clone, Copy)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct WoodiesCCI { pub period1: PeriodType, pub period2: PeriodType, pub signal1_period: PeriodType, pub signal2_bars_count: isize, pub signal3_zone: ValueType, } impl IndicatorConfig for WoodiesCCI { const NAME: &'static str = "WoodiesCCI"; fn validate(&self) -> bool { self.period1 > self.period2 } fn set(&mut self, name: &str, value: String) -> Option<Error> { match name { "period1" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.period1 = value, }, "period2" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.period2 = value, }, "signal1_period" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.signal1_period = value, }, "signal1_bars_count" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.signal2_bars_count = value, }, "signal3_zone" => match value.parse() { Err(_) => return Some(Error::ParameterParse(name.to_string(), value.to_string())), Ok(value) => self.signal3_zone = value, }, _ => { return Some(Error::ParameterParse(name.to_string(), value)); } }; None } fn size(&self) -> (u8, u8) { (2, 3) } } impl<T: OHLC> IndicatorInitializer<T> for WoodiesCCI { type Instance = WoodiesCCIInstance; fn init(self, candle: T) -> Result<Self::Instance, Error> where Self: Sized, { if !self.validate() { return Err(Error::WrongConfig); } let cfg = self; let mut cci1 = CommodityChannelIndex::default(); cci1.period = cfg.period1; let mut cci2 = CommodityChannelIndex::default(); cci2.period = cfg.period2; Ok(Self::Instance { cci1: cci1.init(candle)?, cci2: cci2.init(candle)?, sma: SMA::new(cfg.signal1_period, 0.)?, cross1: Cross::default(), cross2: Cross::default(), s2_sum: 0, s3_sum: 0., s3_count: 0, window: Window::new(cfg.signal2_bars_count as PeriodType, 0), cross_above: CrossAbove::default(), cross_under: CrossUnder::default(), cfg, }) } } impl Default for WoodiesCCI { fn default() -> Self { Self { period1: 14, period2: 6, signal1_period: 9, signal2_bars_count: 6, signal3_zone: 0.2, } } } #[derive(Debug)] pub struct WoodiesCCIInstance { cfg: WoodiesCCI, cci1: CommodityChannelIndexInstance, cci2: CommodityChannelIndexInstance, sma: SMA, cross1: Cross, cross2: Cross, s2_sum: isize, s3_sum: ValueType, s3_count: PeriodType, window: Window<i8>, cross_above: CrossAbove, cross_under: CrossUnder, } impl<T: OHLC> IndicatorInstance<T> for WoodiesCCIInstance { type Config = WoodiesCCI; fn config(&self) -> &Self::Config { &self.cfg }
}
fn next(&mut self, candle: T) -> IndicatorResult { let cci1 = self.cci1.next(candle).value(0); let cci2 = self.cci2.next(candle).value(0); let cci1_sign = signi(cci1); let d_cci = cci1 - cci2; let sma = self.sma.next(d_cci); let s1 = self.cross1.next((sma, 0.)); let s0 = self.cross2.next((cci1, 0.)); self.s2_sum += (cci1_sign - self.window.push(cci1_sign)) as isize; let s2 = (self.s2_sum >= self.cfg.signal2_bars_count) as i8 - (self.s2_sum <= -self.cfg.signal2_bars_count) as i8; let is_none = s0.is_none(); self.s3_sum *= is_none as i8 as ValueType; self.s3_count *= is_none as PeriodType; self.s3_sum += cci1; self.s3_count += 1; let s3v = self.s3_sum / self.s3_count as ValueType; let s3 = self.cross_above.next((s3v, self.cfg.signal3_zone)) - self.cross_under.next((s3v, -self.cfg.signal3_zone)); IndicatorResult::new(&[cci1, cci2], &[s1, Action::from(s2), s3]) }
function_block-full_function
[ { "content": "/// Basic trait for implementing [Open-High-Low-Close timeseries data](https://en.wikipedia.org/wiki/Candlestick_chart).\n\n///\n\n/// It has already implemented for tuple of 4 and 5 float values:\n\n/// ```\n\n/// use yata::prelude::OHLC;\n\n/// // open high low close\n\n/// let row = (2...
Rust
src/stan_client/mod.rs
stevelr/ratsio
bcda26c44bf82895fa90603a4e2d706c9a663b3b
use crate::nats_client::{ClosableMessage, NatsClient, NatsClientOptions, NatsSid}; use crate::nuid::NUID; use std::{collections::HashMap, sync::Arc}; use tokio::sync::RwLock; use std::fmt::{Debug, Error, Formatter}; use tokio::sync::mpsc::UnboundedSender; pub mod client; const DEFAULT_DISCOVER_PREFIX: &str = "_STAN.discover"; const DEFAULT_ACK_PREFIX: &str = "_STAN.acks"; const DEFAULT_MAX_PUB_ACKS_INFLIGHT: u32 = 16384; const DEFAULT_PING_INTERVAL: u32 = 5; const DEFAULT_PING_MAX_OUT: u32 = 3; const DEFAULT_ACK_WAIT: i32 = 30 * 60000; const DEFAULT_MAX_INFLIGHT: i32 = 1024; #[derive(Debug, Clone, PartialEq, Builder)] #[builder(setter(into), default)] pub struct StanOptions { pub nats_options: NatsClientOptions, pub cluster_id: String, pub client_id: String, pub ping_interval: u32, pub ping_max_out: u32, pub max_pub_acks_inflight: u32, pub discover_prefix: String, pub ack_prefix: String, } #[derive(Debug, Clone)] pub struct StanSid(pub(crate) NatsSid); impl StanOptions { pub fn new<S>(cluster_id: S, client_id: S) -> StanOptions where S: ToString, { StanOptions { client_id: client_id.to_string(), cluster_id: cluster_id.to_string(), ..Default::default() } } pub fn with_options<T, S>(nats_options: T, cluster_id: S, client_id: S) -> StanOptions where T: Into<NatsClientOptions>, S: ToString, { StanOptions { client_id: client_id.to_string(), cluster_id: cluster_id.to_string(), nats_options: nats_options.into(), ..Default::default() } } pub fn builder() -> StanOptionsBuilder { StanOptionsBuilder::default() } } impl Default for StanOptions { fn default() -> Self { StanOptions { nats_options: NatsClientOptions::default(), cluster_id: String::from(""), client_id: String::from(""), ping_interval: DEFAULT_PING_INTERVAL, ping_max_out: DEFAULT_PING_MAX_OUT, max_pub_acks_inflight: DEFAULT_MAX_PUB_ACKS_INFLIGHT, discover_prefix: DEFAULT_DISCOVER_PREFIX.into(), ack_prefix: DEFAULT_ACK_PREFIX.into(), } } } pub(crate) struct AckHandler(Box<dyn Fn() + Send + Sync>); impl Drop for AckHandler { fn drop(&mut self) { self.0() } } impl Debug for AckHandler { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { f.write_str("<ack-handler>") } } #[derive(Debug, Builder)] #[builder(default)] pub struct StanMessage { pub subject: String, pub reply_to: Option<String>, pub payload: Vec<u8>, pub timestamp: i64, pub sequence: u64, pub redelivered: bool, pub ack_inbox: Option<String>, #[builder(setter(skip))] ack_handler: Option<AckHandler>, } impl StanMessage { pub fn new(subject: String, payload: Vec<u8>) -> Self { StanMessage { subject, payload, reply_to: None, timestamp: 0, sequence: 0, redelivered: false, ack_inbox: None, ack_handler: None, } } pub fn with_reply(subject: String, payload: Vec<u8>, reply_to: Option<String>) -> Self { StanMessage { subject, payload, reply_to, timestamp: 0, sequence: 0, redelivered: false, ack_inbox: None, ack_handler: None, } } pub fn builder() -> StanMessageBuilder { StanMessageBuilder::default() } } impl Default for StanMessage { fn default() -> Self { use std::time::{SystemTime, UNIX_EPOCH}; let now = SystemTime::now(); let tstamp = now.duration_since(UNIX_EPOCH).unwrap(); let tstamp_ms = tstamp.as_millis() as i64; StanMessage { subject: String::new(), reply_to: None, payload: Vec::new(), timestamp: tstamp_ms, sequence: 0, redelivered: false, ack_inbox: None, ack_handler: None, } } } impl Clone for StanMessage { fn clone(&self) -> Self { StanMessage { subject: self.subject.clone(), reply_to: self.reply_to.clone(), payload: self.payload.clone(), timestamp: self.timestamp, sequence: self.sequence, redelivered: self.redelivered, ack_inbox: self.ack_inbox.clone(), ack_handler: None, } } } #[derive(Clone, Debug, PartialEq)] pub enum StartPosition { NewOnly = 0, LastReceived = 1, TimeDeltaStart = 2, SequenceStart = 3, First = 4, } #[derive(Clone, Debug, PartialEq, Builder)] #[builder(default)] pub struct StanSubscribe { pub subject: String, pub queue_group: Option<String>, pub durable_name: Option<String>, pub max_in_flight: i32, pub ack_wait_in_secs: i32, pub start_position: StartPosition, pub start_sequence: u64, pub start_time_delta: Option<i32>, pub manual_acks: bool, } impl StanSubscribe { pub fn builder() -> StanSubscribeBuilder { StanSubscribeBuilder::default() } } impl Default for StanSubscribe { fn default() -> Self { StanSubscribe { subject: String::from(""), queue_group: None, durable_name: None, max_in_flight: DEFAULT_MAX_INFLIGHT, ack_wait_in_secs: DEFAULT_ACK_WAIT, start_position: StartPosition::LastReceived, start_sequence: 0, start_time_delta: None, manual_acks: false, } } } #[derive(Clone)] struct Subscription { client_id: String, subject: String, queue_group: Option<String>, durable_name: Option<String>, max_in_flight: i32, ack_wait_in_secs: i32, inbox: String, ack_inbox: String, unsub_requests: String, close_requests: String, sender: UnboundedSender<ClosableMessage>, } pub struct StanClient { pub options: StanOptions, pub nats_client: Arc<NatsClient>, pub client_id: String, client_info: Arc<RwLock<ClientInfo>>, id_generator: Arc<RwLock<NUID>>, conn_id: RwLock<Vec<u8>>, subscriptions: RwLock<HashMap<String, Subscription>>, self_reference: RwLock<Option<Arc<StanClient>>>, } #[derive(Clone, Debug, Default)] pub struct ClientInfo { pub_prefix: String, sub_requests: String, unsub_requests: String, sub_close_requests: String, close_requests: String, ping_requests: String, public_key: String, }
use crate::nats_client::{ClosableMessage, NatsClient, NatsClientOptions, NatsSid}; use crate::nuid::NUID; use std::{collections::HashMap, sync::Arc}; use tokio::sync::RwLock; use std::fmt::{Debug, Error, Formatter}; use tokio::sync::mpsc::UnboundedSender; pub mod client; const DEFAULT_DISCOVER_PREFIX: &str = "_STAN.discover"; const DEFAULT_ACK_PREFIX: &str = "_STAN.acks"; const DEFAULT_MAX_PUB_ACKS_INFLIGHT: u32 = 16384; const DEFAULT_PING_INTERVAL: u32 = 5; const DEFAULT_PING_MAX_OUT: u32 = 3; const DEFAULT_ACK_WAIT: i32 = 30 * 60000; const DEFAULT_MAX_INFLIGHT: i32 = 1024; #[derive(Debug, Clone, PartialEq, Builder)] #[builder(setter(into), default)] pub struct StanOptions { pub nats_options: NatsClientOptions, pub cluster_id: String, pub client_id: String, pub ping_interval: u32, pub ping_max_out: u32, pub max_pub_acks_inflight: u32, pub discover_prefix: String, pub ack_prefix: String, } #[derive(Debug, Clone)] pub struct StanSid(pub(crate) NatsSid); impl StanOptions { pub fn new<S>(cluster_id: S, client_id: S) -> StanOptions where S: ToString, { StanOptions { client_id: client_id.to_string(), cluster_id: cluster_id.to_string(), ..Default::default() } } pub fn with_options<T, S>(nats_options: T, cluster_id: S, client_id: S) -> StanOptions where T: Into<NatsClientOptions>, S: ToString, { StanOptions { client_id: client_id.to_string(), cluster_id: cluster_id.to_string(), nats_options: nats_options.into(), ..Default::default() } } pub fn builder() -> StanOptionsBuilder { StanOptionsBuilder::default() } } impl Default for StanOptions { fn default() -> Self { StanOptions { nats_options: NatsClientOptions::default(), cluster_id: String::from(""), client_id: String::from(""), ping_interval: DEFAULT_PING_INTERVAL, ping_max_out: DEFAULT_PING_MAX_OUT, max_pub_acks_inflight: DEFAULT_MAX_PUB_ACKS_INFLIGHT, discover_prefix: DEFAULT_DISCOVER_PREFIX.into(), ack_prefix: DEFAULT_ACK_PREFIX.into(), } } } pub(crate) struct AckHandler(Box<dyn Fn() + Send + Sync>); impl Drop for AckHandler { fn drop(&mut
one, payload: Vec::new(), timestamp: tstamp_ms, sequence: 0, redelivered: false, ack_inbox: None, ack_handler: None, } } } impl Clone for StanMessage { fn clone(&self) -> Self { StanMessage { subject: self.subject.clone(), reply_to: self.reply_to.clone(), payload: self.payload.clone(), timestamp: self.timestamp, sequence: self.sequence, redelivered: self.redelivered, ack_inbox: self.ack_inbox.clone(), ack_handler: None, } } } #[derive(Clone, Debug, PartialEq)] pub enum StartPosition { NewOnly = 0, LastReceived = 1, TimeDeltaStart = 2, SequenceStart = 3, First = 4, } #[derive(Clone, Debug, PartialEq, Builder)] #[builder(default)] pub struct StanSubscribe { pub subject: String, pub queue_group: Option<String>, pub durable_name: Option<String>, pub max_in_flight: i32, pub ack_wait_in_secs: i32, pub start_position: StartPosition, pub start_sequence: u64, pub start_time_delta: Option<i32>, pub manual_acks: bool, } impl StanSubscribe { pub fn builder() -> StanSubscribeBuilder { StanSubscribeBuilder::default() } } impl Default for StanSubscribe { fn default() -> Self { StanSubscribe { subject: String::from(""), queue_group: None, durable_name: None, max_in_flight: DEFAULT_MAX_INFLIGHT, ack_wait_in_secs: DEFAULT_ACK_WAIT, start_position: StartPosition::LastReceived, start_sequence: 0, start_time_delta: None, manual_acks: false, } } } #[derive(Clone)] struct Subscription { client_id: String, subject: String, queue_group: Option<String>, durable_name: Option<String>, max_in_flight: i32, ack_wait_in_secs: i32, inbox: String, ack_inbox: String, unsub_requests: String, close_requests: String, sender: UnboundedSender<ClosableMessage>, } pub struct StanClient { pub options: StanOptions, pub nats_client: Arc<NatsClient>, pub client_id: String, client_info: Arc<RwLock<ClientInfo>>, id_generator: Arc<RwLock<NUID>>, conn_id: RwLock<Vec<u8>>, subscriptions: RwLock<HashMap<String, Subscription>>, self_reference: RwLock<Option<Arc<StanClient>>>, } #[derive(Clone, Debug, Default)] pub struct ClientInfo { pub_prefix: String, sub_requests: String, unsub_requests: String, sub_close_requests: String, close_requests: String, ping_requests: String, public_key: String, }
self) { self.0() } } impl Debug for AckHandler { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { f.write_str("<ack-handler>") } } #[derive(Debug, Builder)] #[builder(default)] pub struct StanMessage { pub subject: String, pub reply_to: Option<String>, pub payload: Vec<u8>, pub timestamp: i64, pub sequence: u64, pub redelivered: bool, pub ack_inbox: Option<String>, #[builder(setter(skip))] ack_handler: Option<AckHandler>, } impl StanMessage { pub fn new(subject: String, payload: Vec<u8>) -> Self { StanMessage { subject, payload, reply_to: None, timestamp: 0, sequence: 0, redelivered: false, ack_inbox: None, ack_handler: None, } } pub fn with_reply(subject: String, payload: Vec<u8>, reply_to: Option<String>) -> Self { StanMessage { subject, payload, reply_to, timestamp: 0, sequence: 0, redelivered: false, ack_inbox: None, ack_handler: None, } } pub fn builder() -> StanMessageBuilder { StanMessageBuilder::default() } } impl Default for StanMessage { fn default() -> Self { use std::time::{SystemTime, UNIX_EPOCH}; let now = SystemTime::now(); let tstamp = now.duration_since(UNIX_EPOCH).unwrap(); let tstamp_ms = tstamp.as_millis() as i64; StanMessage { subject: String::new(), reply_to: N
random
[]
Rust
crates/napi/src/promise.rs
AlCalzone/napi-rs
110f2196a4095963d73cdcfc5d49f72a9c579aaa
use std::ffi::CStr; use std::future::Future; use std::marker::PhantomData; use std::os::raw::c_void; use std::ptr; use crate::{check_status, sys, JsError, Result}; pub struct FuturePromise<Data, Resolver: FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>> { deferred: sys::napi_deferred, env: sys::napi_env, tsfn: sys::napi_threadsafe_function, async_resource_name: sys::napi_value, resolver: Resolver, _data: PhantomData<Data>, } unsafe impl<T, F: FnOnce(sys::napi_env, T) -> Result<sys::napi_value>> Send for FuturePromise<T, F> { } impl<Data, Resolver: FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>> FuturePromise<Data, Resolver> { pub fn new(env: sys::napi_env, deferred: sys::napi_deferred, resolver: Resolver) -> Result<Self> { let mut async_resource_name = ptr::null_mut(); let s = unsafe { CStr::from_bytes_with_nul_unchecked(b"napi_resolve_promise_from_future\0") }; check_status!(unsafe { sys::napi_create_string_utf8(env, s.as_ptr(), 32, &mut async_resource_name) })?; Ok(FuturePromise { deferred, resolver, env, tsfn: ptr::null_mut(), async_resource_name, _data: PhantomData, }) } pub(crate) fn start(self) -> Result<TSFNValue> { let mut tsfn_value = ptr::null_mut(); let async_resource_name = self.async_resource_name; let env = self.env; let self_ref = Box::leak(Box::from(self)); check_status!(unsafe { sys::napi_create_threadsafe_function( env, ptr::null_mut(), ptr::null_mut(), async_resource_name, 0, 1, ptr::null_mut(), None, self_ref as *mut FuturePromise<Data, Resolver> as *mut c_void, Some(call_js_cb::<Data, Resolver>), &mut tsfn_value, ) })?; self_ref.tsfn = tsfn_value; Ok(TSFNValue(tsfn_value)) } } pub(crate) struct TSFNValue(sys::napi_threadsafe_function); unsafe impl Send for TSFNValue {} pub(crate) async fn resolve_from_future<Data: Send, Fut: Future<Output = Result<Data>>>( tsfn_value: TSFNValue, fut: Fut, ) { let val = fut.await; check_status!(unsafe { sys::napi_call_threadsafe_function( tsfn_value.0, Box::into_raw(Box::from(val)) as *mut c_void, sys::ThreadsafeFunctionCallMode::nonblocking, ) }) .expect("Failed to call thread safe function"); check_status!(unsafe { sys::napi_release_threadsafe_function(tsfn_value.0, sys::ThreadsafeFunctionReleaseMode::release) }) .expect("Failed to release thread safe function"); } unsafe extern "C" fn call_js_cb< Data, Resolver: FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>, >( env: sys::napi_env, _js_callback: sys::napi_value, context: *mut c_void, data: *mut c_void, ) { let future_promise = unsafe { Box::from_raw(context as *mut FuturePromise<Data, Resolver>) }; let value = unsafe { Box::from_raw(data as *mut Result<Data>) }; let resolver = future_promise.resolver; let deferred = future_promise.deferred; let js_value_to_resolve = value.and_then(move |v| (resolver)(env, v)); match js_value_to_resolve { Ok(v) => { let status = unsafe { sys::napi_resolve_deferred(env, deferred, v) }; debug_assert!(status == sys::Status::napi_ok, "Resolve promise failed"); } Err(e) => { let status = unsafe { sys::napi_reject_deferred( env, deferred, if e.maybe_raw.is_null() { JsError::from(e).into_value(env) } else { let mut err = ptr::null_mut(); let get_err_status = sys::napi_get_reference_value(env, e.maybe_raw, &mut err); debug_assert!( get_err_status == sys::Status::napi_ok, "Get Error from Reference failed" ); let delete_reference_status = sys::napi_delete_reference(env, e.maybe_raw); debug_assert!( delete_reference_status == sys::Status::napi_ok, "Delete Error Reference failed" ); err }, ) }; debug_assert!(status == sys::Status::napi_ok, "Reject promise failed"); } }; }
use std::ffi::CStr; use std::future::Future; use std::marker::PhantomData; use std::os::raw::c_void; use std::ptr; use crate::{check_status, sys, JsError, Result}; pub struct FuturePromise<Data, Resolver: FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>> { deferred: sys::napi_deferred, env: sys::napi_env, tsfn: sys::napi_threadsafe_function, async_resource_name: sys::napi_value, resolver: Resolver, _data: PhantomData<Data>, } unsafe impl<T, F: FnOnce(sys::napi_env, T) -> Result<sys::napi_value>> Send for FuturePromise<T, F> { } impl<Data, Resolver: FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>> FuturePromise<Data, Resolver> { pub fn new(env: sys::napi_env, deferred: sys::napi_deferred, resolver: Resolver) -> Result<Self> { let mut async_resource_name = ptr::null_mut(); let s = unsafe { CStr::from_bytes_with_nul_unchecked(b"napi_resolve_promise_from_future\0") };
) }) .expect("Failed to call thread safe function"); check_status!(unsafe { sys::napi_release_threadsafe_function(tsfn_value.0, sys::ThreadsafeFunctionReleaseMode::release) }) .expect("Failed to release thread safe function"); } unsafe extern "C" fn call_js_cb< Data, Resolver: FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>, >( env: sys::napi_env, _js_callback: sys::napi_value, context: *mut c_void, data: *mut c_void, ) { let future_promise = unsafe { Box::from_raw(context as *mut FuturePromise<Data, Resolver>) }; let value = unsafe { Box::from_raw(data as *mut Result<Data>) }; let resolver = future_promise.resolver; let deferred = future_promise.deferred; let js_value_to_resolve = value.and_then(move |v| (resolver)(env, v)); match js_value_to_resolve { Ok(v) => { let status = unsafe { sys::napi_resolve_deferred(env, deferred, v) }; debug_assert!(status == sys::Status::napi_ok, "Resolve promise failed"); } Err(e) => { let status = unsafe { sys::napi_reject_deferred( env, deferred, if e.maybe_raw.is_null() { JsError::from(e).into_value(env) } else { let mut err = ptr::null_mut(); let get_err_status = sys::napi_get_reference_value(env, e.maybe_raw, &mut err); debug_assert!( get_err_status == sys::Status::napi_ok, "Get Error from Reference failed" ); let delete_reference_status = sys::napi_delete_reference(env, e.maybe_raw); debug_assert!( delete_reference_status == sys::Status::napi_ok, "Delete Error Reference failed" ); err }, ) }; debug_assert!(status == sys::Status::napi_ok, "Reject promise failed"); } }; }
check_status!(unsafe { sys::napi_create_string_utf8(env, s.as_ptr(), 32, &mut async_resource_name) })?; Ok(FuturePromise { deferred, resolver, env, tsfn: ptr::null_mut(), async_resource_name, _data: PhantomData, }) } pub(crate) fn start(self) -> Result<TSFNValue> { let mut tsfn_value = ptr::null_mut(); let async_resource_name = self.async_resource_name; let env = self.env; let self_ref = Box::leak(Box::from(self)); check_status!(unsafe { sys::napi_create_threadsafe_function( env, ptr::null_mut(), ptr::null_mut(), async_resource_name, 0, 1, ptr::null_mut(), None, self_ref as *mut FuturePromise<Data, Resolver> as *mut c_void, Some(call_js_cb::<Data, Resolver>), &mut tsfn_value, ) })?; self_ref.tsfn = tsfn_value; Ok(TSFNValue(tsfn_value)) } } pub(crate) struct TSFNValue(sys::napi_threadsafe_function); unsafe impl Send for TSFNValue {} pub(crate) async fn resolve_from_future<Data: Send, Fut: Future<Output = Result<Data>>>( tsfn_value: TSFNValue, fut: Fut, ) { let val = fut.await; check_status!(unsafe { sys::napi_call_threadsafe_function( tsfn_value.0, Box::into_raw(Box::from(val)) as *mut c_void, sys::ThreadsafeFunctionCallMode::nonblocking,
random
[ { "content": "pub fn register_js(exports: &mut JsObject, env: &Env) -> Result<()> {\n\n let test_class = env.define_class(\n\n \"TestClass\",\n\n test_class_constructor,\n\n &[\n\n Property::new(\"miterNative\")?\n\n .with_getter(get_miter_native)\n\n .with_setter(set_miter_native),...
Rust
src/sys/component_manager/tests/test_utils.rs
mehulagg/fuchsia
3f56175ee594da6b287d5fb19f2f0eccea2897f0
use { breakpoint_system_client::BreakpointSystemClient, failure::{format_err, Error, ResultExt}, fidl_fuchsia_io::DirectoryProxy, fidl_fuchsia_sys::{ ComponentControllerEvent, EnvironmentControllerEvent, EnvironmentControllerProxy, EnvironmentMarker, EnvironmentOptions, FileDescriptor, LauncherProxy, }, fidl_fuchsia_test_breakpoints::*, files_async, fuchsia_component::client::*, fuchsia_runtime::HandleType, fuchsia_zircon as zx, futures::future, futures::stream::{StreamExt, TryStreamExt}, parking_lot::{Condvar, Mutex}, rand::random, std::fs::*, std::path::PathBuf, std::{fs::File, io::Read, sync::Arc, thread, time::Duration}, }; pub static COMPONENT_MANAGER_URL: &str = "fuchsia-pkg://fuchsia.com/component_manager#meta/component_manager.cmx"; pub struct BlackBoxTest { pub env: EnvironmentControllerProxy, pub component_manager_app: App, pub component_manager_url: String, pub root_component_url: String, pub label: String, } impl BlackBoxTest { pub async fn default(root_component_url: &str) -> Result<Self, Error> { Self::custom(COMPONENT_MANAGER_URL, root_component_url, vec![], None).await } pub async fn custom( component_manager_url: &str, root_component_url: &str, dir_handles: Vec<(String, zx::Handle)>, output_file_descriptor: Option<FileDescriptor>, ) -> Result<Self, Error> { let random_num = random::<u32>(); let label = format!("test_{}", random_num); let (env, launcher) = create_isolated_environment(&label).await?; let component_manager_app = launch_component_manager( launcher, component_manager_url, root_component_url, dir_handles, output_file_descriptor, ) .await?; let test = Self { env, component_manager_app, component_manager_url: component_manager_url.to_string(), root_component_url: root_component_url.to_string(), label, }; Ok(test) } pub fn get_component_manager_path(&self) -> PathBuf { find_component_manager_in_hub(&self.component_manager_url, &self.label) } pub fn get_hub_v2_path(&self) -> PathBuf { let path = self.get_component_manager_path(); path.join("out/hub") } pub async fn connect_to_breakpoint_system(&self) -> Result<BreakpointSystemClient, Error> { let path = self.get_component_manager_path(); connect_to_breakpoint_system(&path).await } } pub async fn launch_component_and_expect_output( root_component_url: &str, expected_output: String, ) -> Result<(), Error> { launch_component_and_expect_output_with_extra_dirs(root_component_url, vec![], expected_output) .await } pub async fn launch_component_and_expect_output_with_extra_dirs( root_component_url: &str, dir_handles: Vec<(String, zx::Handle)>, expected_output: String, ) -> Result<(), Error> { let (file, pipe_handle) = make_pipe(); let test = BlackBoxTest::custom( COMPONENT_MANAGER_URL, root_component_url, dir_handles, Some(pipe_handle), ) .await?; let breakpoint_system_client = &test.connect_to_breakpoint_system().await?; breakpoint_system_client.start_component_manager().await?; read_from_pipe(file, expected_output) } async fn create_isolated_environment( label: &str, ) -> Result<(EnvironmentControllerProxy, LauncherProxy), Error> { let env = connect_to_service::<EnvironmentMarker>() .context("could not connect to current environment")?; let (new_env, new_env_server_end) = fidl::endpoints::create_proxy().context("could not create proxy")?; let (controller, controller_server_end) = fidl::endpoints::create_proxy().context("could not create proxy")?; let (launcher, launcher_server_end) = fidl::endpoints::create_proxy().context("could not create proxy")?; let mut env_options = EnvironmentOptions { inherit_parent_services: true, use_parent_runners: true, kill_on_oom: false, delete_storage_on_death: true, }; env.create_nested_environment( new_env_server_end, controller_server_end, label, None, &mut env_options, ) .context("could not create isolated environment")?; let EnvironmentControllerEvent::OnCreated {} = controller.take_event_stream().next().await.unwrap().unwrap(); new_env .get_launcher(launcher_server_end) .context("could not get isolated environment launcher")?; Ok((controller, launcher)) } async fn launch_component_manager( launcher: LauncherProxy, component_manager_url: &str, root_component_url: &str, dir_handles: Vec<(String, zx::Handle)>, output_file_descriptor: Option<FileDescriptor>, ) -> Result<App, Error> { let mut options = LaunchOptions::new(); if let Some(output_file_descriptor) = output_file_descriptor { options.set_out(output_file_descriptor); } for dir in dir_handles { options.add_handle_to_namespace(dir.0, dir.1); } let component_manager_app = launch_with_options( &launcher, component_manager_url.to_string(), Some(vec![root_component_url.to_string(), "--debug".to_string()]), options, ) .context("could not launch component manager")?; let event_stream = component_manager_app.controller().take_event_stream(); event_stream .try_filter_map(|event| { let event = match event { ComponentControllerEvent::OnDirectoryReady {} => Some(event), _ => None, }; future::ready(Ok(event)) }) .next() .await; Ok(component_manager_app) } async fn connect_to_breakpoint_system( component_manager_path: &PathBuf, ) -> Result<BreakpointSystemClient, Error> { let path_to_svc = component_manager_path.join("out/svc"); let path_to_svc = path_to_svc.to_str().expect("found invalid chars"); let proxy = connect_to_service_at::<BreakpointSystemMarker>(path_to_svc) .context("could not connect to BreakpointSystem service")?; Ok(BreakpointSystemClient::from_proxy(proxy)) } fn find_component_manager_in_hub(component_manager_url: &str, label: &str) -> PathBuf { let path_to_env = format!("/hub/r/{}", label); let dir: Vec<DirEntry> = read_dir(path_to_env) .expect("could not open nested environment in the hub") .map(|x| x.expect("entry unreadable")) .collect(); assert_eq!(dir.len(), 1); let component_name = component_manager_url .split("/") .last() .expect("the URL for component manager must have at least one '/' character"); let path_to_cm = dir[0].path().join("c").join(component_name); let dir: Vec<DirEntry> = read_dir(path_to_cm) .expect("could not open component manager in the hub") .map(|x| x.expect("entry unreadable")) .collect(); assert_eq!(dir.len(), 1); dir[0].path() } const WAIT_TIMEOUT_SEC: u64 = 10; fn make_pipe() -> (std::fs::File, FileDescriptor) { match fdio::pipe_half() { Err(_) => panic!("failed to create pipe"), Ok((pipe, handle)) => { let pipe_handle = FileDescriptor { type0: HandleType::FileDescriptor as i32, type1: 0, type2: 0, handle0: Some(handle.into()), handle1: None, handle2: None, }; (pipe, pipe_handle) } } } fn read_from_pipe(mut f: File, expected_msg: String) -> Result<(), Error> { let pair = Arc::new((Mutex::new(Vec::new()), Condvar::new())); { let pair = pair.clone(); let expected_msg = expected_msg.clone(); thread::spawn(move || { let expected = expected_msg.as_bytes(); let mut buf = [0; 1024]; loop { let n = f.read(&mut buf).expect("failed to read pipe"); let (actual, cond) = &*pair; let mut actual = actual.lock(); actual.extend_from_slice(&buf[0..n]); if &**actual == expected { cond.notify_one(); return; } } }); } let (actual, cond) = &*pair; let mut actual = actual.lock(); if cond.wait_for(&mut actual, Duration::from_secs(WAIT_TIMEOUT_SEC)).timed_out() { let actual_msg = String::from_utf8(actual.clone()) .map(|v| format!("'{}'", v)) .unwrap_or(format!("{:?}", actual)); return Err(format_err!( "Timed out waiting for matching output\n\ Expected: '{}'\n\ Actual: {}", expected_msg, actual_msg, )); } Ok(()) } pub async fn list_directory(root_proxy: &DirectoryProxy) -> Result<Vec<String>, Error> { let entries = files_async::readdir(&root_proxy).await?; let mut items = entries.iter().map(|entry| entry.name.clone()).collect::<Vec<String>>(); items.sort(); Ok(items) }
use { breakpoint_system_client::BreakpointSystemClient, failure::{format_err, Error, ResultExt}, fidl_fuchsia_io::DirectoryProxy, fidl_fuchsia_sys::{ ComponentControllerEvent, EnvironmentControllerEvent, EnvironmentControllerProxy, EnvironmentMarker, EnvironmentOptions, FileDescriptor, LauncherProxy, }, fidl_fuchsia_test_breakpoints::*, files_async, fuchsia_component::client::*, fuchsia_runtime::HandleType, fuchsia_zircon as zx, futures::future, futures::stream::{StreamExt, TryStreamExt}, parking_lot::{Condvar, Mutex}, rand::random, std::fs::*, std::path::PathBuf, std::{fs::File, io::Read, sync::Arc, thread, time::Duration}, }; pub static COMPONENT_MANAGER_URL: &str = "fuchsia-pkg://fuchsia.com/component_manager#meta/component_manager.cmx"; pub struct BlackBoxTest { pub env: EnvironmentControllerProxy, pub component_manager_app: App, pub component_manager_url: String, pub root_component_url: String, pub label: String, } impl BlackBoxTest { pub async fn default(root_component_url: &str) -> Result<Self, Error> { Self::custom(COMPONENT_MANAGER_URL, root_component_url, vec![], None).await } pub async fn custom( component_manager_url: &str, root_component_url: &str, dir_handles: Vec<(String, zx::Handle)>, output_file_descriptor: Option<FileDescriptor>, ) -> Result<Self, Error> { let random_num = random::<u32>(); let label = format!("test_{}", random_num); let (env, launcher) = create_isolated_environment(&label).await?; let component_manager_app = launch_component_manager( launcher, component_manager_url, root_component_url, dir_handles, output_file_descriptor, ) .await?; let test = Self { env, component_manager_app, component_manager_url: component_manager_url.to_string(), root_component_url: root_component_url.to_string(), label, }; Ok(test) } pub fn get_component_manager_path(&self) -> PathBuf { find_component_manager_in_hub(&self.component_manager_url, &self.label) } pub fn get_hub_v2_path(&self) -> PathBuf { let path = self.get_component_manager_path(); path.join("out/hub") } pub async fn connect_to_breakpoint_system(&self) -> Result<BreakpointSystemClient, Error> { let path = self.get_component_manager_path(); connect_to_breakpoint_system(&path).await } } pub async fn launch_component_and_expect_output( root_component_url: &str, expected_output: String, ) -> Result<(), Error> { launch_component_and_expect_output_with_extra_dirs(root_component_url, vec![], expected_output) .await } pub async fn launch_component_and_expect_output_with_extra_dirs( root_component_url: &str, dir_handles: Vec<(String, zx::Handle)>, expected_output: String, ) -> Result<(), Error> { let (file, pipe_handle) = make_pipe(); let test = BlackBoxTest::custom( COMPONENT_MANAGER_URL, root_component_url, dir_handles, Some(pipe_handle), ) .await?; let breakpoint_system_client = &test.connect_to_breakpoint_system().await?; breakpoint_system_client.start_component_manager().await?; read_from_pipe(file, expected_output) } async fn create_isolated_environment( label: &str, ) -> Result<(EnvironmentControllerProxy, LauncherProxy), Error> { let env = connect_to_service::<EnvironmentMarker>() .context("could not connect to current environment")?; let (new_env, new_env_server_end) = fidl::endpoints::create_proxy().context("could not create proxy")?; let (controller, controller_server_end) = fidl::endpoints::create_proxy().context("could not create proxy")?; let (launcher, launcher_server_end) = fidl::endpoints::create_proxy().context("could not create proxy")?; let mut env_options = EnvironmentOptions { inherit_parent_services: true, use_parent_runners: true, kill_on_oom: false, delete_storage_on_death: true, }; env.create_nested_environment( new_env_server_end, controller_server_end, label, None, &mut env_options, ) .context("could not create isolated environment")?; let EnvironmentControllerEvent::OnCreated {} = controller.take_event_stream().next().await.unwrap().unwrap(); new_env .get_launcher(launcher_server_end) .context("could not get isolated environment launcher")?; Ok((controller, launcher)) } async fn launch_component_manager( launcher: LauncherProxy, component_manager_url: &str, root_component_url: &str, dir_handles: Vec<(String, zx::Handle)>, output_file_descriptor: Option<FileDescriptor>, ) -> Result<App, Error> { let mut options = LaunchOptions::new(); if let Some(output_file_descriptor) = output_file_descriptor { options.set_out(output_file_descriptor); } for dir in dir_handles { options.add_handle_to_namespace(dir.0, dir.1); } let component_manager_app = launch_with_options( &launcher, component_manager_url.to_string(), Some(vec![root_component_url.to_string(), "--debug".to_string()]), options, ) .context("could not launch component manager")?; let event_stream = component_manager_app.controller().take_event_stream(); event_stream .try_filter_map(|event| { let event = match event { ComponentControllerEvent::OnDirectoryReady {} => Some(event), _ => None, }; future::ready(Ok(event)) }) .next() .await; Ok(component_manager_app) } async fn connec
fn find_component_manager_in_hub(component_manager_url: &str, label: &str) -> PathBuf { let path_to_env = format!("/hub/r/{}", label); let dir: Vec<DirEntry> = read_dir(path_to_env) .expect("could not open nested environment in the hub") .map(|x| x.expect("entry unreadable")) .collect(); assert_eq!(dir.len(), 1); let component_name = component_manager_url .split("/") .last() .expect("the URL for component manager must have at least one '/' character"); let path_to_cm = dir[0].path().join("c").join(component_name); let dir: Vec<DirEntry> = read_dir(path_to_cm) .expect("could not open component manager in the hub") .map(|x| x.expect("entry unreadable")) .collect(); assert_eq!(dir.len(), 1); dir[0].path() } const WAIT_TIMEOUT_SEC: u64 = 10; fn make_pipe() -> (std::fs::File, FileDescriptor) { match fdio::pipe_half() { Err(_) => panic!("failed to create pipe"), Ok((pipe, handle)) => { let pipe_handle = FileDescriptor { type0: HandleType::FileDescriptor as i32, type1: 0, type2: 0, handle0: Some(handle.into()), handle1: None, handle2: None, }; (pipe, pipe_handle) } } } fn read_from_pipe(mut f: File, expected_msg: String) -> Result<(), Error> { let pair = Arc::new((Mutex::new(Vec::new()), Condvar::new())); { let pair = pair.clone(); let expected_msg = expected_msg.clone(); thread::spawn(move || { let expected = expected_msg.as_bytes(); let mut buf = [0; 1024]; loop { let n = f.read(&mut buf).expect("failed to read pipe"); let (actual, cond) = &*pair; let mut actual = actual.lock(); actual.extend_from_slice(&buf[0..n]); if &**actual == expected { cond.notify_one(); return; } } }); } let (actual, cond) = &*pair; let mut actual = actual.lock(); if cond.wait_for(&mut actual, Duration::from_secs(WAIT_TIMEOUT_SEC)).timed_out() { let actual_msg = String::from_utf8(actual.clone()) .map(|v| format!("'{}'", v)) .unwrap_or(format!("{:?}", actual)); return Err(format_err!( "Timed out waiting for matching output\n\ Expected: '{}'\n\ Actual: {}", expected_msg, actual_msg, )); } Ok(()) } pub async fn list_directory(root_proxy: &DirectoryProxy) -> Result<Vec<String>, Error> { let entries = files_async::readdir(&root_proxy).await?; let mut items = entries.iter().map(|entry| entry.name.clone()).collect::<Vec<String>>(); items.sort(); Ok(items) }
t_to_breakpoint_system( component_manager_path: &PathBuf, ) -> Result<BreakpointSystemClient, Error> { let path_to_svc = component_manager_path.join("out/svc"); let path_to_svc = path_to_svc.to_str().expect("found invalid chars"); let proxy = connect_to_service_at::<BreakpointSystemMarker>(path_to_svc) .context("could not connect to BreakpointSystem service")?; Ok(BreakpointSystemClient::from_proxy(proxy)) }
function_block-function_prefixed
[]
Rust
src/lib.rs
laurmaedje/symslice
5e650353099e46b35a2b614b64f4eee7d0307bac
use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::path::Path; use crate::elf::ElfFile; use crate::ir::{Microcode, MicroEncoder}; use crate::x86_64::Instruction; #[macro_use] mod helper { use std::fmt::{self, Formatter}; use crate::math::DataType; pub fn write_signed_hex(f: &mut Formatter, value: i64) -> fmt::Result { if value > 0 { write!(f, "+{:#x}", value) } else if value < 0 { write!(f, "-{:#x}", -value) } else { Ok(()) } } pub fn signed_name(s: bool) -> &'static str { if s { " signed" } else { "" } } pub fn boxed<T>(value: T) -> Box<T> { Box::new(value) } pub fn check_compatible(a: DataType, b: DataType, operation: &str) { assert_eq!(a, b, "incompatible data types for {}", operation); } macro_rules! debug_display { ($type:ty) => { impl std::fmt::Debug for $type { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { std::fmt::Display::fmt(self, f) } } }; } } pub mod flow; pub mod math; pub mod sym; pub mod elf; pub mod ir; pub mod x86_64; #[cfg(feature = "timings")] pub mod timings; #[cfg(not(feature = "timings"))] mod timings { pub(crate) fn with<S: Into<String>, F, T>(_: S, f: F) -> T where F: FnOnce() -> T { f() } pub(crate) fn start<S>(_: S) {} pub(crate) fn stop() {} } #[derive(Debug, Clone, Eq, PartialEq)] pub struct Program { pub base: u64, pub entry: u64, pub binary: Vec<u8>, pub code: Vec<(u64, u64, Instruction, Microcode)>, pub symbols: HashMap<u64, String>, } impl Program { pub fn new<P: AsRef<Path>>(filename: P) -> Program { crate::timings::start("program"); let mut file = ElfFile::new(filename).unwrap(); let text = file.get_section(".text").unwrap(); let base = text.header.addr; let binary = text.data; let mut index = 0; let mut code = Vec::new(); let mut encoder = MicroEncoder::new(); while index < binary.len() as u64 { let len = Instruction::length(&binary[index as usize ..]); let bytes = &binary[index as usize .. (index + len) as usize]; let instruction = Instruction::decode(bytes).unwrap(); let microcode = encoder.encode(&instruction).unwrap(); code.push((base + index, len, instruction, microcode)); index += len; } let mut symbols = HashMap::new(); if let Ok(symbol_entries) = file.get_symbols() { for entry in symbol_entries { if !entry.name.is_empty() { symbols.insert(entry.value, entry.name); } } } crate::timings::stop(); Program { base, entry: file.header.entry, binary, code, symbols } } pub fn get_instruction(&self, addr: u64) -> Option<&Instruction> { self.code.iter() .find(|entry| entry.0 == addr) .map(|entry| &entry.2) } } impl Display for Program { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "Program [")?; if !self.code.is_empty() { writeln!(f)?; } let mut first = true; for (addr, _, instruction, microcode) in &self.code { if f.alternate() && !first { writeln!(f)?; } first = false; writeln!(f, " {:x}: {}", addr, instruction)?; if f.alternate() { for op in &microcode.ops { writeln!(f, " | {}", op)?; } } } write!(f, "]") } } #[cfg(test)] mod tests { use super::*; fn test(filename: &str) { let path = format!("target/bin/{}", filename); Program::new(path); } #[test] fn program() { test("block-1"); test("block-2"); test("case"); test("twice"); test("loop"); test("recursive-1"); test("recursive-2"); test("func"); test("bufs"); test("paths"); test("deep"); test("overwrite"); test("min"); } }
use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::path::Path; use crate::elf::ElfFile; use crate::ir::{Microcode, MicroEncoder}; use crate::x86_64::Instruction; #[macro_use] mod helper { use std::fmt::{self, Formatter}; use crate::math::DataType; pub fn write_signed_hex(f: &mut Formatter, value: i64) -> fmt::Result { if value > 0 { write!(f, "+{:#x}", value) } else if value < 0 { write!(f, "-{:#x}", -value) } else {
" {:x}: {}", addr, instruction)?; if f.alternate() { for op in &microcode.ops { writeln!(f, " | {}", op)?; } } } write!(f, "]") } } #[cfg(test)] mod tests { use super::*; fn test(filename: &str) { let path = format!("target/bin/{}", filename); Program::new(path); } #[test] fn program() { test("block-1"); test("block-2"); test("case"); test("twice"); test("loop"); test("recursive-1"); test("recursive-2"); test("func"); test("bufs"); test("paths"); test("deep"); test("overwrite"); test("min"); } }
Ok(()) } } pub fn signed_name(s: bool) -> &'static str { if s { " signed" } else { "" } } pub fn boxed<T>(value: T) -> Box<T> { Box::new(value) } pub fn check_compatible(a: DataType, b: DataType, operation: &str) { assert_eq!(a, b, "incompatible data types for {}", operation); } macro_rules! debug_display { ($type:ty) => { impl std::fmt::Debug for $type { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { std::fmt::Display::fmt(self, f) } } }; } } pub mod flow; pub mod math; pub mod sym; pub mod elf; pub mod ir; pub mod x86_64; #[cfg(feature = "timings")] pub mod timings; #[cfg(not(feature = "timings"))] mod timings { pub(crate) fn with<S: Into<String>, F, T>(_: S, f: F) -> T where F: FnOnce() -> T { f() } pub(crate) fn start<S>(_: S) {} pub(crate) fn stop() {} } #[derive(Debug, Clone, Eq, PartialEq)] pub struct Program { pub base: u64, pub entry: u64, pub binary: Vec<u8>, pub code: Vec<(u64, u64, Instruction, Microcode)>, pub symbols: HashMap<u64, String>, } impl Program { pub fn new<P: AsRef<Path>>(filename: P) -> Program { crate::timings::start("program"); let mut file = ElfFile::new(filename).unwrap(); let text = file.get_section(".text").unwrap(); let base = text.header.addr; let binary = text.data; let mut index = 0; let mut code = Vec::new(); let mut encoder = MicroEncoder::new(); while index < binary.len() as u64 { let len = Instruction::length(&binary[index as usize ..]); let bytes = &binary[index as usize .. (index + len) as usize]; let instruction = Instruction::decode(bytes).unwrap(); let microcode = encoder.encode(&instruction).unwrap(); code.push((base + index, len, instruction, microcode)); index += len; } let mut symbols = HashMap::new(); if let Ok(symbol_entries) = file.get_symbols() { for entry in symbol_entries { if !entry.name.is_empty() { symbols.insert(entry.value, entry.name); } } } crate::timings::stop(); Program { base, entry: file.header.entry, binary, code, symbols } } pub fn get_instruction(&self, addr: u64) -> Option<&Instruction> { self.code.iter() .find(|entry| entry.0 == addr) .map(|entry| &entry.2) } } impl Display for Program { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "Program [")?; if !self.code.is_empty() { writeln!(f)?; } let mut first = true; for (addr, _, instruction, microcode) in &self.code { if f.alternate() && !first { writeln!(f)?; } first = false; writeln!(f,
random
[ { "content": "/// Write the closing of the file.\n\npub fn write_footer<W: Write>(mut f: W) -> Result<()> {\n\n writeln!(f, \"}}\")\n\n}\n\n\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use std::fs::{self, File};\n\n use std::process::Command;\n\n use super::*;\n\n\n\n /// Compile the file with grap...
Rust
native-windows-gui/examples/treeview_d.rs
gyk/native-windows-gui
163d0fcb5c2af8a859f603ce23a7ec218e9b6813
/*! An application that show how to use the TreeView control. Requires the following features: `cargo run --example treeview_d --features "tree-view tree-view-iterator listbox image-list frame"` */ extern crate native_windows_derive as nwd; extern crate native_windows_gui as nwg; use nwd::NwgUi; use nwg::NativeUi; #[derive(Default, NwgUi)] pub struct TreeViewApp { #[nwg_control(size: (600, 350), position: (300, 300), title: "TreeView - Musteloidea")] #[nwg_events( OnWindowClose: [TreeViewApp::exit], OnInit: [TreeViewApp::load_data] )] window: nwg::Window, #[nwg_resource(initial: 5, size: (16, 16))] view_icons: nwg::ImageList, #[nwg_layout(parent: window)] layout: nwg::GridLayout, #[nwg_control(focus: true)] #[nwg_layout_item(layout: layout, col: 0, col_span: 3, row: 0, row_span: 6)] #[nwg_events( OnTreeViewClick: [TreeViewApp::log_events(SELF, EVT)], OnTreeViewDoubleClick: [TreeViewApp::log_events(SELF, EVT)], OnTreeViewRightClick: [TreeViewApp::log_events(SELF, EVT)], OnTreeFocusLost: [TreeViewApp::log_events(SELF, EVT)], OnTreeFocus: [TreeViewApp::log_events(SELF, EVT)], OnTreeItemDelete: [TreeViewApp::log_events(SELF, EVT)], OnTreeItemExpanded: [TreeViewApp::log_events(SELF, EVT)], OnTreeItemChanged: [TreeViewApp::log_events(SELF, EVT)], OnTreeItemSelectionChanged: [TreeViewApp::log_events(SELF, EVT)], )] tree_view: nwg::TreeView, #[nwg_control(flags: "VISIBLE")] #[nwg_layout_item(layout: layout, col: 3, col_span: 2, row: 0, row_span: 3,)] control_frame: nwg::Frame, #[nwg_layout(parent: control_frame, spacing: 3, margin: [0,0,0,0])] control_layout: nwg::GridLayout, #[nwg_control(parent: control_frame, text: "Options:")] #[nwg_layout_item(layout: control_layout, col: 0, row: 0)] label1: nwg::Label, #[nwg_control(parent: control_frame, text: "New item name")] #[nwg_layout_item(layout: control_layout, col: 0, col_span: 2, row: 1)] new_item: nwg::TextInput, #[nwg_control(parent: control_frame, text: "Add")] #[nwg_layout_item(layout: control_layout, col: 0, row: 2)] #[nwg_events(OnButtonClick: [TreeViewApp::button_actions(SELF, CTRL)])] add_btn: nwg::Button, #[nwg_control(parent: control_frame, text: "Del")] #[nwg_layout_item(layout: control_layout, col: 1, row: 2)] #[nwg_events(OnButtonClick: [TreeViewApp::button_actions(SELF, CTRL)])] remove_btn: nwg::Button, #[nwg_control(text: "Events:")] #[nwg_layout_item(layout: layout, col: 3, col_span: 2, row: 3)] label2: nwg::Label, #[nwg_control] #[nwg_layout_item(layout: layout, col: 3, col_span: 2, row: 4, row_span: 2)] events_log: nwg::ListBox<String>, } impl TreeViewApp { fn load_data(&self) { let tv = &self.tree_view; let icons = &self.view_icons; icons.add_icon_from_filename("./test_rc/cog.ico").unwrap(); icons.add_icon_from_filename("./test_rc/love.ico").unwrap(); tv.set_image_list(Some(icons)); let root = tv.insert_item("Caniformia", None, nwg::TreeInsert::Root); tv.insert_item( "Canidae (dogs and other canines)", Some(&root), nwg::TreeInsert::Last, ); let arc = tv.insert_item("Arctoidea", Some(&root), nwg::TreeInsert::Last); tv.insert_item("Ursidae (bears)", Some(&arc), nwg::TreeInsert::Last); let mus = tv.insert_item("Musteloidea (weasel)", Some(&arc), nwg::TreeInsert::Last); tv.insert_item("Mephitidae (skunks)", Some(&mus), nwg::TreeInsert::Last); tv.insert_item("Ailuridae (red panda)", Some(&mus), nwg::TreeInsert::Last); tv.insert_item( "Procyonidae (raccoons and allies)", Some(&mus), nwg::TreeInsert::Last, ); tv.insert_item( "Mustelidae (weasels and allies)", Some(&mus), nwg::TreeInsert::Last, ); tv.set_text_color(50, 50, 200); for item in tv.iter() { tv.set_expand_state(&item, nwg::ExpandState::Expand); tv.set_item_image(&item, 1, true); } } fn button_actions(&self, btn: &nwg::Button) { let tv = &self.tree_view; if btn == &self.add_btn { let text = self.new_item.text(); let item = match tv.selected_item() { Some(i) => tv.insert_item(&text, Some(&i), nwg::TreeInsert::Last), None => tv.insert_item(&text, None, nwg::TreeInsert::Root), }; tv.set_item_image(&item, 1, true); } else if btn == &self.remove_btn { if let Some(item) = tv.selected_item() { tv.remove_item(&item); } } } fn log_events(&self, evt: nwg::Event) { self.events_log.insert(0, format!("{:?}", evt)); } fn exit(&self) { nwg::stop_thread_dispatch(); } } fn main() { nwg::init().expect("Failed to init Native Windows GUI"); nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font"); let _app = TreeViewApp::build_ui(Default::default()).expect("Failed to build UI"); nwg::dispatch_thread_events(); }
/*! An application that show how to use the TreeView control. Requires the following features: `cargo run --example treeview_d --features "tree-view tree-view-iterator listbox image-list frame"` */ extern crate native_windows_derive as nwd; extern crate native_windows_gui as nwg; use nwd::NwgUi; use nwg::NativeUi; #[derive(Default, NwgUi)] pub struct TreeViewApp { #[nwg_control(size: (600, 350), position: (300, 300), title: "TreeView - Musteloidea")] #[nwg_events( OnWindowClose: [TreeViewApp::exit], OnInit: [TreeViewApp::load_data] )] window: nwg::Window, #[nwg_resource(initial: 5, size: (16, 16))] view_icons: nwg::ImageList, #[nwg_layout(parent: window)] layout: nwg::GridLayout, #[nwg_control(focus: true)] #[nwg_layout_item(layout: layout, col: 0, col_span: 3, row: 0, row_span: 6)] #[nwg_events( OnTreeViewClick: [TreeViewApp::log_events(SELF, EVT)], OnTreeViewDoubleClick: [TreeViewApp::log_events(SELF, EVT)], OnTreeViewRightClick: [TreeViewApp::log_events(SELF, EVT)], OnTreeFocusLost: [TreeViewApp::log_events(SELF, EVT)], OnTreeFocus: [TreeViewApp::log_events(SELF, EVT)], OnTreeItemDelete: [TreeViewApp::log_events(SELF, EVT)], OnTreeItemExpanded: [TreeViewApp::log_events(SELF, EVT)], OnTreeItemChanged: [TreeViewApp::log_events(SELF, EVT)], OnTreeItemSelectionChanged: [TreeViewApp::log_events(SELF, EVT)], )] tree_view: nwg::TreeView, #[nwg_control(flags: "VISIBLE")] #[nwg_layout_item(layout: layout, col: 3, col_span: 2, row: 0, row_span: 3,)] control_frame: nwg::Frame, #[nwg_layout(parent: control_frame, spacing: 3, margin: [0,0,0,0])] control_layout: nwg::GridLayout, #[nwg_control(parent: control_frame, text: "Options:")] #[nwg_layout_item(layout: control_layout, col: 0, row: 0)] label1: nwg::Label, #[nwg_control(parent: control_frame, text: "New item name")] #[nwg_layout_item(layout: control_layout, col: 0, col_span: 2, row: 1)] new_item: nwg::TextInput, #[nwg_control(parent: control_frame, text: "Add")] #[nwg_layout_item(layout: control_layout, col: 0, row: 2)] #[nwg_events(OnButtonClick: [TreeViewApp::button_actions(SELF, CTRL)])] add_btn: nwg::Button, #[nwg_control(parent: control_frame, text: "Del")] #[nwg_layout_item(layout: control_layout, col: 1, row: 2)] #[nwg_events(OnButtonClick: [TreeViewApp::button_actions(SELF, CTRL)])] remove_btn: nwg::Button, #[nwg_control(text: "Events:")] #[nwg_layout_item(layout: layout, col: 3, col_span: 2, row: 3)] label2: nwg::Label, #[nwg_control] #[nwg_layout_item(layout: layout, col: 3, col_span: 2, row: 4, row_span: 2)] events_log: nwg::ListBox<String>, } impl TreeViewApp { fn load_data(&self) { let tv = &self.tree_view; let icons = &self.view_icons; icons.add_icon_from_filename("./test_rc/cog.ico").unwrap(); icons.add_icon_from_filename("./test_rc/love.ico").unwrap(); tv.set_image_list(Some(icons)); let root = tv.insert_item("Caniformia", None, nwg::TreeInsert::Root); tv.insert_item( "Canidae (dogs and other canines)", Some(&root), nwg::TreeInsert::Last, ); let arc = tv.insert_item("Arctoidea", Some(&root), nwg::TreeInsert::Last); tv.insert_item("Ursidae (bears)", Some(&arc), nwg::TreeInsert::Last); let mus = tv.insert_item("Musteloidea (weasel)", Some(&arc), nwg::TreeInsert::Last); tv.insert_item("Mephitidae (skunks)", Some(&mus), nwg::TreeInsert::Last); tv.insert_item("Ailuridae (red panda)", Some(&mus), nwg::TreeInsert::Last); tv.insert_item( "Procyonidae (raccoons and allies)", Some(&mus), nwg::TreeInsert::Last, ); tv.insert_item( "Mustelidae (weasels and allies)", Some(&mus), nwg::TreeInsert::Last, ); tv.set_text_color(50, 50, 200); for item in tv.iter() { tv.set_expand_state(&item, nwg::ExpandState::Expand); tv.set_item_image(&item, 1, true); } } fn button_actions(&self, btn: &nwg::Button) { let tv = &self.tree_view; if btn == &self.add_btn { let text = self.new_item.text(); let item = match tv.selected_item() { Some(i) => tv.insert_item(&text, Some(&i), nwg::TreeInsert::Last), None => tv.insert_item(&text, None, nwg::TreeInsert::Root), };
fn log_events(&self, evt: nwg::Event) { self.events_log.insert(0, format!("{:?}", evt)); } fn exit(&self) { nwg::stop_thread_dispatch(); } } fn main() { nwg::init().expect("Failed to init Native Windows GUI"); nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font"); let _app = TreeViewApp::build_ui(Default::default()).expect("Failed to build UI"); nwg::dispatch_thread_events(); }
tv.set_item_image(&item, 1, true); } else if btn == &self.remove_btn { if let Some(item) = tv.selected_item() { tv.remove_item(&item); } } }
function_block-function_prefix_line
[ { "content": "fn build_frame(button: &mut nwg::ImageFrame, window: &nwg::Window, ico: &nwg::Icon) {\n\n nwg::ImageFrame::builder()\n\n .parent(window)\n\n .build(button);\n\n}\n\n```\n\n*/\n\n#[derive(Default)]\n\npub struct ImageFrame {\n\n pub handle: ControlHandle,\n\n background_brush...
Rust
io-engine/tests/lock_lba_range.rs
openebs/MayaStor
a6424b565ea4023acc7896e591e9c71f832eba3f
#![allow(clippy::await_holding_refcell_ref)] #[macro_use] extern crate tracing; use std::{ cell::{Ref, RefCell, RefMut}, ops::{Deref, DerefMut}, rc::Rc, }; use crossbeam::channel::unbounded; use io_engine::{ bdev::nexus::{nexus_create, nexus_lookup_mut}, core::{ IoChannel, MayastorCliArgs, MayastorEnvironment, RangeContext, Reactor, Reactors, UntypedBdev, }, }; use spdk_rs::DmaBuf; pub mod common; const NEXUS_NAME: &str = "lba_range_nexus"; const NEXUS_SIZE: u64 = 10 * 1024 * 1024; const NUM_NEXUS_CHILDREN: u64 = 2; #[derive(Clone)] struct ShareableContext { ctx: Rc<RefCell<RangeContext>>, ch: Rc<RefCell<IoChannel>>, } impl ShareableContext { pub fn new(offset: u64, len: u64) -> ShareableContext { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); Self { ctx: Rc::new(RefCell::new(RangeContext::new(offset, len))), ch: Rc::new(RefCell::new(nexus.get_channel().unwrap())), } } pub fn borrow_mut_ctx(&self) -> RefMut<RangeContext> { self.ctx.borrow_mut() } pub fn borrow_ch(&self) -> Ref<IoChannel> { self.ch.borrow() } } fn test_ini() { test_init!(); for i in 0 .. NUM_NEXUS_CHILDREN { common::delete_file(&[get_disk(i)]); common::truncate_file_bytes(&get_disk(i), NEXUS_SIZE); } Reactor::block_on(async { create_nexus().await; }); } fn test_fini() { for i in 0 .. NUM_NEXUS_CHILDREN { common::delete_file(&[get_disk(i)]); } Reactor::block_on(async { let nexus = nexus_lookup_mut(NEXUS_NAME).unwrap(); nexus.destroy().await.unwrap(); }); } fn get_disk(number: u64) -> String { format!("/tmp/disk{}.img", number) } fn get_dev(number: u64) -> String { format!("aio://{}?blk_size=512", get_disk(number)) } async fn create_nexus() { let mut ch = Vec::new(); for i in 0 .. NUM_NEXUS_CHILDREN { ch.push(get_dev(i)); } nexus_create(NEXUS_NAME, NEXUS_SIZE, None, &ch) .await .unwrap(); } async fn lock_range( ctx: &mut RangeContext, ch: &IoChannel, ) -> Result<(), nix::errno::Errno> { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); nexus.lock_lba_range(ctx, ch).await } async fn unlock_range( ctx: &mut RangeContext, ch: &IoChannel, ) -> Result<(), nix::errno::Errno> { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); nexus.unlock_lba_range(ctx, ch).await } #[test] fn lock_unlock() { test_ini(); Reactor::block_on(async { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); let mut ctx = RangeContext::new(1, 5); let ch = nexus.get_channel().unwrap(); nexus .lock_lba_range(&mut ctx, &ch) .await .expect("Failed to acquire lock"); nexus .unlock_lba_range(&mut ctx, &ch) .await .expect("Failed to release lock"); }); test_fini(); } #[test] fn lock_unlock_different_context() { test_ini(); Reactor::block_on(async { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); let mut ctx = RangeContext::new(1, 5); let ch = nexus.get_channel().unwrap(); nexus .lock_lba_range(&mut ctx, &ch) .await .expect("Failed to acquire lock"); let mut ctx1 = RangeContext::new(1, 5); let ch1 = nexus.get_channel().unwrap(); nexus .unlock_lba_range(&mut ctx1, &ch1) .await .expect_err("Shouldn't be able to unlock with a different context"); }); test_fini(); } #[test] fn multiple_locks() { test_ini(); let reactor = Reactors::current(); let (s, r) = unbounded::<()>(); let ctx1 = ShareableContext::new(1, 10); let ctx_clone1 = ctx1.clone(); reactor.send_future(async move { lock_range( ctx_clone1.borrow_mut_ctx().deref_mut(), ctx_clone1.borrow_ch().deref(), ) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); let (lock_sender, lock_receiver) = unbounded::<()>(); let ctx2 = ShareableContext::new(1, 5); let ctx_clone2 = ctx2.clone(); reactor.send_future(async move { lock_range( ctx_clone2.borrow_mut_ctx().deref_mut(), ctx_clone2.borrow_ch().deref(), ) .await .unwrap(); lock_sender.send(()).unwrap(); }); reactor_poll!(100); assert!(lock_receiver.try_recv().is_err()); let (s, r) = unbounded::<()>(); reactor.send_future(async move { unlock_range( ctx1.borrow_mut_ctx().deref_mut(), ctx1.borrow_ch().deref(), ) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); reactor_poll!(100); assert!(lock_receiver.try_recv().is_ok()); let (s, r) = unbounded::<()>(); reactor.send_future(async move { unlock_range( ctx2.borrow_mut_ctx().deref_mut(), ctx2.borrow_ch().deref(), ) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); test_fini(); } #[test] fn lock_then_fe_io() { test_ini(); let reactor = Reactors::current(); let (s, r) = unbounded::<()>(); let ctx = ShareableContext::new(1, 10); let ctx_clone = ctx.clone(); reactor.send_future(async move { lock_range( ctx_clone.borrow_mut_ctx().deref_mut(), ctx_clone.borrow_ch().deref(), ) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); let (io_sender, io_receiver) = unbounded::<()>(); reactor.send_future(async move { let nexus_desc = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); let h = nexus_desc.into_handle().unwrap(); let blk = 2; let blk_size = 512; let buf = DmaBuf::new(blk * blk_size, 9).unwrap(); match h.write_at((blk * blk_size) as u64, &buf).await { Ok(_) => trace!("Successfully wrote to nexus"), Err(e) => trace!("Failed to write to nexus: {}", e), } io_sender.send(()).unwrap(); }); reactor_poll!(1000); assert!(io_receiver.try_recv().is_err()); let (s, r) = unbounded::<()>(); reactor.send_future(async move { unlock_range(ctx.borrow_mut_ctx().deref_mut(), ctx.borrow_ch().deref()) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); assert!(io_receiver.try_recv().is_ok()); test_fini(); }
#![allow(clippy::await_holding_refcell_ref)] #[macro_use] extern crate tracing; use std::{ cell::{Ref, RefCell, RefMut}, ops::{Deref, DerefMut}, rc::Rc, }; use crossbea
lock_sender.send(()).unwrap(); }); reactor_poll!(100); assert!(lock_receiver.try_recv().is_err()); let (s, r) = unbounded::<()>(); reactor.send_future(async move { unlock_range( ctx1.borrow_mut_ctx().deref_mut(), ctx1.borrow_ch().deref(), ) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); reactor_poll!(100); assert!(lock_receiver.try_recv().is_ok()); let (s, r) = unbounded::<()>(); reactor.send_future(async move { unlock_range( ctx2.borrow_mut_ctx().deref_mut(), ctx2.borrow_ch().deref(), ) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); test_fini(); } #[test] fn lock_then_fe_io() { test_ini(); let reactor = Reactors::current(); let (s, r) = unbounded::<()>(); let ctx = ShareableContext::new(1, 10); let ctx_clone = ctx.clone(); reactor.send_future(async move { lock_range( ctx_clone.borrow_mut_ctx().deref_mut(), ctx_clone.borrow_ch().deref(), ) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); let (io_sender, io_receiver) = unbounded::<()>(); reactor.send_future(async move { let nexus_desc = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); let h = nexus_desc.into_handle().unwrap(); let blk = 2; let blk_size = 512; let buf = DmaBuf::new(blk * blk_size, 9).unwrap(); match h.write_at((blk * blk_size) as u64, &buf).await { Ok(_) => trace!("Successfully wrote to nexus"), Err(e) => trace!("Failed to write to nexus: {}", e), } io_sender.send(()).unwrap(); }); reactor_poll!(1000); assert!(io_receiver.try_recv().is_err()); let (s, r) = unbounded::<()>(); reactor.send_future(async move { unlock_range(ctx.borrow_mut_ctx().deref_mut(), ctx.borrow_ch().deref()) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); assert!(io_receiver.try_recv().is_ok()); test_fini(); }
m::channel::unbounded; use io_engine::{ bdev::nexus::{nexus_create, nexus_lookup_mut}, core::{ IoChannel, MayastorCliArgs, MayastorEnvironment, RangeContext, Reactor, Reactors, UntypedBdev, }, }; use spdk_rs::DmaBuf; pub mod common; const NEXUS_NAME: &str = "lba_range_nexus"; const NEXUS_SIZE: u64 = 10 * 1024 * 1024; const NUM_NEXUS_CHILDREN: u64 = 2; #[derive(Clone)] struct ShareableContext { ctx: Rc<RefCell<RangeContext>>, ch: Rc<RefCell<IoChannel>>, } impl ShareableContext { pub fn new(offset: u64, len: u64) -> ShareableContext { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); Self { ctx: Rc::new(RefCell::new(RangeContext::new(offset, len))), ch: Rc::new(RefCell::new(nexus.get_channel().unwrap())), } } pub fn borrow_mut_ctx(&self) -> RefMut<RangeContext> { self.ctx.borrow_mut() } pub fn borrow_ch(&self) -> Ref<IoChannel> { self.ch.borrow() } } fn test_ini() { test_init!(); for i in 0 .. NUM_NEXUS_CHILDREN { common::delete_file(&[get_disk(i)]); common::truncate_file_bytes(&get_disk(i), NEXUS_SIZE); } Reactor::block_on(async { create_nexus().await; }); } fn test_fini() { for i in 0 .. NUM_NEXUS_CHILDREN { common::delete_file(&[get_disk(i)]); } Reactor::block_on(async { let nexus = nexus_lookup_mut(NEXUS_NAME).unwrap(); nexus.destroy().await.unwrap(); }); } fn get_disk(number: u64) -> String { format!("/tmp/disk{}.img", number) } fn get_dev(number: u64) -> String { format!("aio://{}?blk_size=512", get_disk(number)) } async fn create_nexus() { let mut ch = Vec::new(); for i in 0 .. NUM_NEXUS_CHILDREN { ch.push(get_dev(i)); } nexus_create(NEXUS_NAME, NEXUS_SIZE, None, &ch) .await .unwrap(); } async fn lock_range( ctx: &mut RangeContext, ch: &IoChannel, ) -> Result<(), nix::errno::Errno> { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); nexus.lock_lba_range(ctx, ch).await } async fn unlock_range( ctx: &mut RangeContext, ch: &IoChannel, ) -> Result<(), nix::errno::Errno> { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); nexus.unlock_lba_range(ctx, ch).await } #[test] fn lock_unlock() { test_ini(); Reactor::block_on(async { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); let mut ctx = RangeContext::new(1, 5); let ch = nexus.get_channel().unwrap(); nexus .lock_lba_range(&mut ctx, &ch) .await .expect("Failed to acquire lock"); nexus .unlock_lba_range(&mut ctx, &ch) .await .expect("Failed to release lock"); }); test_fini(); } #[test] fn lock_unlock_different_context() { test_ini(); Reactor::block_on(async { let nexus = UntypedBdev::open_by_name(NEXUS_NAME, true).unwrap(); let mut ctx = RangeContext::new(1, 5); let ch = nexus.get_channel().unwrap(); nexus .lock_lba_range(&mut ctx, &ch) .await .expect("Failed to acquire lock"); let mut ctx1 = RangeContext::new(1, 5); let ch1 = nexus.get_channel().unwrap(); nexus .unlock_lba_range(&mut ctx1, &ch1) .await .expect_err("Shouldn't be able to unlock with a different context"); }); test_fini(); } #[test] fn multiple_locks() { test_ini(); let reactor = Reactors::current(); let (s, r) = unbounded::<()>(); let ctx1 = ShareableContext::new(1, 10); let ctx_clone1 = ctx1.clone(); reactor.send_future(async move { lock_range( ctx_clone1.borrow_mut_ctx().deref_mut(), ctx_clone1.borrow_ch().deref(), ) .await .unwrap(); s.send(()).unwrap(); }); reactor_poll!(r); let (lock_sender, lock_receiver) = unbounded::<()>(); let ctx2 = ShareableContext::new(1, 5); let ctx_clone2 = ctx2.clone(); reactor.send_future(async move { lock_range( ctx_clone2.borrow_mut_ctx().deref_mut(), ctx_clone2.borrow_ch().deref(), ) .await .unwrap();
random
[ { "content": "#[async_trait(? Send)]\n\npub trait Share: std::fmt::Debug {\n\n type Error;\n\n type Output: std::fmt::Display + std::fmt::Debug;\n\n async fn share_nvmf(\n\n self: Pin<&mut Self>,\n\n cntlid_range: Option<(u16, u16)>,\n\n ) -> Result<Self::Output, Self::Error>;\n\n\n\n ...
Rust
tests/curve_test.rs
AlexandruIca/verg
adcdac98f57492e8b7576e06a92491934d2e0fa1
use crate::common::default_blending; use verg::{ canvas::{Canvas, CanvasDescription, ViewBox}, color::{Color, FillRule, FillStyle}, geometry::{PathOps, Point}, math::{rotate_around, scale_around, translate, Angle}, }; mod common; const WIDTH: usize = 805; const HEIGHT: usize = 405; fn canvas_description() -> CanvasDescription { CanvasDescription { width: WIDTH, height: HEIGHT, viewbox: ViewBox { x: 0.0, y: 0.0, width: WIDTH as f64, height: HEIGHT as f64, }, background_color: Color::white(), tolerance: 0.25, } } const PATH: [PathOps; 4] = [ PathOps::MoveTo { x: 20.0, y: 360.0 }, PathOps::CubicTo { x1: 100.0, y1: 260.0, x2: 50.0, y2: 160.0, x3: 150.0, y3: 60.0, }, PathOps::CubicTo { x1: 120.0, y1: 160.0, x2: 150.0, y2: 260.0, x3: 200.0, y3: 360.0, }, PathOps::CubicTo { x1: 90.0, y1: 320.0, x2: 130.0, y2: 320.0, x3: 20.0, y3: 360.0, }, ]; const DARK_SLATE_BLUE: FillStyle = FillStyle::Plain(Color::dark_slate_blue()); const YELLOW: FillStyle = FillStyle::Plain(Color::yellow()); const BLACK: FillStyle = FillStyle::Plain(Color::black()); const FILL_RULE: FillRule = FillRule::NonZero; const MOON_WIDTH: f64 = 30.0; const MOON_HEIGHT: f64 = 80.0; const MOON_VERTICAL_OFFSET: f64 = 5.0; const MOON: [PathOps; 3] = [ PathOps::MoveTo { x: 0.0, y: 0.0 }, PathOps::CubicTo { x1: MOON_WIDTH / 2.0, y1: MOON_HEIGHT / 2.0 - MOON_VERTICAL_OFFSET, x2: MOON_WIDTH / 2.0, y2: MOON_HEIGHT / 2.0 + MOON_VERTICAL_OFFSET, x3: 0.0, y3: MOON_HEIGHT, }, PathOps::CubicTo { x1: MOON_WIDTH, y1: MOON_HEIGHT / 2.0 + MOON_VERTICAL_OFFSET, x2: MOON_WIDTH, y2: MOON_HEIGHT / 2.0 - MOON_VERTICAL_OFFSET, x3: 0.0, y3: 0.0, }, ]; const EYE_WIDTH: f64 = 150.0; const EYE_HEIGHT: f64 = 300.0; const EYE_QUARTER_W: f64 = EYE_WIDTH / 4.0; const EYE_QUARTER_H: f64 = EYE_HEIGHT / 4.0; const EYE_INNER_OFFSET: f64 = 10.0; const EYE: [PathOps; 10] = [ PathOps::MoveTo { x: EYE_WIDTH / 2.0, y: EYE_HEIGHT, }, PathOps::CubicTo { x1: EYE_WIDTH / 2.0 + EYE_QUARTER_W, y1: EYE_HEIGHT, x2: EYE_WIDTH, y2: EYE_HEIGHT - EYE_QUARTER_H, x3: EYE_WIDTH, y3: EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: EYE_WIDTH, y1: EYE_HEIGHT / 2.0 - EYE_QUARTER_H, x2: EYE_WIDTH - EYE_QUARTER_W, y2: 0.0, x3: EYE_WIDTH / 2.0, y3: 0.0, }, PathOps::CubicTo { x1: EYE_QUARTER_W, y1: 0.0, x2: 0.0, y2: EYE_QUARTER_H, x3: 0.0, y3: EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: 0.0, y1: EYE_HEIGHT / 2.0 + EYE_QUARTER_H, x2: EYE_QUARTER_W, y2: EYE_HEIGHT, x3: EYE_WIDTH / 2.0, y3: EYE_HEIGHT, }, PathOps::MoveTo { x: EYE_WIDTH / 2.0, y: EYE_HEIGHT - EYE_INNER_OFFSET, }, PathOps::CubicTo { x1: EYE_QUARTER_W + EYE_INNER_OFFSET, y1: EYE_HEIGHT - EYE_INNER_OFFSET, x2: EYE_INNER_OFFSET, y2: EYE_HEIGHT - EYE_QUARTER_H - EYE_INNER_OFFSET, x3: EYE_INNER_OFFSET, y3: EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: EYE_INNER_OFFSET, y1: EYE_QUARTER_H + EYE_INNER_OFFSET, x2: EYE_QUARTER_W + EYE_INNER_OFFSET, y2: EYE_INNER_OFFSET, x3: EYE_WIDTH / 2.0, y3: EYE_INNER_OFFSET, }, PathOps::CubicTo { x1: EYE_WIDTH / 2.0 + EYE_QUARTER_W - EYE_INNER_OFFSET, y1: EYE_INNER_OFFSET, x2: EYE_WIDTH - EYE_INNER_OFFSET, y2: EYE_QUARTER_H + EYE_INNER_OFFSET, x3: EYE_WIDTH - EYE_INNER_OFFSET, y3: EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: EYE_WIDTH - EYE_INNER_OFFSET, y1: EYE_HEIGHT / 2.0 + EYE_QUARTER_H - EYE_INNER_OFFSET, x2: EYE_WIDTH / 2.0 + EYE_QUARTER_W - EYE_INNER_OFFSET, y2: EYE_HEIGHT - EYE_INNER_OFFSET, x3: EYE_WIDTH / 2.0, y3: EYE_HEIGHT - EYE_INNER_OFFSET, }, ]; const SMALL_EYE_WIDTH: f64 = 80.0; const SMALL_EYE_HEIGHT: f64 = 1.5 * SMALL_EYE_WIDTH; const SMALL_EYE_QUARTER_W: f64 = SMALL_EYE_WIDTH / 4.0; const SMALL_EYE_QUARTER_H: f64 = SMALL_EYE_HEIGHT / 4.0; const SMALL_EYE_INNER_OFFSET: f64 = 10.0; const SMALL_EYE_UPPER: f64 = 4.0; const SMALL_EYE: [PathOps; 10] = [ PathOps::MoveTo { x: SMALL_EYE_WIDTH / 2.0, y: SMALL_EYE_HEIGHT, }, PathOps::CubicTo { x1: SMALL_EYE_WIDTH / 2.0 + SMALL_EYE_QUARTER_W, y1: SMALL_EYE_HEIGHT, x2: SMALL_EYE_WIDTH, y2: SMALL_EYE_HEIGHT - SMALL_EYE_QUARTER_H, x3: SMALL_EYE_WIDTH, y3: SMALL_EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: SMALL_EYE_WIDTH, y1: SMALL_EYE_HEIGHT / 2.0 - SMALL_EYE_QUARTER_H, x2: SMALL_EYE_WIDTH - SMALL_EYE_QUARTER_W, y2: 0.0, x3: SMALL_EYE_WIDTH / 2.0, y3: 0.0, }, PathOps::CubicTo { x1: SMALL_EYE_QUARTER_W, y1: 0.0, x2: 0.0, y2: SMALL_EYE_QUARTER_H, x3: 0.0, y3: SMALL_EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: 0.0, y1: SMALL_EYE_HEIGHT / 2.0 + SMALL_EYE_QUARTER_H, x2: SMALL_EYE_QUARTER_W, y2: SMALL_EYE_HEIGHT, x3: SMALL_EYE_WIDTH / 2.0, y3: SMALL_EYE_HEIGHT, }, PathOps::MoveTo { x: SMALL_EYE_WIDTH / 2.0, y: SMALL_EYE_HEIGHT - SMALL_EYE_INNER_OFFSET, }, PathOps::CubicTo { x1: SMALL_EYE_QUARTER_W + SMALL_EYE_INNER_OFFSET, y1: SMALL_EYE_HEIGHT - SMALL_EYE_INNER_OFFSET, x2: SMALL_EYE_INNER_OFFSET, y2: SMALL_EYE_HEIGHT - SMALL_EYE_QUARTER_H - SMALL_EYE_INNER_OFFSET, x3: SMALL_EYE_INNER_OFFSET, y3: SMALL_EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: SMALL_EYE_INNER_OFFSET, y1: SMALL_EYE_QUARTER_H + SMALL_EYE_INNER_OFFSET, x2: SMALL_EYE_QUARTER_W + SMALL_EYE_INNER_OFFSET, y2: SMALL_EYE_UPPER * SMALL_EYE_INNER_OFFSET, x3: SMALL_EYE_WIDTH / 2.0, y3: SMALL_EYE_UPPER * SMALL_EYE_INNER_OFFSET, }, PathOps::CubicTo { x1: SMALL_EYE_WIDTH / 2.0 + SMALL_EYE_QUARTER_W - SMALL_EYE_INNER_OFFSET, y1: SMALL_EYE_UPPER * SMALL_EYE_INNER_OFFSET, x2: SMALL_EYE_WIDTH - SMALL_EYE_INNER_OFFSET, y2: SMALL_EYE_QUARTER_H + SMALL_EYE_INNER_OFFSET, x3: SMALL_EYE_WIDTH - SMALL_EYE_INNER_OFFSET, y3: SMALL_EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: SMALL_EYE_WIDTH - SMALL_EYE_INNER_OFFSET, y1: SMALL_EYE_HEIGHT / 2.0 + SMALL_EYE_QUARTER_H - SMALL_EYE_INNER_OFFSET, x2: SMALL_EYE_WIDTH / 2.0 + SMALL_EYE_QUARTER_W - SMALL_EYE_INNER_OFFSET, y2: SMALL_EYE_HEIGHT - SMALL_EYE_INNER_OFFSET, x3: SMALL_EYE_WIDTH / 2.0, y3: SMALL_EYE_HEIGHT - SMALL_EYE_INNER_OFFSET, }, ]; const IRIS_WIDTH: f64 = 40.0; const IRIS_HEIGHT: f64 = 1.5 * IRIS_WIDTH; const IRIS_QUARTER_W: f64 = IRIS_WIDTH / 4.0; const IRIS_QUARTER_H: f64 = IRIS_HEIGHT / 4.0; const IRIS: [PathOps; 5] = [ PathOps::MoveTo { x: IRIS_WIDTH / 2.0, y: IRIS_HEIGHT, }, PathOps::CubicTo { x1: IRIS_WIDTH / 2.0 + IRIS_QUARTER_W, y1: IRIS_HEIGHT, x2: IRIS_WIDTH, y2: IRIS_HEIGHT - IRIS_QUARTER_H, x3: IRIS_WIDTH, y3: IRIS_HEIGHT / 2.0, }, PathOps::CubicTo { x1: IRIS_WIDTH, y1: IRIS_HEIGHT / 2.0 - IRIS_QUARTER_H, x2: IRIS_WIDTH - IRIS_QUARTER_W, y2: 0.0, x3: IRIS_WIDTH / 2.0, y3: 0.0, }, PathOps::CubicTo { x1: IRIS_QUARTER_W, y1: 0.0, x2: 0.0, y2: IRIS_QUARTER_H, x3: 0.0, y3: IRIS_HEIGHT / 2.0, }, PathOps::CubicTo { x1: 0.0, y1: IRIS_HEIGHT / 2.0 + IRIS_QUARTER_H, x2: IRIS_QUARTER_W, y2: IRIS_HEIGHT, x3: IRIS_WIDTH / 2.0, y3: IRIS_HEIGHT, }, ]; fn callback(canvas: &mut Canvas) { let transform = |p: &Point| { let center = Point { x: MOON_WIDTH / 2.0, y: MOON_HEIGHT / 2.0, }; let p = rotate_around(&p, &center, Angle::from_degrees(65.0)); let p = scale_around(&p, &center, 1.5, 1.5); translate(&p, 280.0, 180.0) }; canvas.draw_shape(&MOON, YELLOW, FILL_RULE, transform); let transform = |x: f64, y: f64| { return move |p: &Point| translate(&p, x, y); }; canvas.draw_shape(&EYE, BLACK, FILL_RULE, transform(400.0, 50.0)); canvas.draw_shape(&EYE, BLACK, FILL_RULE, transform(400.0 + EYE_WIDTH, 50.0)); canvas.draw_shape(&SMALL_EYE, BLACK, FILL_RULE, transform(433.0, 220.0)); canvas.draw_shape( &SMALL_EYE, BLACK, FILL_RULE, transform(433.0 + EYE_WIDTH, 220.0), ); canvas.draw_shape(&IRIS, BLACK, FILL_RULE, transform(448.0, 267.0)); canvas.draw_shape(&IRIS, BLACK, FILL_RULE, transform(448.0 + EYE_WIDTH, 267.0)); } implement_test! { curve_test, canvas_description, callback | PATH, DARK_SLATE_BLUE, FILL_RULE, default_blending }
use crate::common::default_blending; use verg::{ canvas::{Canvas, CanvasDescription, ViewBox}, color::{Color, FillRule, FillStyle}, geometry::{PathOps, Point}, math::{rotate_around, scale_around, translate, Angle}, }; mod common; const WIDTH: usize = 805; const HEIGHT: usize = 405; fn canvas_description() -> CanvasDescription { CanvasDescription {
}, background_color: Color::white(), tolerance: 0.25, } } const PATH: [PathOps; 4] = [ PathOps::MoveTo { x: 20.0, y: 360.0 }, PathOps::CubicTo { x1: 100.0, y1: 260.0, x2: 50.0, y2: 160.0, x3: 150.0, y3: 60.0, }, PathOps::CubicTo { x1: 120.0, y1: 160.0, x2: 150.0, y2: 260.0, x3: 200.0, y3: 360.0, }, PathOps::CubicTo { x1: 90.0, y1: 320.0, x2: 130.0, y2: 320.0, x3: 20.0, y3: 360.0, }, ]; const DARK_SLATE_BLUE: FillStyle = FillStyle::Plain(Color::dark_slate_blue()); const YELLOW: FillStyle = FillStyle::Plain(Color::yellow()); const BLACK: FillStyle = FillStyle::Plain(Color::black()); const FILL_RULE: FillRule = FillRule::NonZero; const MOON_WIDTH: f64 = 30.0; const MOON_HEIGHT: f64 = 80.0; const MOON_VERTICAL_OFFSET: f64 = 5.0; const MOON: [PathOps; 3] = [ PathOps::MoveTo { x: 0.0, y: 0.0 }, PathOps::CubicTo { x1: MOON_WIDTH / 2.0, y1: MOON_HEIGHT / 2.0 - MOON_VERTICAL_OFFSET, x2: MOON_WIDTH / 2.0, y2: MOON_HEIGHT / 2.0 + MOON_VERTICAL_OFFSET, x3: 0.0, y3: MOON_HEIGHT, }, PathOps::CubicTo { x1: MOON_WIDTH, y1: MOON_HEIGHT / 2.0 + MOON_VERTICAL_OFFSET, x2: MOON_WIDTH, y2: MOON_HEIGHT / 2.0 - MOON_VERTICAL_OFFSET, x3: 0.0, y3: 0.0, }, ]; const EYE_WIDTH: f64 = 150.0; const EYE_HEIGHT: f64 = 300.0; const EYE_QUARTER_W: f64 = EYE_WIDTH / 4.0; const EYE_QUARTER_H: f64 = EYE_HEIGHT / 4.0; const EYE_INNER_OFFSET: f64 = 10.0; const EYE: [PathOps; 10] = [ PathOps::MoveTo { x: EYE_WIDTH / 2.0, y: EYE_HEIGHT, }, PathOps::CubicTo { x1: EYE_WIDTH / 2.0 + EYE_QUARTER_W, y1: EYE_HEIGHT, x2: EYE_WIDTH, y2: EYE_HEIGHT - EYE_QUARTER_H, x3: EYE_WIDTH, y3: EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: EYE_WIDTH, y1: EYE_HEIGHT / 2.0 - EYE_QUARTER_H, x2: EYE_WIDTH - EYE_QUARTER_W, y2: 0.0, x3: EYE_WIDTH / 2.0, y3: 0.0, }, PathOps::CubicTo { x1: EYE_QUARTER_W, y1: 0.0, x2: 0.0, y2: EYE_QUARTER_H, x3: 0.0, y3: EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: 0.0, y1: EYE_HEIGHT / 2.0 + EYE_QUARTER_H, x2: EYE_QUARTER_W, y2: EYE_HEIGHT, x3: EYE_WIDTH / 2.0, y3: EYE_HEIGHT, }, PathOps::MoveTo { x: EYE_WIDTH / 2.0, y: EYE_HEIGHT - EYE_INNER_OFFSET, }, PathOps::CubicTo { x1: EYE_QUARTER_W + EYE_INNER_OFFSET, y1: EYE_HEIGHT - EYE_INNER_OFFSET, x2: EYE_INNER_OFFSET, y2: EYE_HEIGHT - EYE_QUARTER_H - EYE_INNER_OFFSET, x3: EYE_INNER_OFFSET, y3: EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: EYE_INNER_OFFSET, y1: EYE_QUARTER_H + EYE_INNER_OFFSET, x2: EYE_QUARTER_W + EYE_INNER_OFFSET, y2: EYE_INNER_OFFSET, x3: EYE_WIDTH / 2.0, y3: EYE_INNER_OFFSET, }, PathOps::CubicTo { x1: EYE_WIDTH / 2.0 + EYE_QUARTER_W - EYE_INNER_OFFSET, y1: EYE_INNER_OFFSET, x2: EYE_WIDTH - EYE_INNER_OFFSET, y2: EYE_QUARTER_H + EYE_INNER_OFFSET, x3: EYE_WIDTH - EYE_INNER_OFFSET, y3: EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: EYE_WIDTH - EYE_INNER_OFFSET, y1: EYE_HEIGHT / 2.0 + EYE_QUARTER_H - EYE_INNER_OFFSET, x2: EYE_WIDTH / 2.0 + EYE_QUARTER_W - EYE_INNER_OFFSET, y2: EYE_HEIGHT - EYE_INNER_OFFSET, x3: EYE_WIDTH / 2.0, y3: EYE_HEIGHT - EYE_INNER_OFFSET, }, ]; const SMALL_EYE_WIDTH: f64 = 80.0; const SMALL_EYE_HEIGHT: f64 = 1.5 * SMALL_EYE_WIDTH; const SMALL_EYE_QUARTER_W: f64 = SMALL_EYE_WIDTH / 4.0; const SMALL_EYE_QUARTER_H: f64 = SMALL_EYE_HEIGHT / 4.0; const SMALL_EYE_INNER_OFFSET: f64 = 10.0; const SMALL_EYE_UPPER: f64 = 4.0; const SMALL_EYE: [PathOps; 10] = [ PathOps::MoveTo { x: SMALL_EYE_WIDTH / 2.0, y: SMALL_EYE_HEIGHT, }, PathOps::CubicTo { x1: SMALL_EYE_WIDTH / 2.0 + SMALL_EYE_QUARTER_W, y1: SMALL_EYE_HEIGHT, x2: SMALL_EYE_WIDTH, y2: SMALL_EYE_HEIGHT - SMALL_EYE_QUARTER_H, x3: SMALL_EYE_WIDTH, y3: SMALL_EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: SMALL_EYE_WIDTH, y1: SMALL_EYE_HEIGHT / 2.0 - SMALL_EYE_QUARTER_H, x2: SMALL_EYE_WIDTH - SMALL_EYE_QUARTER_W, y2: 0.0, x3: SMALL_EYE_WIDTH / 2.0, y3: 0.0, }, PathOps::CubicTo { x1: SMALL_EYE_QUARTER_W, y1: 0.0, x2: 0.0, y2: SMALL_EYE_QUARTER_H, x3: 0.0, y3: SMALL_EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: 0.0, y1: SMALL_EYE_HEIGHT / 2.0 + SMALL_EYE_QUARTER_H, x2: SMALL_EYE_QUARTER_W, y2: SMALL_EYE_HEIGHT, x3: SMALL_EYE_WIDTH / 2.0, y3: SMALL_EYE_HEIGHT, }, PathOps::MoveTo { x: SMALL_EYE_WIDTH / 2.0, y: SMALL_EYE_HEIGHT - SMALL_EYE_INNER_OFFSET, }, PathOps::CubicTo { x1: SMALL_EYE_QUARTER_W + SMALL_EYE_INNER_OFFSET, y1: SMALL_EYE_HEIGHT - SMALL_EYE_INNER_OFFSET, x2: SMALL_EYE_INNER_OFFSET, y2: SMALL_EYE_HEIGHT - SMALL_EYE_QUARTER_H - SMALL_EYE_INNER_OFFSET, x3: SMALL_EYE_INNER_OFFSET, y3: SMALL_EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: SMALL_EYE_INNER_OFFSET, y1: SMALL_EYE_QUARTER_H + SMALL_EYE_INNER_OFFSET, x2: SMALL_EYE_QUARTER_W + SMALL_EYE_INNER_OFFSET, y2: SMALL_EYE_UPPER * SMALL_EYE_INNER_OFFSET, x3: SMALL_EYE_WIDTH / 2.0, y3: SMALL_EYE_UPPER * SMALL_EYE_INNER_OFFSET, }, PathOps::CubicTo { x1: SMALL_EYE_WIDTH / 2.0 + SMALL_EYE_QUARTER_W - SMALL_EYE_INNER_OFFSET, y1: SMALL_EYE_UPPER * SMALL_EYE_INNER_OFFSET, x2: SMALL_EYE_WIDTH - SMALL_EYE_INNER_OFFSET, y2: SMALL_EYE_QUARTER_H + SMALL_EYE_INNER_OFFSET, x3: SMALL_EYE_WIDTH - SMALL_EYE_INNER_OFFSET, y3: SMALL_EYE_HEIGHT / 2.0, }, PathOps::CubicTo { x1: SMALL_EYE_WIDTH - SMALL_EYE_INNER_OFFSET, y1: SMALL_EYE_HEIGHT / 2.0 + SMALL_EYE_QUARTER_H - SMALL_EYE_INNER_OFFSET, x2: SMALL_EYE_WIDTH / 2.0 + SMALL_EYE_QUARTER_W - SMALL_EYE_INNER_OFFSET, y2: SMALL_EYE_HEIGHT - SMALL_EYE_INNER_OFFSET, x3: SMALL_EYE_WIDTH / 2.0, y3: SMALL_EYE_HEIGHT - SMALL_EYE_INNER_OFFSET, }, ]; const IRIS_WIDTH: f64 = 40.0; const IRIS_HEIGHT: f64 = 1.5 * IRIS_WIDTH; const IRIS_QUARTER_W: f64 = IRIS_WIDTH / 4.0; const IRIS_QUARTER_H: f64 = IRIS_HEIGHT / 4.0; const IRIS: [PathOps; 5] = [ PathOps::MoveTo { x: IRIS_WIDTH / 2.0, y: IRIS_HEIGHT, }, PathOps::CubicTo { x1: IRIS_WIDTH / 2.0 + IRIS_QUARTER_W, y1: IRIS_HEIGHT, x2: IRIS_WIDTH, y2: IRIS_HEIGHT - IRIS_QUARTER_H, x3: IRIS_WIDTH, y3: IRIS_HEIGHT / 2.0, }, PathOps::CubicTo { x1: IRIS_WIDTH, y1: IRIS_HEIGHT / 2.0 - IRIS_QUARTER_H, x2: IRIS_WIDTH - IRIS_QUARTER_W, y2: 0.0, x3: IRIS_WIDTH / 2.0, y3: 0.0, }, PathOps::CubicTo { x1: IRIS_QUARTER_W, y1: 0.0, x2: 0.0, y2: IRIS_QUARTER_H, x3: 0.0, y3: IRIS_HEIGHT / 2.0, }, PathOps::CubicTo { x1: 0.0, y1: IRIS_HEIGHT / 2.0 + IRIS_QUARTER_H, x2: IRIS_QUARTER_W, y2: IRIS_HEIGHT, x3: IRIS_WIDTH / 2.0, y3: IRIS_HEIGHT, }, ]; fn callback(canvas: &mut Canvas) { let transform = |p: &Point| { let center = Point { x: MOON_WIDTH / 2.0, y: MOON_HEIGHT / 2.0, }; let p = rotate_around(&p, &center, Angle::from_degrees(65.0)); let p = scale_around(&p, &center, 1.5, 1.5); translate(&p, 280.0, 180.0) }; canvas.draw_shape(&MOON, YELLOW, FILL_RULE, transform); let transform = |x: f64, y: f64| { return move |p: &Point| translate(&p, x, y); }; canvas.draw_shape(&EYE, BLACK, FILL_RULE, transform(400.0, 50.0)); canvas.draw_shape(&EYE, BLACK, FILL_RULE, transform(400.0 + EYE_WIDTH, 50.0)); canvas.draw_shape(&SMALL_EYE, BLACK, FILL_RULE, transform(433.0, 220.0)); canvas.draw_shape( &SMALL_EYE, BLACK, FILL_RULE, transform(433.0 + EYE_WIDTH, 220.0), ); canvas.draw_shape(&IRIS, BLACK, FILL_RULE, transform(448.0, 267.0)); canvas.draw_shape(&IRIS, BLACK, FILL_RULE, transform(448.0 + EYE_WIDTH, 267.0)); } implement_test! { curve_test, canvas_description, callback | PATH, DARK_SLATE_BLUE, FILL_RULE, default_blending }
width: WIDTH, height: HEIGHT, viewbox: ViewBox { x: 0.0, y: 0.0, width: WIDTH as f64, height: HEIGHT as f64,
function_block-random_span
[ { "content": "pub fn rotate(point: &Point, angle: Angle) -> Point {\n\n let (sin, cos) = angle.to_radians().sin_cos();\n\n\n\n Point {\n\n x: point.x * sin - point.y * cos,\n\n y: point.x * cos + point.y * sin,\n\n }\n\n}\n\n\n", "file_path": "src/math.rs", "rank": 0, "score":...
Rust
pkg-dashboard/rate-app/src/canvas.rs
transparencies/rillrate
a1a6f76e84211224a85bb9fd92602d33f095229e
use anyhow::Error; use approx::abs_diff_ne; use derive_more::{Deref, DerefMut}; use plotters::prelude::*; use plotters_canvas::CanvasBackend; use rate_ui::packages::or_fail::{Fail, Fasten}; use wasm_bindgen::JsCast; use web_sys::{CanvasRenderingContext2d as Context2d, HtmlCanvasElement}; use yew::NodeRef; const SCALE: f64 = 2.0; pub struct SmartCanvas { canvas_ref: NodeRef, canvas: Option<HtmlCanvasElement>, ctx2d: Option<Context2d>, scale: f64, real_width: f64, real_height: f64, was_width: f64, was_height: f64, } impl Default for SmartCanvas { fn default() -> Self { Self { canvas_ref: NodeRef::default(), canvas: None, ctx2d: None, scale: SCALE, real_width: 0.0, real_height: 0.0, was_width: 0.0, was_height: 0.0, } } } impl SmartCanvas { pub fn node_ref(&self) -> &NodeRef { &self.canvas_ref } pub fn canvas(&self) -> Result<&HtmlCanvasElement, Error> { self.canvas.as_ref().ok_or_else(|| Error::msg("no canvas")) } pub fn bind(&mut self) -> Result<(), Error> { let canvas = self .canvas_ref .cast::<HtmlCanvasElement>() .or_fail("can't cast canvas")?; let ctx2d: Context2d = canvas .get_context("2d") .fasten()? .or_fail("no canvas context")? .dyn_into() .fasten()?; self.canvas = Some(canvas); self.ctx2d = Some(ctx2d); Ok(()) } pub fn resize(&mut self) -> Result<(), Error> { let canvas = self .canvas .as_ref() .ok_or_else(|| Error::msg("Canvas 2D is not available!"))?; let rect = canvas.get_bounding_client_rect(); self.scale = 2.0; self.real_height = rect.height(); if abs_diff_ne!(&self.was_height, &self.real_height) { let height = self.real_height * self.scale; canvas.set_height(height as u32); self.was_height = self.real_height; } self.real_width = rect.width(); if abs_diff_ne!(&self.was_width, &self.real_width) { let width = self.real_width * self.scale; canvas.set_width(width as u32); self.was_width = self.real_width; } /* log::info!("RATIO: {}", web_sys::window().unwrap().device_pixel_ratio()); self.scale = web_sys::window() .as_ref() .map(Window::device_pixel_ratio) .unwrap_or(SCALE); self.scale = 2.0; */ Ok(()) } pub fn clear(&mut self) -> Result<(), Error> { let ctx = self .ctx2d .as_ref() .ok_or_else(|| Error::msg("Canvas 2D Context not initialized!"))?; /* ctx.set_transform(self.scale, 0.0, 0.0, self.scale, 0.0, 0.0) .map_err(|_| { Error::msg("Can't set transformation parameter to the Canvas 2D Context!") })?; */ ctx.clear_rect( 0.0, 0.0, self.real_width * self.scale, self.real_height * self.scale, ); Ok(()) } } #[derive(Deref, DerefMut, Default)] pub struct DrawCanvas { canvas: SmartCanvas, } impl DrawCanvas { #[allow(clippy::too_many_arguments)] pub fn draw_charts( &mut self, secs: i64, mut from_color: usize, min: f32, max: f32, x_formatter: &dyn Fn(&i64) -> String, y_formatter: &dyn Fn(&f32) -> String, data: &[Vec<(i64, f32)>], ) -> Result<(), Error> { from_color += 5; let canvas = self.canvas.canvas()?.clone(); let root_area = CanvasBackend::with_canvas_object(canvas) .ok_or_else(|| Error::msg("no canvas backend created"))? .into_drawing_area(); let mut ctx = ChartBuilder::on(&root_area) .set_label_area_size(LabelAreaPosition::Left, 40) .set_label_area_size(LabelAreaPosition::Bottom, 40) .margin(60) .build_cartesian_2d((-secs * 1_000)..0, min..max)?; ctx.configure_mesh() .light_line_style(&RGBColor(0xF8, 0xF9, 0xFA)) .label_style(("Jost", 26)) .x_label_formatter(x_formatter) .y_label_formatter(y_formatter) .draw()?; let single = data.len() == 1; for (col, line) in data.iter().enumerate() { let area_color; let line_color; if single { area_color = RGBColor(0xD2, 0x09, 0x09).mix(0.2).to_rgba(); line_color = RGBColor(0x42, 0x11, 0xCC).mix(1.0).to_rgba(); } else { line_color = Palette99::pick(from_color + col).to_rgba(); area_color = line_color.mix(0.2).to_rgba(); } let line = line.iter().cloned(); let series = AreaSeries::new(line, 0.0, &area_color).border_style(&line_color); ctx.draw_series(series)?; } Ok(()) } } pub fn sustain<Y: Copy>(mut iter: impl Iterator<Item = (i64, Y)>, last_x: i64) -> Vec<(i64, Y)> { let mut result = Vec::new(); if let Some((mut prev_x, mut prev_y)) = iter.next() { result.push((prev_x, prev_y)); for (next_x, next_y) in iter { let diff = next_x - prev_x; let shift = (diff as f32 * 0.1) as i64; result.push((next_x - shift, prev_y)); result.push((next_x, next_y)); prev_x = next_x; prev_y = next_y; } result.push((last_x, prev_y)); } result } /* pub fn sustain_soft<Y: Copy>( mut iter: impl Iterator<Item = (i64, Y)>, last: Option<i64>, ) -> Vec<(i64, Y)> { let mut result = Vec::new(); if let Some((mut prev_x, mut prev_y)) = iter.next() { result.push((prev_x, prev_y)); for (next_x, next_y) in iter { let diff = ((next_x - prev_x) as f32 * 0.2) as i64; result.push((next_x - diff, prev_y)); result.push((next_x, next_y)); prev_x = next_x; prev_y = next_y; } if let Some(last_x) = last { result.push((last_x, prev_y)); } } result } pub fn sustain_sharp<X: Copy, Y: Copy>( mut iter: impl Iterator<Item = (X, Y)>, last: Option<X>, ) -> Vec<(X, Y)> { let mut result = Vec::new(); if let Some((prev_x, mut prev_y)) = iter.next() { result.push((prev_x, prev_y)); for (next_x, next_y) in iter { result.push((next_x, prev_y)); result.push((next_x, next_y)); //prev_x = next_x; prev_y = next_y; } if let Some(last_x) = last { result.push((last_x, prev_y)); } } result } */ pub fn formatter_plain(input: &f32) -> String { input.to_string() } /* pub fn formatter_pct(input: &f32) -> String { format!("{:.0} %", input) } */ /* pub fn formatter_kib(input: &f32) -> String { format!("{:.0} KiB/s", input / 1_024.0) } pub fn formatter_gb(input: &f32) -> String { format!("{:.0} Gb", input / 1_000_000.0) } */ pub fn formatter_sec(input: &i64) -> String { let input = input.abs(); format!("{} sec", input / 1_000) /* if input % 60_000 == 0 { format!("{} min", input / 60_000) } else { format!("{} sec", input / 1_000) } */ }
use anyhow::Error; use approx::abs_diff_ne; use derive_more::{Deref, DerefMut}; use plotters::prelude::*; use plotters_canvas::CanvasBackend; use rate_ui::packages::or_fail::{Fail, Fasten}; use wasm_bindgen::JsCast; use web_sys::{CanvasRenderingContext2d as Context2d, HtmlCanvasElement}; use yew::NodeRef; const SCALE: f64 = 2.0; pub struct SmartCanvas { canvas_ref: NodeRef, canvas: Option<HtmlCanvasElement>, ctx2d: Option<Context2d>, scale: f64, real_width: f64, real_height: f64, was_width: f64, was_height: f64, } impl Default for SmartCanvas { fn default() -> Self { Self { canvas_ref: NodeRef::default(), canvas: None, ctx2d: None, scale: SCALE, real_width: 0.0, real_height: 0.0, was_width: 0.0, was_height: 0.0, } } } impl SmartCanvas { pub fn node_ref(&self) -> &NodeRef { &self.canvas_ref } pub fn canvas(&self) -> Result<&HtmlCanvasElement, Error> { self.canvas.as_ref().ok_or_else(|| Error::msg("no canvas")) } pub fn bind(&mut self) -> Result<(), Error> { let canvas = self .canvas_ref .cast::<HtmlCanvasElement>() .or_fail("can't cast canvas")?; let ctx2d: Context2d = canvas .get_context("2d") .fasten()? .or_fail("no canvas context")? .dyn_into() .fasten()?; self.canvas = Some(canvas); self.ctx2d = Some(ctx2d); Ok(()) } pub fn resize(&mut self) -> Result<(), Error> { let canvas = self .canvas .as_ref() .ok_or_else(|| Error::msg("Canvas 2D is not available!"))?; let rect = canvas.get_bounding_client_rect(); self.scale = 2.0; self.real_height = rect.height(); if abs_diff_ne!(&self.was_height, &self.real_height) { let height = self.real_height * self.scale; canvas.set_height(height as u32); self.was_height = self.real_height; } self.real_width = rect.width(); if abs_diff_ne!(&self.was_width, &self.real_width) { let width = self.real_width * self.scale; canvas.set_width(width as u32); self.was_width = self.real_width; } /* log::info!("RATIO: {}", web_sys::window().unwrap().device_pixel_ratio()); self.scale = web_sys::window() .as_ref() .map(Window::device_pixel_ratio) .unwrap_or(SCALE); self.scale = 2.0; */ Ok(()) } pub fn clear(&mut self) -> Result<(), Error> { let ctx = self .ctx2d .as_ref() .ok_or_else(|| Error::msg("Canvas 2D Context not initialized!"))?; /* ctx.set_transform(self.scale, 0.0, 0.0, self.scale, 0.0, 0.0) .map_err(|_| { Error::msg("Can't set transformation parameter to the Canvas 2D Context!") })?; */ ctx.clear_rect( 0.0, 0.0, self.real_width * self.scale, self.real_height * self.scale, ); Ok(()) } } #[derive(Deref, DerefMut, Default)] pub struct DrawCanvas { canvas: SmartCanvas, } impl DrawCanvas { #[allow(clippy::too_many_arguments)] pub fn draw_charts( &mut self, secs: i64, mut from_color: usize, min: f32, max: f32, x_formatter: &dyn Fn(&i64) -> String, y_formatter: &dyn Fn(&f32) -> String, data: &[Vec<(i64, f32)>], ) -> Result<(), Error> { from_color += 5; let canvas = self.canvas.canvas()?.clone(); let root_area = CanvasBackend::with_canvas_object(canvas) .ok_or_else(|| Error::msg("no canvas backend created"))? .into_drawing_area(); let mut ctx = ChartBuilder::on(&root_area) .set_label_area_size(LabelAreaPosition::Left, 40) .set_label_area_size(LabelAreaPosition::Bottom, 40) .margin(60) .build_cartesian_2d((-secs * 1_000)..0, min..max)?; ctx.configure_mesh() .light_line_style(&RGBColor(0xF8, 0xF9, 0xFA)) .label_style(("Jost", 26)) .x_label_formatter(x_formatter) .y_label_formatter(y_formatter) .draw()?; let single = data.len() == 1; for (col, line) in data.iter().enumerate() { let area_color; let line_color; if single { area_color = RGBColor(0xD2, 0x09, 0x09).mix(0.2).to_rgba(); line_color = RGBColor(0x42, 0x11, 0xCC).mix(1.0).to_rgba(); } else { line_color = Palette99::pick(from_color + col).to_rgba(); area_color = line_color.mix(0.2).to_rgba(); } let line = line.iter().cloned(); let series = AreaSeries::new(line, 0.0, &area_color).border_style(&line_color); ctx.draw_series(series)?; } Ok(()) } } pub fn sustain<Y: Copy>(mut iter: impl Iterato
((last_x, prev_y)); } result } /* pub fn sustain_soft<Y: Copy>( mut iter: impl Iterator<Item = (i64, Y)>, last: Option<i64>, ) -> Vec<(i64, Y)> { let mut result = Vec::new(); if let Some((mut prev_x, mut prev_y)) = iter.next() { result.push((prev_x, prev_y)); for (next_x, next_y) in iter { let diff = ((next_x - prev_x) as f32 * 0.2) as i64; result.push((next_x - diff, prev_y)); result.push((next_x, next_y)); prev_x = next_x; prev_y = next_y; } if let Some(last_x) = last { result.push((last_x, prev_y)); } } result } pub fn sustain_sharp<X: Copy, Y: Copy>( mut iter: impl Iterator<Item = (X, Y)>, last: Option<X>, ) -> Vec<(X, Y)> { let mut result = Vec::new(); if let Some((prev_x, mut prev_y)) = iter.next() { result.push((prev_x, prev_y)); for (next_x, next_y) in iter { result.push((next_x, prev_y)); result.push((next_x, next_y)); //prev_x = next_x; prev_y = next_y; } if let Some(last_x) = last { result.push((last_x, prev_y)); } } result } */ pub fn formatter_plain(input: &f32) -> String { input.to_string() } /* pub fn formatter_pct(input: &f32) -> String { format!("{:.0} %", input) } */ /* pub fn formatter_kib(input: &f32) -> String { format!("{:.0} KiB/s", input / 1_024.0) } pub fn formatter_gb(input: &f32) -> String { format!("{:.0} Gb", input / 1_000_000.0) } */ pub fn formatter_sec(input: &i64) -> String { let input = input.abs(); format!("{} sec", input / 1_000) /* if input % 60_000 == 0 { format!("{} min", input / 60_000) } else { format!("{} sec", input / 1_000) } */ }
r<Item = (i64, Y)>, last_x: i64) -> Vec<(i64, Y)> { let mut result = Vec::new(); if let Some((mut prev_x, mut prev_y)) = iter.next() { result.push((prev_x, prev_y)); for (next_x, next_y) in iter { let diff = next_x - prev_x; let shift = (diff as f32 * 0.1) as i64; result.push((next_x - shift, prev_y)); result.push((next_x, next_y)); prev_x = next_x; prev_y = next_y; } result.push
function_block-random_span
[]
Rust
src/env.rs
sezaru/rust-rocks
06245eedaf91b8358688abefa67eba802b607142
use lazy_static::lazy_static; use std::ffi::CStr; use std::mem; use std::path::Path; use std::ptr; use std::str; use rocks_sys as ll; use crate::thread_status::ThreadStatus; use crate::to_raw::{FromRaw, ToRaw}; use crate::{Error, Result}; pub const DEFAULT_PAGE_SIZE: usize = 4 * 1024; lazy_static! { static ref DEFAULT_ENVOPTIONS: EnvOptions = EnvOptions::default(); static ref DEFAULT_ENV: Env = { Env { raw: unsafe { ll::rocks_create_default_env() }, } }; } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Priority { Low, High, Total, } pub struct EnvOptions { raw: *mut ll::rocks_envoptions_t, } impl Drop for EnvOptions { fn drop(&mut self) { unsafe { ll::rocks_envoptions_destroy(self.raw) } } } impl ToRaw<ll::rocks_envoptions_t> for EnvOptions { fn raw(&self) -> *mut ll::rocks_envoptions_t { self.raw } } impl Default for EnvOptions { fn default() -> Self { EnvOptions { raw: unsafe { ll::rocks_envoptions_create() }, } } } unsafe impl Sync for EnvOptions {} impl EnvOptions { pub fn default_instance() -> &'static EnvOptions { &*DEFAULT_ENVOPTIONS } pub fn use_mmap_reads(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_use_mmap_reads(self.raw, val as u8); } self } pub fn use_mmap_writes(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_use_mmap_writes(self.raw, val as u8); } self } pub fn use_direct_reads(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_use_direct_reads(self.raw, val as u8); } self } pub fn use_direct_writes(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_use_direct_writes(self.raw, val as u8); } self } pub fn allow_fallocate(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_allow_fallocate(self.raw, val as u8); } self } pub fn fd_cloexec(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_fd_cloexec(self.raw, val as u8); } self } pub fn bytes_per_sync(self, val: u64) -> Self { unsafe { ll::rocks_envoptions_set_bytes_per_sync(self.raw, val); } self } pub fn fallocate_with_keep_size(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_fallocate_with_keep_size(self.raw, val as u8); } self } pub fn compaction_readahead_size(self, val: usize) -> Self { unsafe { ll::rocks_envoptions_set_compaction_readahead_size(self.raw, val); } self } pub fn random_access_max_buffer_size(self, val: usize) -> Self { unsafe { ll::rocks_envoptions_set_random_access_max_buffer_size(self.raw, val); } self } pub fn writable_file_max_buffer_size(self, val: usize) -> Self { unsafe { ll::rocks_envoptions_set_writable_file_max_buffer_size(self.raw, val); } self } } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum InfoLogLevel { Debug = 0, Info, Warn, Error, Fatal, Header, } #[derive(Debug)] pub struct Logger { raw: *mut ll::rocks_logger_t, } impl ToRaw<ll::rocks_logger_t> for Logger { fn raw(&self) -> *mut ll::rocks_logger_t { self.raw } } impl Drop for Logger { fn drop(&mut self) { unsafe { ll::rocks_logger_destroy(self.raw); } } } impl Logger { unsafe fn from_ll(raw: *mut ll::rocks_logger_t) -> Logger { Logger { raw: raw } } pub fn log(&self, log_level: InfoLogLevel, msg: &str) { unsafe { ll::rocks_logger_log(self.raw, mem::transmute(log_level), msg.as_ptr() as *const _, msg.len()); } } pub fn flush(&self) { unsafe { ll::rocks_logger_flush(self.raw); } } pub fn get_log_level(&self) -> InfoLogLevel { unsafe { mem::transmute(ll::rocks_logger_get_log_level(self.raw)) } } pub fn set_log_level(&mut self, log_level: InfoLogLevel) { unsafe { ll::rocks_logger_set_log_level(self.raw, mem::transmute(log_level)); } } } pub struct Env { raw: *mut ll::rocks_env_t, } impl ToRaw<ll::rocks_env_t> for Env { fn raw(&self) -> *mut ll::rocks_env_t { self.raw } } impl Drop for Env { fn drop(&mut self) { unsafe { ll::rocks_env_destroy(self.raw) } } } unsafe impl Sync for Env {} impl Env { pub fn default_instance() -> &'static Env { &*DEFAULT_ENV } pub fn new_mem() -> Env { Env { raw: unsafe { ll::rocks_create_mem_env() }, } } pub fn new_timed() -> Env { Env { raw: unsafe { ll::rocks_create_timed_env() }, } } pub fn set_low_priority_background_threads(&self, number: i32) { unsafe { ll::rocks_env_set_background_threads(self.raw, number); } } pub fn set_high_priority_background_threads(&self, number: i32) { unsafe { ll::rocks_env_set_high_priority_background_threads(self.raw, number); } } pub fn wait_for_join(&self) { unsafe { ll::rocks_env_join_all_threads(self.raw); } } pub fn get_thread_pool_queue_len(&self, pri: Priority) -> u32 { unsafe { ll::rocks_env_get_thread_pool_queue_len(self.raw, mem::transmute(pri)) as u32 } } pub fn create_logger<P: AsRef<Path>>(&self, fname: P) -> Result<Logger> { let mut status = ptr::null_mut(); unsafe { let name = fname.as_ref().to_str().unwrap(); let logger = ll::rocks_env_new_logger(self.raw, name.as_ptr() as *const _, name.len(), &mut status); Error::from_ll(status).map(|_| Logger::from_ll(logger)) } } pub fn now_micros(&self) -> u64 { unsafe { ll::rocks_env_now_micros(self.raw) as u64 } } pub fn now_nanos(&self) -> u64 { unsafe { ll::rocks_env_now_nanos(self.raw) as u64 } } pub fn sleep_for_microseconds(&self, micros: i32) { unsafe { ll::rocks_env_sleep_for_microseconds(self.raw, micros); } } pub fn get_hostname(&self) -> Result<String> { let mut buf = [0u8; 128]; let mut status = ptr::null_mut(); unsafe { ll::rocks_env_get_host_name(self.raw, (&mut buf).as_mut_ptr() as *mut _, 128, &mut status); Error::from_ll(status).map(|_| CStr::from_ptr(buf[..].as_ptr() as _).to_string_lossy().to_string()) } } pub fn get_current_time(&self) -> Result<u64> { let mut status = ptr::null_mut(); unsafe { let tm = ll::rocks_env_get_current_time(self.raw, &mut status); Error::from_ll(status).map(|()| tm as u64) } } pub fn time_to_string(&self, time: u64) -> String { unsafe { let cxx_string = ll::rocks_env_time_to_string(self.raw, time); let ret = CStr::from_ptr(ll::cxx_string_data(cxx_string) as *const _) .to_str() .unwrap() .into(); ll::cxx_string_destroy(cxx_string); ret } } pub fn set_background_threads(&self, number: i32, pri: Priority) { match pri { Priority::Low => self.set_low_priority_background_threads(number), Priority::High => self.set_high_priority_background_threads(number), _ => unreachable!("wrong pri for thread pool"), } } pub fn get_background_threads(&self, pri: Priority) -> i32 { unsafe { ll::rocks_env_get_background_threads(self.raw, mem::transmute(pri)) as i32 } } pub fn inc_background_threads_if_needed(&self, number: i32, pri: Priority) { unsafe { ll::rocks_env_inc_background_threads_if_needed(self.raw, number, mem::transmute(pri)); } } pub fn lower_thread_pool_io_priority(&self, pool: Priority) { unsafe { ll::rocks_env_lower_thread_pool_io_priority(self.raw, mem::transmute(pool)); } } pub fn get_thread_list(&self) -> Vec<ThreadStatus> { let mut len = 0; unsafe { let thread_status_arr = ll::rocks_env_get_thread_list(self.raw, &mut len); let ret = (0..len) .into_iter() .map(|i| ThreadStatus::from_ll(*thread_status_arr.offset(i as isize))) .collect(); ll::rocks_env_get_thread_list_destroy(thread_status_arr); ret } } pub fn get_thread_id(&self) -> u64 { unsafe { ll::rocks_env_get_thread_id(self.raw) as u64 } } } #[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::prelude::*; #[test] fn env_basic() { let env = Env::default_instance(); assert!(env.get_thread_id() > 0); assert!(env.now_micros() > 1500000000000000); assert!(env.get_hostname().is_ok()); assert!(env.get_current_time().is_ok()); assert!(env.time_to_string(env.get_current_time().unwrap()).len() > 10); } #[test] fn logger() { let log_dir = ::tempdir::TempDir::new_in(".", "log").unwrap(); let env = Env::default_instance(); { let logger = env.create_logger(log_dir.path().join("test.log")); assert!(logger.is_ok()); let mut logger = logger.unwrap(); logger.set_log_level(InfoLogLevel::Info); assert_eq!(logger.get_log_level(), InfoLogLevel::Info); logger.log(InfoLogLevel::Error, "test log message"); logger.log(InfoLogLevel::Debug, "debug log message"); logger.flush(); } let mut f = File::open(log_dir.path().join("test.log")).unwrap(); let mut s = String::new(); f.read_to_string(&mut s).unwrap(); assert!(s.contains("[ERROR] test log message")); assert!(!s.contains("debug log message")); } }
use lazy_static::lazy_static; use std::ffi::CStr; use std::mem; use std::path::Path; use std::ptr; use std::str; use rocks_sys as ll; use crate::thread_status::ThreadStatus; use crate::to_raw::{FromRaw, ToRaw}; use crate::{Error, Result}; pub const DEFAULT_PAGE_SIZE: usize = 4 * 1024; lazy_static! { static ref DEFAULT_ENVOPTIONS: EnvOptions = EnvOptions::default(); static ref DEFAULT_ENV: Env = { Env { raw: unsafe { ll::rocks_create_default_env() }, } }; } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Priority { Low, High, Total, } pub struct EnvOptions { raw: *mut ll::rocks_envoptions_t, } impl Drop for EnvOptions { fn drop(&mut self) { unsafe { ll::rocks_envoptions_destroy(self.raw) } } } impl ToRaw<ll::rocks_envoptions_t> for EnvOptions { fn raw(&self) -> *mut ll::rocks_envoptions_t { self.raw } } impl Default for EnvOptions { fn default() -> Self { EnvOptions { raw: unsafe { ll::rocks_envoptions_create() }, } } } unsafe impl Sync for EnvOptions {} impl EnvOptions { pub fn default_instance() -> &'static EnvOptions { &*DEFAULT_ENVOPTIONS } pub fn use_mmap_reads(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_use_mmap_reads(self.raw, val as u8); } self } pub fn use_mmap_writes(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_use_mmap_writes(self.raw, val as u8); } self } pub fn use_direct_reads(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_use_direct_reads(self.raw, val as u8); } self } pub fn use_direct_writes(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_use_direct_writes(self.raw, val as u8); } self } pub fn allow_fallocate(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_allow_fallocate(self.raw, val as u8); } self } pub fn fd_cloexec(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_fd_cloexec(self.raw, val as u8); } self } pub fn bytes_per_sync(self, val: u64) -> Self { unsafe { ll::rocks_envoptions_set_bytes_per_sync(self.raw, val); } self } pub fn fallocate_with_keep_size(self, val: bool) -> Self { unsafe { ll::rocks_envoptions_set_fallocate_with_keep_size(self.raw, val as u8); } self } pub fn compaction_readahead_size(self, val: usize) -> Self { unsafe { ll::rocks_envoptions_set_compaction_readahead_size(self.raw, val); } self } pub fn random_access_max_buffer_size(self, val: usize) -> Self { unsafe { ll::rocks_envoptions_set_random_access_max_buffer_size(self.raw, val); } self } pub fn writable_file_max_buffer_size(self, val: usize) -> Self { unsafe { ll::rocks_envoptions_set_writable_file_max_buffer_size(self.raw, val); } self } } #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum InfoLogLevel { Debug = 0, Info, Warn, Error, Fatal, Header, } #[derive(Debug)] pub struct Logger { raw: *mut ll::rocks_logger_t, } impl ToRaw<ll::rocks_logger_t> for Logger { fn raw(&self) -> *mut ll::rocks_logger_t { self.raw } } impl Drop for Logger { fn drop(&mut self) { unsafe { ll::rocks_logger_destroy(self.raw); } } } impl Logger { unsafe fn from_ll(raw: *mut ll::rocks_logger_t) -> Logger { Logger { raw: raw } } pub fn log(&self, log_level: InfoLogLevel, msg: &str) { unsafe { ll::rocks_logger_log(self.raw, mem::transmute(log_level), msg.as_ptr() as *const _, msg.len()); } } pub fn flush(&self) { unsafe { ll::rocks_logger_flush(self.raw); } } pub fn get_log_level(&self) -> InfoLogLevel { unsafe { mem::transmute(ll::rocks_logger_get_log_level(self.raw)) } } pub fn set_log_level(&mut self, log_level: InfoLogLevel) { unsafe { ll::rocks_logger_set_log_level(self.raw, mem::transmute(log_level)); } } } pub struct Env { raw: *mut ll::rocks_env_t, } impl ToRaw<ll::rocks_env_t> for Env { fn raw(&self) -> *mut ll::rocks_env_t { self.raw } } impl Drop for Env { fn drop(&mut self) { unsafe { ll::rocks_env_destroy(self.raw) } } } unsafe impl Sync for Env {} impl Env { pub fn default_instance() -> &'static Env { &*DEFAULT_ENV } pub fn new_mem() -> Env { Env { raw: unsafe { ll::rocks_create_mem_env() }, } } pub fn new_timed() -> Env { Env { raw: unsafe { ll::rocks_create_timed_env() }, } } pub fn set_low_priority_background_threads(&self, number: i32) { unsafe { ll::rocks_env_set_background_threads(self.raw, number); } } pub fn set_high_priority_background_threads(&self, number: i32) { unsafe { ll::rocks_env_set_high_priority_background_threads(self.raw, number); } } pub fn wait_for_join(&self) { unsafe { ll::rocks_env_join_all_threads(self.raw); } } pub fn get_thread_pool_queue_len(&self, pri: Priority) -> u32 { unsafe { ll::rocks_env_get_thread_pool_queue_len(self.raw, mem::transmute(pri)) as u32 } } pub fn create_logger<P: AsRef<Path>>(&self, fname: P) -> Result<Logger> { let mut status = ptr::null_mut(); unsafe { let name = fname.as_ref().to_str().unwrap(); let logger = ll::rocks_env_new_logger(self.raw, name.as_ptr() as *const _, name.len(), &mut status); Error::from_ll(status).map(|_| Logger::from_ll(logger)) } } pub fn now_micros(&self) -> u64 { unsafe { ll::rocks_env_now_micros(self.raw) as u64 } } pub fn now_nanos(&self) -> u64 { unsafe { ll::rocks_env_now_nanos(self.raw) as u64 } } pub fn sleep_for_microseconds(&self, micros: i32) { unsafe { ll::rocks_env_sleep_for_microseconds(self.raw, micros); } } pub fn get_hostname(&self) -> Result<String> { let mut buf = [0u8; 128]; let mut status = ptr::null_mut(); unsafe { ll::rocks_env_get_host_name(self.raw, (&mut buf).as_mut_ptr() as *mut _, 128, &mut status); Error::from_ll(status).map(|_| CStr::from_ptr(buf[..].as_ptr() as _).to_string_lossy().to_string()) } } pub fn get_current_time(&self) -> Result<u64> { let mut status = ptr::null_mut(); unsafe { let tm = ll::rocks_env_get_current_time(self.raw, &mut status); Error::from_ll(status).map(|()| tm as u64) } } pub fn time_to_string(&self, time: u64) -> String { unsafe { let cxx_string = ll::rocks_env_time_to_string(self.raw, time); let ret = CStr::from_ptr(ll::cxx_string_data(cxx_string) as *const _) .to_str() .unwrap() .into(); ll::cxx_string_destroy(cxx_string); ret } } pub fn set_background_threads(&self, number: i32, pri: Priority) { match pri { Priority::Low => self.set_low_priority_background_threads(number), Priority::High => self.set_high_priority_background_threads(number), _ => unreachable!("wrong pri for thread pool"), } } pub fn get_background_threads(&self, pri: Priority) -> i32 { unsafe { ll::rocks_env_get_background_threads(self.raw, mem::transmute(pri)) as i32 } } pub fn inc_background_threads_if_needed(&self, number: i32, pri: Priority) { unsafe { ll::rocks_env_inc_background_threads_if_needed(self.raw, number, mem::transmute(pri)); } } pub fn lower_thread_pool_io_priority(&self, pool: Priority) { unsafe { ll::rocks_env_lower_thread_pool_io_priority(self.raw, mem::transmute(pool)); } } pub fn get_thread_list(&self) -> Vec<ThreadStatus> { let mut len = 0; unsafe { let thread_status_arr = ll::rocks_env_get_thread_list(self.raw, &mut len); let ret = (0..len) .into_iter() .map(|i| ThreadStatus::from_ll(*thread_status_arr.offset(i as isize))) .collect(); ll::rocks_env_get_thread_list_destroy(thread_status_arr); ret } } pub fn get_thread_id(&self) -> u64 { unsafe { ll::rocks_env_get_thread_id(self.raw) as u64 } } } #[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::prelude::*; #[test] fn env_basic() { let env = Env::default_instance(); assert!(env.get_thread_id() > 0); assert!(env.now_micros() > 1500000000000000); assert!(env.get_hostname().is_ok()); assert!(env.get_current_time().is_ok()); assert!(env.time_to_string(env.get_current_time().unwrap()).len() > 10); } #[test] fn logger() { let log_dir = ::tempdir::TempDir::new_in(".", "log").unwrap(); let env = Env::default_instance(); { let logger = env.create_logger(log_dir.path().join
sage")); assert!(!s.contains("debug log message")); } }
("test.log")); assert!(logger.is_ok()); let mut logger = logger.unwrap(); logger.set_log_level(InfoLogLevel::Info); assert_eq!(logger.get_log_level(), InfoLogLevel::Info); logger.log(InfoLogLevel::Error, "test log message"); logger.log(InfoLogLevel::Debug, "debug log message"); logger.flush(); } let mut f = File::open(log_dir.path().join("test.log")).unwrap(); let mut s = String::new(); f.read_to_string(&mut s).unwrap(); assert!(s.contains("[ERROR] test log mes
function_block-random_span
[ { "content": "/// Destroy the contents of the specified database.\n\n///\n\n/// Be very careful using this method.\n\npub fn destroy_db<P: AsRef<Path>>(options: &Options, name: P) -> Result<()> {\n\n let name = name.as_ref().to_str().expect(\"valid utf8\");\n\n let mut status = ptr::null_mut();\n\n uns...
Rust
game-core/src/system/ally.rs
TheBlueSmoke/gameoff
b3619817c9c2af750c0eda2fad3e441692852261
use amethyst::{ core::cgmath::{InnerSpace, Vector2}, core::Transform, ecs::{Entities, Join, Read, ReadStorage, System, WriteStorage}, renderer::{SpriteRender, Transparent}, }; use config::GameoffConfig; use crate::component::{Ally, Animation, Motion, Player}; use rand::distributions::{Distribution, Uniform}; pub struct Movement; impl<'s> System<'s> for Movement { type SystemData = ( ReadStorage<'s, Ally>, WriteStorage<'s, Motion>, ReadStorage<'s, Transform>, ReadStorage<'s, Player>, Read<'s, GameoffConfig>, Entities<'s>, ); fn run( &mut self, (allies, mut motions, transforms, players, config, entities): Self::SystemData, ) { let mut rng = rand::thread_rng(); let zero_distance_dist = Uniform::new(0.5, 1.0); let p_transform = { let (t, _) = (&transforms, &players) .join() .next() .expect("no player found"); (t.clone()) }; for (_, motion, transform1, entity1) in (&allies, &mut motions, &transforms, &entities).join() { let d = (p_transform.translation - transform1.translation).truncate(); let m = d.magnitude().abs(); let mut pv = d.normalize(); if m < config.ally.follow_distance { pv *= 0.0; } else if (m > config.ally.follow_distance) && (m < config.ally.max_distance) { pv *= (1.0 + (m - config.ally.follow_distance) / (config.ally.max_distance - config.ally.follow_distance)) * config.speed; } else if m > config.ally.max_distance { pv *= 2.0 * config.speed; } let mut av = Vector2::new(0.0, 0.0); for (_, transform2, entity2) in (&allies, &transforms, &entities).join() { if entity1 != entity2 { let d = (transform1.translation - transform2.translation).truncate(); let m = d.magnitude().abs(); let mut v = if m == 0.0 { Vector2::new( zero_distance_dist.sample(&mut rng), zero_distance_dist.sample(&mut rng), ).normalize() } else { d.normalize() }; if m < config.ally.min_distance { v *= (config.ally.min_distance - m) / config.ally.min_distance * 5.0 * config.speed; } else if (m > config.ally.follow_distance) && (m < config.ally.max_distance) { v *= ((m - config.ally.follow_distance) / (config.ally.max_distance - config.ally.follow_distance)) * config.speed; } av += v; } } motion.vel = pv + av; } } } pub struct Grouper; impl<'s> System<'s> for Grouper { type SystemData = ( ReadStorage<'s, Ally>, ReadStorage<'s, Transform>, WriteStorage<'s, Motion>, ReadStorage<'s, Player>, Entities<'s>, ); fn run(&mut self, (allies, transforms, mut motions, players, entities): Self::SystemData) { let p_transform = { let (t, _) = (&transforms, &players) .join() .next() .expect("no player found"); (t.clone()) }; let mut merged = vec![]; for (_ally, transform, e, _) in (&allies, &transforms, &*entities, !&motions).join() { let d = p_transform.translation - transform.translation; let m = d.truncate().magnitude(); let merge_dist = 32.0 * 1.0; if m < merge_dist { merged.push(e); } } for entity in merged { let _ = motions.insert(entity, Motion::default()); } } } pub struct Spawner; impl<'s> System<'s> for Spawner { type SystemData = ( ReadStorage<'s, Player>, ReadStorage<'s, Motion>, Read<'s, crate::load::LoadedTextures>, WriteStorage<'s, Transform>, WriteStorage<'s, Ally>, WriteStorage<'s, SpriteRender>, WriteStorage<'s, Transparent>, Entities<'s>, WriteStorage<'s, Animation>, ); fn run( &mut self, ( players, motions, textures, mut transforms, mut allies, mut sprites, mut transparent, entities, mut animation, ): Self::SystemData, ) { let count = (&allies, !&motions).join().count(); if count < 5 { let mut ally_positions = vec![]; let range = Uniform::new_inclusive(-5.0 * 32.0, 5.0 * 32.0); let mut rng = rand::thread_rng(); for (_, transform) in (&players, &mut transforms).join() { let mut pos = Transform::default(); pos.scale.x = 0.5; pos.scale.y = 0.5; pos.translation.x = transform.translation.x + range.sample(&mut rng); pos.translation.y = transform.translation.y + range.sample(&mut rng); ally_positions.push(pos); } for pos in ally_positions { let sprite = SpriteRender { sprite_sheet: textures.textures["FRONT.png"].clone(), sprite_number: 1, flip_horizontal: false, flip_vertical: false, }; let anim = Animation { total_frames: 8, max_count_till_next_frame: 0.1, frame_life_time_count: 0.1, current_frame: 0, }; entities .build_entity() .with(pos, &mut transforms) .with(Ally::default(), &mut allies) .with(sprite, &mut sprites) .with(Transparent, &mut transparent) .with(anim, &mut animation) .build(); } } } }
use amethyst::{ core::cgmath::{InnerSpace, Vector2}, core::Transform, ecs::{Entities, Join, Read, ReadStorage, System, WriteStorage}, renderer::{SpriteRender, Transparent}, }; use config::GameoffConfig; use crate::component::{Ally, Animation, Motion, Player}; use rand::distributions::{Distribution, Uniform}; pub struct Movement; impl<'s> System<'s> for Movement { type SystemData = ( ReadStorage<'s, Ally>, WriteStorage<'s, Motion>, ReadStorage<'s, Transform>, ReadStorage<'s, Player>, Read<'s, GameoffConfig>, Entities<'s>, ); fn run( &mut self, (allies, mut motions, transforms, players, config, entities): Self::SystemData, ) { let mut rng = rand::thread_rng(); let zero_distance_dist = Uniform::new(0.5, 1.0); let p_transform = { let (t, _) = (&transforms, &players) .join() .next() .expect("no player found"); (t.clone()) }; for (_, motion, transform1, entity1) in (&allies, &mut motions, &transforms, &entities).join() { let d = (p_transform.translation - transform1.translation).truncate(); let m = d.magnitude().abs(); let mut pv = d.normalize(); if m < config.ally.follow_distance { pv *= 0.0; } else if (m > config.ally.follow_distance) && (m < config.ally.max_distance) { pv *= (1.0 + (m - config.ally.follow_distance) / (config.ally.max_distance - config.ally.follow_distance)) * config.speed; } else if m > config.ally.max_distance { pv *= 2.0 * config.speed; } let mut av = Vector2::new(0.0, 0.0); for (_, transform2, entity2) in (&allies, &transforms, &entities).join() { if entity1 != entity2 { let d = (transform1.translation - transform2.translation).truncate(); let m = d.magnitude().abs(); let mut v = if m == 0.0 { Vector2::new( zero_distance_dist.sample(&mut rng), zero_distance_dist.sample(&mut rng), ).normalize() } else { d.normalize() }; if m < config.ally.min_distance { v *= (config.ally.min_distance - m) / config.ally.min_distance * 5.0 * config.speed; } else if (m > config.ally.follow_distance) && (m < config.ally.max_distance) { v *= ((m - config.ally.follow_distance) / (config.ally.max_distance - config.ally.follow_distance)) * config.speed; } av += v; } } motion.vel = pv + av; } } } pub struct Grouper; impl<'s> System<'s> for Grouper { type SystemData = ( ReadStorage<'s, Ally>, ReadStorage<'s, Transform>, WriteStorage<'s, Motion>, ReadStorage<'s, Player>, Entities<'s>, ); fn run(&mut self, (allies, transforms, mut motions, players, entities): Self::SystemData) { let p_transform = { let (t, _) = (&transforms, &players) .join() .next() .expect("no player found"); (t.clone()) }; let mut merged = vec![]; for (_ally, transform, e, _) in (&allies, &transforms, &*entities, !&motions).join() { let d = p_transform.translation - transform.translation; let m = d.truncate().magnitude(); let merge_dist = 32.0 * 1.0; if m < merge_dist { merged.push(e); } } for entity in merged { let _ = motions.insert(entity, Motion::default()); } } } pub struct Spawner; impl<'s> System<'s> for Spawner { type SystemData = ( ReadStorage<'s, Player>, ReadStorage<'s, Motion>, Read<'s, crate::load::LoadedTextures>, WriteStorage<'s, Transform>, WriteStorage<'s, Ally>, WriteStorage<'s, SpriteRender>, WriteStorage<'s, Transparent>, Entities<'s>, WriteStorage<'s, Animation>, ); fn run( &mut self, ( players, motions, textures, mut transforms, mut allies, mut sprites, mut transparent, entities, mut animation, ): Self::SystemData, ) { let count = (&allies, !&motions).join().count(); if count < 5 { let mut ally_positions = vec![]; let range = Uniform::new_inclusive(-5.0 * 32.0, 5.0 * 32.0); let mut rng = rand::thread_rng(); for (_, transform) in (&players, &mut transforms).join() { let mut pos = Transform::default(); pos.scale.x = 0.5; pos.scale.y = 0.5; pos.translation.x = transform.translation.x + range.sample(&mut rng); pos.translation.y = transform.translation.y + range.sample(&mut rng);
priteRender { sprite_sheet: textures.textures["FRONT.png"].clone(), sprite_number: 1, flip_horizontal: false, flip_vertical: false, }; let anim = Animation { total_frames: 8, max_count_till_next_frame: 0.1, frame_life_time_count: 0.1, current_frame: 0, }; entities .build_entity() .with(pos, &mut transforms) .with(Ally::default(), &mut allies) .with(sprite, &mut sprites) .with(Transparent, &mut transparent) .with(anim, &mut animation) .build(); } } } }
ally_positions.push(pos); } for pos in ally_positions { let sprite = S
function_block-random_span
[ { "content": "pub fn run() -> amethyst::Result<()> {\n\n let root = format!(\"{}/resources\", application_root_dir());\n\n let display_config = DisplayConfig::load(format!(\"{}/display_config.ron\", root));\n\n let gameoff_config = config::GameoffConfig::load(format!(\"{}/config.ron\", root));\n\n l...
Rust
examples/demo.rs
alvinhochun/conrod_floatwin
c29c2668bdc4408fce802bd5cc6e44ef05dd82b2
use conrod_core::{ widget, widget_ids, Borderable, Colorable, Labelable, Positionable, Sizeable, Widget, }; use conrod_floatwin::windowing_area::{ layout::{WinId, WindowingState}, WindowBuilder, WindowingArea, WindowingContext, }; use glium::Surface; mod support; fn main() { const WIDTH: u32 = 800; const HEIGHT: u32 = 600; let mut events_loop = glium::glutin::EventsLoop::new(); let window = glium::glutin::WindowBuilder::new() .with_title("conrod_floatwin demo") .with_dimensions((WIDTH, HEIGHT).into()); let context = glium::glutin::ContextBuilder::new() .with_vsync(true) .with_multisampling(4); let display = glium::Display::new(window, context, &events_loop).unwrap(); let display = support::GliumDisplayWinitWrapper(display); let mut current_hidpi_factor = display.0.gl_window().get_hidpi_factor(); let mut ui = conrod_core::UiBuilder::new([WIDTH as f64, HEIGHT as f64]).build(); let font_path = "./assets/fonts/NotoSans/NotoSans-Regular.ttf"; ui.fonts.insert_from_file(font_path).unwrap(); let mut renderer = conrod_glium::Renderer::new(&display.0).unwrap(); let image_map = conrod_core::image::Map::<glium::texture::Texture2d>::new(); let ids = &mut Ids::new(ui.widget_id_generator()); let mut win_state = WindowingState::new(); let win_ids = WinIds { test1: win_state.next_id(), test2: win_state.next_id(), }; let mut ui_state = UiState { enable_debug: false, win_state, win_ids, array_wins: vec![], reusable_win_ids: vec![], next_array_win_idx: 1, hide_test2: false, }; let mut event_loop = support::EventLoop::new(); 'main: loop { for event in event_loop.next(&mut events_loop) { if let Some(event) = support::convert_event(event.clone(), &display) { ui.handle_event(event); event_loop.needs_update(); } match event { glium::glutin::Event::WindowEvent { event, .. } => match event { glium::glutin::WindowEvent::CloseRequested | glium::glutin::WindowEvent::KeyboardInput { input: glium::glutin::KeyboardInput { virtual_keycode: Some(glium::glutin::VirtualKeyCode::Escape), .. }, .. } => break 'main, glium::glutin::WindowEvent::HiDpiFactorChanged(hidpi_factor) => { current_hidpi_factor = hidpi_factor; } glium::glutin::WindowEvent::KeyboardInput { input: glium::glutin::KeyboardInput { virtual_keycode: Some(glium::glutin::VirtualKeyCode::F11), state: glium::glutin::ElementState::Pressed, .. }, .. } => match display.0.gl_window().window().get_fullscreen() { Some(_) => display.0.gl_window().window().set_fullscreen(None), None => display.0.gl_window().window().set_fullscreen(Some( display.0.gl_window().window().get_current_monitor(), )), }, glium::glutin::WindowEvent::KeyboardInput { input: glium::glutin::KeyboardInput { virtual_keycode: Some(glium::glutin::VirtualKeyCode::F12), state: glium::glutin::ElementState::Pressed, .. }, .. } => ui_state.enable_debug = !ui_state.enable_debug, _ => (), }, _ => (), } } set_widgets(ui.set_widgets(), ids, current_hidpi_factor, &mut ui_state); display .0 .gl_window() .window() .set_cursor(support::convert_mouse_cursor(ui.mouse_cursor())); if let Some(primitives) = ui.draw_if_changed() { renderer.fill(&display.0, primitives, &image_map); let mut target = display.0.draw(); target.clear_color(0.0, 0.0, 0.0, 1.0); renderer.draw(&display.0, &mut target, &image_map).unwrap(); target.finish().unwrap(); } } } widget_ids! { struct Ids { backdrop, windowing_area, text, button, toggle, } } struct WinIds { test1: WinId, test2: WinId, } struct UiState { enable_debug: bool, win_state: WindowingState, win_ids: WinIds, array_wins: Vec<ArrayWinState>, reusable_win_ids: Vec<WinId>, next_array_win_idx: usize, hide_test2: bool, } struct ArrayWinState { index: usize, win_id: WinId, } fn set_widgets( ref mut ui: conrod_core::UiCell, ids: &mut Ids, hidpi_factor: f64, state: &mut UiState, ) { widget::Rectangle::fill(ui.window_dim()) .color(conrod_core::color::BLUE) .middle() .set(ids.backdrop, ui); let mut win_ctx: WindowingContext = WindowingArea::new(&mut state.win_state, hidpi_factor) .with_debug(state.enable_debug) .set(ids.windowing_area, ui); let builder = WindowBuilder::new() .title("Test1") .is_collapsible(false) .initial_position([100.0, 100.0]) .initial_size([150.0, 100.0]) .min_size([200.0, 50.0]); if let (_, Some(win)) = win_ctx.make_window(builder, state.win_ids.test1, ui) { let c = widget::Canvas::new() .border(0.0) .color(conrod_core::color::LIGHT_YELLOW) .scroll_kids(); let (container_id, _) = win.set(c, ui); widget::Text::new("Hello World!") .color(conrod_core::color::RED) .font_size(32) .parent(container_id) .set(ids.text, ui); let clicked = widget::Toggle::new(state.hide_test2) .label(if state.hide_test2 { "Test2:\nHidden" } else { "Test2:\nShown" }) .label_color(conrod_core::color::LIGHT_BLUE) .w_h(100.0, 50.0) .up(8.0) .parent(container_id) .set(ids.toggle, ui); state.hide_test2 = clicked.last().unwrap_or(state.hide_test2); } let mut add_win = 0; let builder = WindowBuilder::new() .title("Test2") .is_hidden(state.hide_test2) .initial_position([150.0, 150.0]) .initial_size([200.0, 200.0]); if let (_, Some(win)) = win_ctx.make_window(builder, state.win_ids.test2, ui) { let c = widget::Canvas::new() .border(0.0) .color(conrod_core::color::LIGHT_BLUE) .scroll_kids(); let (container_id, _) = win.set(c, ui); let clicks = widget::Button::new() .label("Click me") .w_h(100.0, 50.0) .middle_of(container_id) .parent(container_id) .set(ids.button, ui); for _ in clicks { println!("Clicked me!"); add_win += 1; } } let mut array_win_to_close = vec![]; for (i, array_win_state) in state.array_wins.iter().enumerate() { let title = format!("Test multi - {}", array_win_state.index); let builder = WindowBuilder::new() .title(&title) .is_closable(true) .initial_size([150.0, 100.0]); let (event, win) = win_ctx.make_window(builder, array_win_state.win_id, ui); if let Some(win) = win { let c = widget::Canvas::new() .border(0.0) .color(conrod_core::color::LIGHT_CHARCOAL) .scroll_kids(); let (_container_id, _) = win.set(c, ui); } if event.close_clicked.was_clicked() { array_win_to_close.push(i); } } std::mem::drop(win_ctx); while add_win > 0 { let win_state = &mut state.win_state; let win_id = state .reusable_win_ids .pop() .unwrap_or_else(|| win_state.next_id()); state.array_wins.push(ArrayWinState { index: state.next_array_win_idx, win_id, }); state.next_array_win_idx += 1; add_win -= 1; } for i in array_win_to_close.into_iter().rev() { let s = state.array_wins.swap_remove(i); state.reusable_win_ids.push(s.win_id); } }
use conrod_core::{ widget, widget_ids, Borderable, Colorable, Labelable, Positionable, Sizeable, Widget, }; use conrod_floatwin::windowing_area::{ layout::{WinId, WindowingState}, WindowBuilder, WindowingArea, WindowingContext, }; use glium::Surface; mod support; fn main() { const WIDTH: u32 = 800; const HEIGHT: u32 = 600; let mut events_loop = glium::glutin::EventsLoop::new();
let context = glium::glutin::ContextBuilder::new() .with_vsync(true) .with_multisampling(4); let display = glium::Display::new(window, context, &events_loop).unwrap(); let display = support::GliumDisplayWinitWrapper(display); let mut current_hidpi_factor = display.0.gl_window().get_hidpi_factor(); let mut ui = conrod_core::UiBuilder::new([WIDTH as f64, HEIGHT as f64]).build(); let font_path = "./assets/fonts/NotoSans/NotoSans-Regular.ttf"; ui.fonts.insert_from_file(font_path).unwrap(); let mut renderer = conrod_glium::Renderer::new(&display.0).unwrap(); let image_map = conrod_core::image::Map::<glium::texture::Texture2d>::new(); let ids = &mut Ids::new(ui.widget_id_generator()); let mut win_state = WindowingState::new(); let win_ids = WinIds { test1: win_state.next_id(), test2: win_state.next_id(), }; let mut ui_state = UiState { enable_debug: false, win_state, win_ids, array_wins: vec![], reusable_win_ids: vec![], next_array_win_idx: 1, hide_test2: false, }; let mut event_loop = support::EventLoop::new(); 'main: loop { for event in event_loop.next(&mut events_loop) { if let Some(event) = support::convert_event(event.clone(), &display) { ui.handle_event(event); event_loop.needs_update(); } match event { glium::glutin::Event::WindowEvent { event, .. } => match event { glium::glutin::WindowEvent::CloseRequested | glium::glutin::WindowEvent::KeyboardInput { input: glium::glutin::KeyboardInput { virtual_keycode: Some(glium::glutin::VirtualKeyCode::Escape), .. }, .. } => break 'main, glium::glutin::WindowEvent::HiDpiFactorChanged(hidpi_factor) => { current_hidpi_factor = hidpi_factor; } glium::glutin::WindowEvent::KeyboardInput { input: glium::glutin::KeyboardInput { virtual_keycode: Some(glium::glutin::VirtualKeyCode::F11), state: glium::glutin::ElementState::Pressed, .. }, .. } => match display.0.gl_window().window().get_fullscreen() { Some(_) => display.0.gl_window().window().set_fullscreen(None), None => display.0.gl_window().window().set_fullscreen(Some( display.0.gl_window().window().get_current_monitor(), )), }, glium::glutin::WindowEvent::KeyboardInput { input: glium::glutin::KeyboardInput { virtual_keycode: Some(glium::glutin::VirtualKeyCode::F12), state: glium::glutin::ElementState::Pressed, .. }, .. } => ui_state.enable_debug = !ui_state.enable_debug, _ => (), }, _ => (), } } set_widgets(ui.set_widgets(), ids, current_hidpi_factor, &mut ui_state); display .0 .gl_window() .window() .set_cursor(support::convert_mouse_cursor(ui.mouse_cursor())); if let Some(primitives) = ui.draw_if_changed() { renderer.fill(&display.0, primitives, &image_map); let mut target = display.0.draw(); target.clear_color(0.0, 0.0, 0.0, 1.0); renderer.draw(&display.0, &mut target, &image_map).unwrap(); target.finish().unwrap(); } } } widget_ids! { struct Ids { backdrop, windowing_area, text, button, toggle, } } struct WinIds { test1: WinId, test2: WinId, } struct UiState { enable_debug: bool, win_state: WindowingState, win_ids: WinIds, array_wins: Vec<ArrayWinState>, reusable_win_ids: Vec<WinId>, next_array_win_idx: usize, hide_test2: bool, } struct ArrayWinState { index: usize, win_id: WinId, } fn set_widgets( ref mut ui: conrod_core::UiCell, ids: &mut Ids, hidpi_factor: f64, state: &mut UiState, ) { widget::Rectangle::fill(ui.window_dim()) .color(conrod_core::color::BLUE) .middle() .set(ids.backdrop, ui); let mut win_ctx: WindowingContext = WindowingArea::new(&mut state.win_state, hidpi_factor) .with_debug(state.enable_debug) .set(ids.windowing_area, ui); let builder = WindowBuilder::new() .title("Test1") .is_collapsible(false) .initial_position([100.0, 100.0]) .initial_size([150.0, 100.0]) .min_size([200.0, 50.0]); if let (_, Some(win)) = win_ctx.make_window(builder, state.win_ids.test1, ui) { let c = widget::Canvas::new() .border(0.0) .color(conrod_core::color::LIGHT_YELLOW) .scroll_kids(); let (container_id, _) = win.set(c, ui); widget::Text::new("Hello World!") .color(conrod_core::color::RED) .font_size(32) .parent(container_id) .set(ids.text, ui); let clicked = widget::Toggle::new(state.hide_test2) .label(if state.hide_test2 { "Test2:\nHidden" } else { "Test2:\nShown" }) .label_color(conrod_core::color::LIGHT_BLUE) .w_h(100.0, 50.0) .up(8.0) .parent(container_id) .set(ids.toggle, ui); state.hide_test2 = clicked.last().unwrap_or(state.hide_test2); } let mut add_win = 0; let builder = WindowBuilder::new() .title("Test2") .is_hidden(state.hide_test2) .initial_position([150.0, 150.0]) .initial_size([200.0, 200.0]); if let (_, Some(win)) = win_ctx.make_window(builder, state.win_ids.test2, ui) { let c = widget::Canvas::new() .border(0.0) .color(conrod_core::color::LIGHT_BLUE) .scroll_kids(); let (container_id, _) = win.set(c, ui); let clicks = widget::Button::new() .label("Click me") .w_h(100.0, 50.0) .middle_of(container_id) .parent(container_id) .set(ids.button, ui); for _ in clicks { println!("Clicked me!"); add_win += 1; } } let mut array_win_to_close = vec![]; for (i, array_win_state) in state.array_wins.iter().enumerate() { let title = format!("Test multi - {}", array_win_state.index); let builder = WindowBuilder::new() .title(&title) .is_closable(true) .initial_size([150.0, 100.0]); let (event, win) = win_ctx.make_window(builder, array_win_state.win_id, ui); if let Some(win) = win { let c = widget::Canvas::new() .border(0.0) .color(conrod_core::color::LIGHT_CHARCOAL) .scroll_kids(); let (_container_id, _) = win.set(c, ui); } if event.close_clicked.was_clicked() { array_win_to_close.push(i); } } std::mem::drop(win_ctx); while add_win > 0 { let win_state = &mut state.win_state; let win_id = state .reusable_win_ids .pop() .unwrap_or_else(|| win_state.next_id()); state.array_wins.push(ArrayWinState { index: state.next_array_win_idx, win_id, }); state.next_array_win_idx += 1; add_win -= 1; } for i in array_win_to_close.into_iter().rev() { let s = state.array_wins.swap_remove(i); state.reusable_win_ids.push(s.win_id); } }
let window = glium::glutin::WindowBuilder::new() .with_title("conrod_floatwin demo") .with_dimensions((WIDTH, HEIGHT).into());
assignment_statement
[ { "content": "#![allow(dead_code)]\n\n\n\nuse glium;\n\nuse std;\n\n\n\npub struct GliumDisplayWinitWrapper(pub glium::Display);\n\n\n\nimpl conrod_winit::WinitWindow for GliumDisplayWinitWrapper {\n\n fn get_inner_size(&self) -> Option<(u32, u32)> {\n\n self.0.gl_window().get_inner_size().map(Into::i...