file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
tensor.rs
use std::collections::HashSet; use std::io::{Read, Seek}; use std::ops::Range; use std::str::FromStr; use std::sync::Mutex; use crate::model::Model; use tract_hir::internal::*; #[derive(Debug, Default, Clone)] pub struct TensorsValues(pub Vec<TensorValues>); impl TensorsValues { pub fn by_name(&self, name: &str) -> Option<&TensorValues> { self.0.iter().find(|t| t.name.as_deref() == Some(name)) } pub fn by_name_mut(&mut self, name: &str) -> Option<&mut TensorValues> { self.0.iter_mut().find(|t| t.name.as_deref() == Some(name)) } pub fn by_name_mut_with_default(&mut self, name: &str) -> &mut TensorValues { if self.by_name_mut(name).is_none() { self.add(TensorValues { name: Some(name.to_string()),..TensorValues::default() }); } self.by_name_mut(name).unwrap() } pub fn by_input_ix(&self, ix: usize) -> Option<&TensorValues> { self.0.iter().find(|t| t.input_index == Some(ix)) } pub fn by_input_ix_mut(&mut self, ix: usize) -> Option<&mut TensorValues> { self.0.iter_mut().find(|t| t.input_index == Some(ix)) } pub fn by_input_ix_mut_with_default(&mut self, ix: usize) -> &mut TensorValues { if self.by_input_ix_mut(ix).is_none()
self.by_input_ix_mut(ix).unwrap() } pub fn add(&mut self, other: TensorValues) { let mut tensor = other.input_index.and_then(|ix| self.by_input_ix_mut(ix)); if tensor.is_none() { tensor = other.name.as_deref().and_then(|ix| self.by_name_mut(ix)) } if let Some(tensor) = tensor { if tensor.fact.is_none() { tensor.fact = other.fact; } if tensor.values.is_none() { tensor.values = other.values; } } else { self.0.push(other.clone()); }; } } #[derive(Debug, PartialEq, Clone, Default)] pub struct TensorValues { pub input_index: Option<usize>, pub output_index: Option<usize>, pub name: Option<String>, pub fact: Option<InferenceFact>, pub values: Option<Vec<TValue>>, pub random_range: Option<Range<f32>>, } fn parse_dt(dt: &str) -> TractResult<DatumType> { Ok(match dt.to_lowercase().as_ref() { "bool" => DatumType::Bool, "f16" => DatumType::F16, "f32" => DatumType::F32, "f64" => DatumType::F64, "i8" => DatumType::I8, "i16" => DatumType::I16, "i32" => DatumType::I32, "i64" => DatumType::I64, "u8" => DatumType::U8, "u16" => DatumType::U16, "u32" => DatumType::U32, "u64" => DatumType::U64, "tdim" => DatumType::TDim, _ => bail!( "Type of the input should be f16, f32, f64, i8, i16, i16, i32, u8, u16, u32, u64, TDim." ), }) } pub fn parse_spec(symbol_table: &SymbolTable, size: &str) -> TractResult<InferenceFact> { if size.is_empty() { return Ok(InferenceFact::default()); } parse_coma_spec(symbol_table, size) } pub fn parse_coma_spec(symbol_table: &SymbolTable, size: &str) -> TractResult<InferenceFact> { let splits = size.split(',').collect::<Vec<_>>(); if splits.is_empty() { // Hide '{' in this error message from the formatting machinery in bail macro let msg = "The <size> argument should be formatted as {size},{...},{type}."; bail!(msg); } let last = splits.last().unwrap(); let (datum_type, shape) = if let Ok(dt) = parse_dt(last) { (Some(dt), &splits[0..splits.len() - 1]) } else { (None, &*splits) }; let shape = ShapeFactoid::closed( shape .iter() .map(|&s| { Ok(if s == "_" { GenericFactoid::Any } else { GenericFactoid::Only(parse_tdim(symbol_table, s)?) }) }) .collect::<TractResult<TVec<DimFact>>>()?, ); if let Some(dt) = datum_type { Ok(InferenceFact::dt_shape(dt, shape)) } else { Ok(InferenceFact::shape(shape)) } } fn parse_values<T: Datum + FromStr>(shape: &[usize], it: Vec<&str>) -> TractResult<Tensor> { let values = it .into_iter() .map(|v| v.parse::<T>().map_err(|_| format_err!("Failed to parse {}", v))) .collect::<TractResult<Vec<T>>>()?; Ok(tract_ndarray::Array::from_shape_vec(shape, values)?.into()) } fn tensor_for_text_data( symbol_table: &SymbolTable, _filename: &str, mut reader: impl Read, ) -> TractResult<Tensor> { let mut data = String::new(); reader.read_to_string(&mut data)?; let mut lines = data.lines(); let proto = parse_spec(symbol_table, lines.next().context("Empty data file")?)?; let shape = proto.shape.concretize().unwrap(); let values = lines.flat_map(|l| l.split_whitespace()).collect::<Vec<&str>>(); // We know there is at most one streaming dimension, so we can deduce the // missing value with a simple division. let product: usize = shape.iter().map(|o| o.to_usize().unwrap_or(1)).product(); let missing = values.len() / product; let shape: Vec<_> = shape.iter().map(|d| d.to_usize().unwrap_or(missing)).collect(); dispatch_numbers!(parse_values(proto.datum_type.concretize().unwrap())(&*shape, values)) } /// Parses the `data` command-line argument. pub fn for_data( symbol_table: &SymbolTable, filename: &str, reader: impl Read + std::io::Seek, ) -> TractResult<(Option<String>, InferenceFact)> { #[allow(unused_imports)] use std::convert::TryFrom; if filename.ends_with(".pb") { #[cfg(feature = "onnx")] { /* let file = fs::File::open(filename).with_context(|| format!("Can't open {filename:?}"))?; */ let proto = ::tract_onnx::tensor::proto_from_reader(reader)?; Ok(( Some(proto.name.to_string()).filter(|s|!s.is_empty()), Tensor::try_from(proto)?.into(), )) } #[cfg(not(feature = "onnx"))] { panic!("Loading tensor from protobuf requires onnx features"); } } else if filename.contains(".npz:") { let mut tokens = filename.split(':'); let (_filename, inner) = (tokens.next().unwrap(), tokens.next().unwrap()); let mut npz = ndarray_npy::NpzReader::new(reader)?; Ok((None, for_npz(&mut npz, inner)?.into())) } else { Ok((None, tensor_for_text_data(symbol_table, filename, reader)?.into())) } } pub fn for_npz( npz: &mut ndarray_npy::NpzReader<impl Read + Seek>, name: &str, ) -> TractResult<Tensor> { if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<f32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<f64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i8>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i16>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u8>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u16>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<bool>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } bail!("Can not extract tensor from {}", name); } pub fn for_string( symbol_table: &SymbolTable, value: &str, ) -> TractResult<(Option<String>, InferenceFact)> { let (name, value) = if value.contains(':') { let mut splits = value.split(':'); (Some(splits.next().unwrap().to_string()), splits.next().unwrap()) } else { (None, value) }; if value.contains('=') { let mut split = value.split('='); let spec = parse_spec(symbol_table, split.next().unwrap())?; let value = split.next().unwrap().split(','); let dt = spec.datum_type.concretize().context("Must specify type when giving tensor value")?; let shape = spec .shape .as_concrete_finite()? .context("Must specify concrete shape when giving tensor value")?; let tensor = dispatch_numbers!(parse_values(dt)(&*shape, value.collect()))?; Ok((name, tensor.into())) } else { Ok((name, parse_spec(symbol_table, value)?)) } } lazy_static::lazy_static! { static ref WARNING_ONCE: Mutex<HashSet<String>> = Mutex::new(HashSet::new()); } fn warn_once(msg: String) { if WARNING_ONCE.lock().unwrap().insert(msg.clone()) { warn!("{}", msg); } } pub struct RunParams { pub tensors_values: TensorsValues, pub allow_random_input: bool, pub allow_float_casts: bool, } pub fn retrieve_or_make_inputs( tract: &dyn Model, params: &RunParams, ) -> TractResult<Vec<TVec<TValue>>> { let mut tmp: TVec<Vec<TValue>> = tvec![]; for (ix, input) in tract.input_outlets().iter().enumerate() { let name = tract.node_name(input.node); let fact = tract.outlet_typedfact(*input)?; if let Some(mut value) = params.tensors_values.by_name(name).and_then(|t| t.values.clone()) { if!value[0].datum_type().is_quantized() && fact.datum_type.is_quantized() && value[0].datum_type() == fact.datum_type.unquantized() { value = value .iter() .map(|v| { let mut v = v.clone().into_tensor(); unsafe { v.set_datum_type(fact.datum_type) }; v.into() }) .collect(); } if TypedFact::from(&*value[0]).compatible_with(&fact) { info!("Using fixed input for input called {} ({} turn(s))", name, value.len()); tmp.push(value.iter().map(|t| t.clone().into_tensor().into()).collect()) } else if fact.datum_type == f16::datum_type() && value[0].datum_type() == f32::datum_type() && params.allow_float_casts { tmp.push( value.iter().map(|t| t.cast_to::<f16>().unwrap().into_owned().into()).collect(), ) } else if value.len() == 1 && tract.properties().contains_key("pulse.delay") { let value = &value[0]; let input_pulse_axis = tract .properties() .get("pulse.input_axes") .context("Expect pulse.input_axes property")? .cast_to::<i64>()? .as_slice::<i64>()?[ix] as usize; let input_pulse = fact.shape.get(input_pulse_axis).unwrap().to_usize().unwrap(); let input_len = value.shape()[input_pulse_axis]; // how many pulses do we need to push full result out? // guess by looking at len and delay of the first output let output_pulse_axis = tract .properties() .get("pulse.output_axes") .context("Expect pulse.output_axes property")? .cast_to::<i64>()? .as_slice::<i64>()?[0] as usize; let output_fact = tract.outlet_typedfact(tract.output_outlets()[0])?; let output_pulse = output_fact.shape.get(output_pulse_axis).unwrap().to_usize().unwrap(); let output_len = input_len * output_pulse / input_pulse; let output_delay = tract.properties()["pulse.delay"].as_slice::<i64>()?[0] as usize; let last_frame = output_len + output_delay; let needed_pulses = last_frame.divceil(output_pulse); let mut values = vec![]; for ix in 0..needed_pulses { let mut t = Tensor::zero_dt(fact.datum_type, fact.shape.as_concrete().unwrap())?; let start = ix * input_pulse; let end = (start + input_pulse).min(input_len); if end > start { t.assign_slice(0..end - start, value, start..end, input_pulse_axis)?; } values.push(t.into()); } info!( "Generated {} pulses of shape {:?} for input {}.", needed_pulses, fact.shape, ix ); tmp.push(values); } else { bail!("For input {}, can not reconcile model input fact {:?} with provided input {:?}", name, fact, value[0]); }; } else if params.allow_random_input { let fact = tract.outlet_typedfact(*input)?; warn_once(format!("Using random input for input called {name:?}: {fact:?}")); let tv = params .tensors_values .by_name(name) .or_else(|| params.tensors_values.by_input_ix(ix)); tmp.push(vec![crate::tensor::tensor_for_fact(&fact, None, tv)?.into()]); } else { bail!("Unmatched tensor {}. Fix the input or use \"--allow-random-input\" if this was intended", name); } } Ok((0..tmp[0].len()).map(|turn| tmp.iter().map(|t| t[turn].clone()).collect()).collect()) } fn make_inputs(values: &[impl std::borrow::Borrow<TypedFact>]) -> TractResult<TVec<TValue>> { values.iter().map(|v| tensor_for_fact(v.borrow(), None, None).map(|t| t.into())).collect() } pub fn make_inputs_for_model(model: &dyn Model) -> TractResult<TVec<TValue>> { make_inputs( &model .input_outlets() .iter() .map(|&t| model.outlet_typedfact(t)) .collect::<TractResult<Vec<TypedFact>>>()?, ) } #[allow(unused_variables)] pub fn tensor_for_fact( fact: &TypedFact, streaming_dim: Option<usize>, tv: Option<&TensorValues>, ) -> TractResult<Tensor> { if let Some(value) = &fact.konst { return Ok(value.clone().into_tensor()); } #[cfg(pulse)] { if fact.shape.stream_info().is_some() { use tract_pulse::fact::StreamFact; use tract_pulse::internal::stream_symbol; let s = stream_symbol(); if let Some(dim) = streaming_dim { let shape = fact .shape .iter() .map(|d| { d.eval(&SymbolValues::default().with(s, dim as i64)).to_usize().unwrap() }) .collect::<TVec<_>>(); return Ok(random(&shape, fact.datum_type)); } else { bail!("random tensor requires a streaming dim") } } } Ok(random( fact.shape .as_concrete() .with_context(|| format!("Expected concrete shape, found: {fact:?}"))?, fact.datum_type, tv, )) } /// Generates a random tensor of a given size and type. pub fn random(sizes: &[usize], datum_type: DatumType, tv: Option<&TensorValues>) -> Tensor { use rand::{Rng, SeedableRng}; let mut rng = rand::rngs::StdRng::seed_from_u64(21242); let mut tensor = Tensor::zero::<f32>(sizes).unwrap(); let slice = tensor.as_slice_mut::<f32>().unwrap(); if let Some(range) = tv.and_then(|tv| tv.random_range.as_ref()) { slice.iter_mut().for_each(|x| *x = rng.gen_range(range.clone())) } else { slice.iter_mut().for_each(|x| *x = rng.gen()) }; tensor.cast_to_dt(datum_type).unwrap().into_owned() }
{ self.add(TensorValues { input_index: Some(ix), ..TensorValues::default() }); }
conditional_block
tensor.rs
use std::collections::HashSet; use std::io::{Read, Seek}; use std::ops::Range; use std::str::FromStr; use std::sync::Mutex; use crate::model::Model; use tract_hir::internal::*; #[derive(Debug, Default, Clone)] pub struct TensorsValues(pub Vec<TensorValues>); impl TensorsValues { pub fn by_name(&self, name: &str) -> Option<&TensorValues> { self.0.iter().find(|t| t.name.as_deref() == Some(name)) } pub fn
(&mut self, name: &str) -> Option<&mut TensorValues> { self.0.iter_mut().find(|t| t.name.as_deref() == Some(name)) } pub fn by_name_mut_with_default(&mut self, name: &str) -> &mut TensorValues { if self.by_name_mut(name).is_none() { self.add(TensorValues { name: Some(name.to_string()),..TensorValues::default() }); } self.by_name_mut(name).unwrap() } pub fn by_input_ix(&self, ix: usize) -> Option<&TensorValues> { self.0.iter().find(|t| t.input_index == Some(ix)) } pub fn by_input_ix_mut(&mut self, ix: usize) -> Option<&mut TensorValues> { self.0.iter_mut().find(|t| t.input_index == Some(ix)) } pub fn by_input_ix_mut_with_default(&mut self, ix: usize) -> &mut TensorValues { if self.by_input_ix_mut(ix).is_none() { self.add(TensorValues { input_index: Some(ix),..TensorValues::default() }); } self.by_input_ix_mut(ix).unwrap() } pub fn add(&mut self, other: TensorValues) { let mut tensor = other.input_index.and_then(|ix| self.by_input_ix_mut(ix)); if tensor.is_none() { tensor = other.name.as_deref().and_then(|ix| self.by_name_mut(ix)) } if let Some(tensor) = tensor { if tensor.fact.is_none() { tensor.fact = other.fact; } if tensor.values.is_none() { tensor.values = other.values; } } else { self.0.push(other.clone()); }; } } #[derive(Debug, PartialEq, Clone, Default)] pub struct TensorValues { pub input_index: Option<usize>, pub output_index: Option<usize>, pub name: Option<String>, pub fact: Option<InferenceFact>, pub values: Option<Vec<TValue>>, pub random_range: Option<Range<f32>>, } fn parse_dt(dt: &str) -> TractResult<DatumType> { Ok(match dt.to_lowercase().as_ref() { "bool" => DatumType::Bool, "f16" => DatumType::F16, "f32" => DatumType::F32, "f64" => DatumType::F64, "i8" => DatumType::I8, "i16" => DatumType::I16, "i32" => DatumType::I32, "i64" => DatumType::I64, "u8" => DatumType::U8, "u16" => DatumType::U16, "u32" => DatumType::U32, "u64" => DatumType::U64, "tdim" => DatumType::TDim, _ => bail!( "Type of the input should be f16, f32, f64, i8, i16, i16, i32, u8, u16, u32, u64, TDim." ), }) } pub fn parse_spec(symbol_table: &SymbolTable, size: &str) -> TractResult<InferenceFact> { if size.is_empty() { return Ok(InferenceFact::default()); } parse_coma_spec(symbol_table, size) } pub fn parse_coma_spec(symbol_table: &SymbolTable, size: &str) -> TractResult<InferenceFact> { let splits = size.split(',').collect::<Vec<_>>(); if splits.is_empty() { // Hide '{' in this error message from the formatting machinery in bail macro let msg = "The <size> argument should be formatted as {size},{...},{type}."; bail!(msg); } let last = splits.last().unwrap(); let (datum_type, shape) = if let Ok(dt) = parse_dt(last) { (Some(dt), &splits[0..splits.len() - 1]) } else { (None, &*splits) }; let shape = ShapeFactoid::closed( shape .iter() .map(|&s| { Ok(if s == "_" { GenericFactoid::Any } else { GenericFactoid::Only(parse_tdim(symbol_table, s)?) }) }) .collect::<TractResult<TVec<DimFact>>>()?, ); if let Some(dt) = datum_type { Ok(InferenceFact::dt_shape(dt, shape)) } else { Ok(InferenceFact::shape(shape)) } } fn parse_values<T: Datum + FromStr>(shape: &[usize], it: Vec<&str>) -> TractResult<Tensor> { let values = it .into_iter() .map(|v| v.parse::<T>().map_err(|_| format_err!("Failed to parse {}", v))) .collect::<TractResult<Vec<T>>>()?; Ok(tract_ndarray::Array::from_shape_vec(shape, values)?.into()) } fn tensor_for_text_data( symbol_table: &SymbolTable, _filename: &str, mut reader: impl Read, ) -> TractResult<Tensor> { let mut data = String::new(); reader.read_to_string(&mut data)?; let mut lines = data.lines(); let proto = parse_spec(symbol_table, lines.next().context("Empty data file")?)?; let shape = proto.shape.concretize().unwrap(); let values = lines.flat_map(|l| l.split_whitespace()).collect::<Vec<&str>>(); // We know there is at most one streaming dimension, so we can deduce the // missing value with a simple division. let product: usize = shape.iter().map(|o| o.to_usize().unwrap_or(1)).product(); let missing = values.len() / product; let shape: Vec<_> = shape.iter().map(|d| d.to_usize().unwrap_or(missing)).collect(); dispatch_numbers!(parse_values(proto.datum_type.concretize().unwrap())(&*shape, values)) } /// Parses the `data` command-line argument. pub fn for_data( symbol_table: &SymbolTable, filename: &str, reader: impl Read + std::io::Seek, ) -> TractResult<(Option<String>, InferenceFact)> { #[allow(unused_imports)] use std::convert::TryFrom; if filename.ends_with(".pb") { #[cfg(feature = "onnx")] { /* let file = fs::File::open(filename).with_context(|| format!("Can't open {filename:?}"))?; */ let proto = ::tract_onnx::tensor::proto_from_reader(reader)?; Ok(( Some(proto.name.to_string()).filter(|s|!s.is_empty()), Tensor::try_from(proto)?.into(), )) } #[cfg(not(feature = "onnx"))] { panic!("Loading tensor from protobuf requires onnx features"); } } else if filename.contains(".npz:") { let mut tokens = filename.split(':'); let (_filename, inner) = (tokens.next().unwrap(), tokens.next().unwrap()); let mut npz = ndarray_npy::NpzReader::new(reader)?; Ok((None, for_npz(&mut npz, inner)?.into())) } else { Ok((None, tensor_for_text_data(symbol_table, filename, reader)?.into())) } } pub fn for_npz( npz: &mut ndarray_npy::NpzReader<impl Read + Seek>, name: &str, ) -> TractResult<Tensor> { if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<f32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<f64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i8>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i16>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u8>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u16>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<bool>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } bail!("Can not extract tensor from {}", name); } pub fn for_string( symbol_table: &SymbolTable, value: &str, ) -> TractResult<(Option<String>, InferenceFact)> { let (name, value) = if value.contains(':') { let mut splits = value.split(':'); (Some(splits.next().unwrap().to_string()), splits.next().unwrap()) } else { (None, value) }; if value.contains('=') { let mut split = value.split('='); let spec = parse_spec(symbol_table, split.next().unwrap())?; let value = split.next().unwrap().split(','); let dt = spec.datum_type.concretize().context("Must specify type when giving tensor value")?; let shape = spec .shape .as_concrete_finite()? .context("Must specify concrete shape when giving tensor value")?; let tensor = dispatch_numbers!(parse_values(dt)(&*shape, value.collect()))?; Ok((name, tensor.into())) } else { Ok((name, parse_spec(symbol_table, value)?)) } } lazy_static::lazy_static! { static ref WARNING_ONCE: Mutex<HashSet<String>> = Mutex::new(HashSet::new()); } fn warn_once(msg: String) { if WARNING_ONCE.lock().unwrap().insert(msg.clone()) { warn!("{}", msg); } } pub struct RunParams { pub tensors_values: TensorsValues, pub allow_random_input: bool, pub allow_float_casts: bool, } pub fn retrieve_or_make_inputs( tract: &dyn Model, params: &RunParams, ) -> TractResult<Vec<TVec<TValue>>> { let mut tmp: TVec<Vec<TValue>> = tvec![]; for (ix, input) in tract.input_outlets().iter().enumerate() { let name = tract.node_name(input.node); let fact = tract.outlet_typedfact(*input)?; if let Some(mut value) = params.tensors_values.by_name(name).and_then(|t| t.values.clone()) { if!value[0].datum_type().is_quantized() && fact.datum_type.is_quantized() && value[0].datum_type() == fact.datum_type.unquantized() { value = value .iter() .map(|v| { let mut v = v.clone().into_tensor(); unsafe { v.set_datum_type(fact.datum_type) }; v.into() }) .collect(); } if TypedFact::from(&*value[0]).compatible_with(&fact) { info!("Using fixed input for input called {} ({} turn(s))", name, value.len()); tmp.push(value.iter().map(|t| t.clone().into_tensor().into()).collect()) } else if fact.datum_type == f16::datum_type() && value[0].datum_type() == f32::datum_type() && params.allow_float_casts { tmp.push( value.iter().map(|t| t.cast_to::<f16>().unwrap().into_owned().into()).collect(), ) } else if value.len() == 1 && tract.properties().contains_key("pulse.delay") { let value = &value[0]; let input_pulse_axis = tract .properties() .get("pulse.input_axes") .context("Expect pulse.input_axes property")? .cast_to::<i64>()? .as_slice::<i64>()?[ix] as usize; let input_pulse = fact.shape.get(input_pulse_axis).unwrap().to_usize().unwrap(); let input_len = value.shape()[input_pulse_axis]; // how many pulses do we need to push full result out? // guess by looking at len and delay of the first output let output_pulse_axis = tract .properties() .get("pulse.output_axes") .context("Expect pulse.output_axes property")? .cast_to::<i64>()? .as_slice::<i64>()?[0] as usize; let output_fact = tract.outlet_typedfact(tract.output_outlets()[0])?; let output_pulse = output_fact.shape.get(output_pulse_axis).unwrap().to_usize().unwrap(); let output_len = input_len * output_pulse / input_pulse; let output_delay = tract.properties()["pulse.delay"].as_slice::<i64>()?[0] as usize; let last_frame = output_len + output_delay; let needed_pulses = last_frame.divceil(output_pulse); let mut values = vec![]; for ix in 0..needed_pulses { let mut t = Tensor::zero_dt(fact.datum_type, fact.shape.as_concrete().unwrap())?; let start = ix * input_pulse; let end = (start + input_pulse).min(input_len); if end > start { t.assign_slice(0..end - start, value, start..end, input_pulse_axis)?; } values.push(t.into()); } info!( "Generated {} pulses of shape {:?} for input {}.", needed_pulses, fact.shape, ix ); tmp.push(values); } else { bail!("For input {}, can not reconcile model input fact {:?} with provided input {:?}", name, fact, value[0]); }; } else if params.allow_random_input { let fact = tract.outlet_typedfact(*input)?; warn_once(format!("Using random input for input called {name:?}: {fact:?}")); let tv = params .tensors_values .by_name(name) .or_else(|| params.tensors_values.by_input_ix(ix)); tmp.push(vec![crate::tensor::tensor_for_fact(&fact, None, tv)?.into()]); } else { bail!("Unmatched tensor {}. Fix the input or use \"--allow-random-input\" if this was intended", name); } } Ok((0..tmp[0].len()).map(|turn| tmp.iter().map(|t| t[turn].clone()).collect()).collect()) } fn make_inputs(values: &[impl std::borrow::Borrow<TypedFact>]) -> TractResult<TVec<TValue>> { values.iter().map(|v| tensor_for_fact(v.borrow(), None, None).map(|t| t.into())).collect() } pub fn make_inputs_for_model(model: &dyn Model) -> TractResult<TVec<TValue>> { make_inputs( &model .input_outlets() .iter() .map(|&t| model.outlet_typedfact(t)) .collect::<TractResult<Vec<TypedFact>>>()?, ) } #[allow(unused_variables)] pub fn tensor_for_fact( fact: &TypedFact, streaming_dim: Option<usize>, tv: Option<&TensorValues>, ) -> TractResult<Tensor> { if let Some(value) = &fact.konst { return Ok(value.clone().into_tensor()); } #[cfg(pulse)] { if fact.shape.stream_info().is_some() { use tract_pulse::fact::StreamFact; use tract_pulse::internal::stream_symbol; let s = stream_symbol(); if let Some(dim) = streaming_dim { let shape = fact .shape .iter() .map(|d| { d.eval(&SymbolValues::default().with(s, dim as i64)).to_usize().unwrap() }) .collect::<TVec<_>>(); return Ok(random(&shape, fact.datum_type)); } else { bail!("random tensor requires a streaming dim") } } } Ok(random( fact.shape .as_concrete() .with_context(|| format!("Expected concrete shape, found: {fact:?}"))?, fact.datum_type, tv, )) } /// Generates a random tensor of a given size and type. pub fn random(sizes: &[usize], datum_type: DatumType, tv: Option<&TensorValues>) -> Tensor { use rand::{Rng, SeedableRng}; let mut rng = rand::rngs::StdRng::seed_from_u64(21242); let mut tensor = Tensor::zero::<f32>(sizes).unwrap(); let slice = tensor.as_slice_mut::<f32>().unwrap(); if let Some(range) = tv.and_then(|tv| tv.random_range.as_ref()) { slice.iter_mut().for_each(|x| *x = rng.gen_range(range.clone())) } else { slice.iter_mut().for_each(|x| *x = rng.gen()) }; tensor.cast_to_dt(datum_type).unwrap().into_owned() }
by_name_mut
identifier_name
tensor.rs
use std::collections::HashSet; use std::io::{Read, Seek}; use std::ops::Range; use std::str::FromStr; use std::sync::Mutex; use crate::model::Model; use tract_hir::internal::*; #[derive(Debug, Default, Clone)] pub struct TensorsValues(pub Vec<TensorValues>); impl TensorsValues { pub fn by_name(&self, name: &str) -> Option<&TensorValues> { self.0.iter().find(|t| t.name.as_deref() == Some(name)) } pub fn by_name_mut(&mut self, name: &str) -> Option<&mut TensorValues> { self.0.iter_mut().find(|t| t.name.as_deref() == Some(name)) } pub fn by_name_mut_with_default(&mut self, name: &str) -> &mut TensorValues { if self.by_name_mut(name).is_none() { self.add(TensorValues { name: Some(name.to_string()),..TensorValues::default() }); } self.by_name_mut(name).unwrap() } pub fn by_input_ix(&self, ix: usize) -> Option<&TensorValues> { self.0.iter().find(|t| t.input_index == Some(ix)) } pub fn by_input_ix_mut(&mut self, ix: usize) -> Option<&mut TensorValues> { self.0.iter_mut().find(|t| t.input_index == Some(ix)) } pub fn by_input_ix_mut_with_default(&mut self, ix: usize) -> &mut TensorValues { if self.by_input_ix_mut(ix).is_none() { self.add(TensorValues { input_index: Some(ix),..TensorValues::default() }); } self.by_input_ix_mut(ix).unwrap() } pub fn add(&mut self, other: TensorValues) { let mut tensor = other.input_index.and_then(|ix| self.by_input_ix_mut(ix)); if tensor.is_none() { tensor = other.name.as_deref().and_then(|ix| self.by_name_mut(ix)) } if let Some(tensor) = tensor { if tensor.fact.is_none() { tensor.fact = other.fact; } if tensor.values.is_none() { tensor.values = other.values; } } else { self.0.push(other.clone()); }; } } #[derive(Debug, PartialEq, Clone, Default)] pub struct TensorValues { pub input_index: Option<usize>, pub output_index: Option<usize>, pub name: Option<String>, pub fact: Option<InferenceFact>, pub values: Option<Vec<TValue>>, pub random_range: Option<Range<f32>>, } fn parse_dt(dt: &str) -> TractResult<DatumType> { Ok(match dt.to_lowercase().as_ref() { "bool" => DatumType::Bool, "f16" => DatumType::F16, "f32" => DatumType::F32, "f64" => DatumType::F64, "i8" => DatumType::I8, "i16" => DatumType::I16, "i32" => DatumType::I32, "i64" => DatumType::I64, "u8" => DatumType::U8, "u16" => DatumType::U16, "u32" => DatumType::U32, "u64" => DatumType::U64, "tdim" => DatumType::TDim, _ => bail!( "Type of the input should be f16, f32, f64, i8, i16, i16, i32, u8, u16, u32, u64, TDim." ), }) } pub fn parse_spec(symbol_table: &SymbolTable, size: &str) -> TractResult<InferenceFact> { if size.is_empty() { return Ok(InferenceFact::default()); } parse_coma_spec(symbol_table, size) } pub fn parse_coma_spec(symbol_table: &SymbolTable, size: &str) -> TractResult<InferenceFact> { let splits = size.split(',').collect::<Vec<_>>(); if splits.is_empty() { // Hide '{' in this error message from the formatting machinery in bail macro let msg = "The <size> argument should be formatted as {size},{...},{type}."; bail!(msg); } let last = splits.last().unwrap(); let (datum_type, shape) = if let Ok(dt) = parse_dt(last) { (Some(dt), &splits[0..splits.len() - 1]) } else { (None, &*splits) }; let shape = ShapeFactoid::closed( shape .iter() .map(|&s| { Ok(if s == "_" { GenericFactoid::Any } else { GenericFactoid::Only(parse_tdim(symbol_table, s)?) }) }) .collect::<TractResult<TVec<DimFact>>>()?, ); if let Some(dt) = datum_type { Ok(InferenceFact::dt_shape(dt, shape)) } else { Ok(InferenceFact::shape(shape)) } } fn parse_values<T: Datum + FromStr>(shape: &[usize], it: Vec<&str>) -> TractResult<Tensor> { let values = it .into_iter() .map(|v| v.parse::<T>().map_err(|_| format_err!("Failed to parse {}", v))) .collect::<TractResult<Vec<T>>>()?; Ok(tract_ndarray::Array::from_shape_vec(shape, values)?.into()) } fn tensor_for_text_data( symbol_table: &SymbolTable, _filename: &str, mut reader: impl Read, ) -> TractResult<Tensor> { let mut data = String::new(); reader.read_to_string(&mut data)?; let mut lines = data.lines(); let proto = parse_spec(symbol_table, lines.next().context("Empty data file")?)?; let shape = proto.shape.concretize().unwrap(); let values = lines.flat_map(|l| l.split_whitespace()).collect::<Vec<&str>>(); // We know there is at most one streaming dimension, so we can deduce the // missing value with a simple division. let product: usize = shape.iter().map(|o| o.to_usize().unwrap_or(1)).product(); let missing = values.len() / product; let shape: Vec<_> = shape.iter().map(|d| d.to_usize().unwrap_or(missing)).collect(); dispatch_numbers!(parse_values(proto.datum_type.concretize().unwrap())(&*shape, values)) } /// Parses the `data` command-line argument. pub fn for_data( symbol_table: &SymbolTable, filename: &str, reader: impl Read + std::io::Seek, ) -> TractResult<(Option<String>, InferenceFact)> { #[allow(unused_imports)] use std::convert::TryFrom; if filename.ends_with(".pb") { #[cfg(feature = "onnx")] { /* let file = fs::File::open(filename).with_context(|| format!("Can't open {filename:?}"))?; */ let proto = ::tract_onnx::tensor::proto_from_reader(reader)?; Ok(( Some(proto.name.to_string()).filter(|s|!s.is_empty()), Tensor::try_from(proto)?.into(), )) } #[cfg(not(feature = "onnx"))] { panic!("Loading tensor from protobuf requires onnx features"); } } else if filename.contains(".npz:") { let mut tokens = filename.split(':'); let (_filename, inner) = (tokens.next().unwrap(), tokens.next().unwrap()); let mut npz = ndarray_npy::NpzReader::new(reader)?; Ok((None, for_npz(&mut npz, inner)?.into())) } else { Ok((None, tensor_for_text_data(symbol_table, filename, reader)?.into())) } } pub fn for_npz( npz: &mut ndarray_npy::NpzReader<impl Read + Seek>, name: &str, ) -> TractResult<Tensor> { if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<f32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<f64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i8>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i16>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u8>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u16>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<bool>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } bail!("Can not extract tensor from {}", name); } pub fn for_string( symbol_table: &SymbolTable, value: &str, ) -> TractResult<(Option<String>, InferenceFact)> { let (name, value) = if value.contains(':') { let mut splits = value.split(':'); (Some(splits.next().unwrap().to_string()), splits.next().unwrap()) } else { (None, value) }; if value.contains('=') { let mut split = value.split('='); let spec = parse_spec(symbol_table, split.next().unwrap())?; let value = split.next().unwrap().split(','); let dt = spec.datum_type.concretize().context("Must specify type when giving tensor value")?; let shape = spec .shape .as_concrete_finite()? .context("Must specify concrete shape when giving tensor value")?; let tensor = dispatch_numbers!(parse_values(dt)(&*shape, value.collect()))?; Ok((name, tensor.into())) } else { Ok((name, parse_spec(symbol_table, value)?)) } } lazy_static::lazy_static! { static ref WARNING_ONCE: Mutex<HashSet<String>> = Mutex::new(HashSet::new()); } fn warn_once(msg: String) { if WARNING_ONCE.lock().unwrap().insert(msg.clone()) { warn!("{}", msg); } } pub struct RunParams { pub tensors_values: TensorsValues, pub allow_random_input: bool, pub allow_float_casts: bool, } pub fn retrieve_or_make_inputs( tract: &dyn Model, params: &RunParams, ) -> TractResult<Vec<TVec<TValue>>> { let mut tmp: TVec<Vec<TValue>> = tvec![]; for (ix, input) in tract.input_outlets().iter().enumerate() { let name = tract.node_name(input.node); let fact = tract.outlet_typedfact(*input)?; if let Some(mut value) = params.tensors_values.by_name(name).and_then(|t| t.values.clone()) { if!value[0].datum_type().is_quantized() && fact.datum_type.is_quantized() && value[0].datum_type() == fact.datum_type.unquantized() { value = value .iter() .map(|v| { let mut v = v.clone().into_tensor(); unsafe { v.set_datum_type(fact.datum_type) }; v.into() }) .collect(); } if TypedFact::from(&*value[0]).compatible_with(&fact) { info!("Using fixed input for input called {} ({} turn(s))", name, value.len()); tmp.push(value.iter().map(|t| t.clone().into_tensor().into()).collect()) } else if fact.datum_type == f16::datum_type() && value[0].datum_type() == f32::datum_type() && params.allow_float_casts { tmp.push( value.iter().map(|t| t.cast_to::<f16>().unwrap().into_owned().into()).collect(), ) } else if value.len() == 1 && tract.properties().contains_key("pulse.delay") { let value = &value[0]; let input_pulse_axis = tract .properties() .get("pulse.input_axes") .context("Expect pulse.input_axes property")? .cast_to::<i64>()? .as_slice::<i64>()?[ix] as usize; let input_pulse = fact.shape.get(input_pulse_axis).unwrap().to_usize().unwrap(); let input_len = value.shape()[input_pulse_axis]; // how many pulses do we need to push full result out? // guess by looking at len and delay of the first output let output_pulse_axis = tract .properties() .get("pulse.output_axes") .context("Expect pulse.output_axes property")? .cast_to::<i64>()? .as_slice::<i64>()?[0] as usize; let output_fact = tract.outlet_typedfact(tract.output_outlets()[0])?; let output_pulse = output_fact.shape.get(output_pulse_axis).unwrap().to_usize().unwrap(); let output_len = input_len * output_pulse / input_pulse; let output_delay = tract.properties()["pulse.delay"].as_slice::<i64>()?[0] as usize; let last_frame = output_len + output_delay; let needed_pulses = last_frame.divceil(output_pulse); let mut values = vec![]; for ix in 0..needed_pulses { let mut t = Tensor::zero_dt(fact.datum_type, fact.shape.as_concrete().unwrap())?; let start = ix * input_pulse; let end = (start + input_pulse).min(input_len); if end > start { t.assign_slice(0..end - start, value, start..end, input_pulse_axis)?; } values.push(t.into()); } info!( "Generated {} pulses of shape {:?} for input {}.", needed_pulses, fact.shape, ix ); tmp.push(values); } else { bail!("For input {}, can not reconcile model input fact {:?} with provided input {:?}", name, fact, value[0]); }; } else if params.allow_random_input { let fact = tract.outlet_typedfact(*input)?; warn_once(format!("Using random input for input called {name:?}: {fact:?}")); let tv = params .tensors_values .by_name(name) .or_else(|| params.tensors_values.by_input_ix(ix)); tmp.push(vec![crate::tensor::tensor_for_fact(&fact, None, tv)?.into()]); } else { bail!("Unmatched tensor {}. Fix the input or use \"--allow-random-input\" if this was intended", name); }
values.iter().map(|v| tensor_for_fact(v.borrow(), None, None).map(|t| t.into())).collect() } pub fn make_inputs_for_model(model: &dyn Model) -> TractResult<TVec<TValue>> { make_inputs( &model .input_outlets() .iter() .map(|&t| model.outlet_typedfact(t)) .collect::<TractResult<Vec<TypedFact>>>()?, ) } #[allow(unused_variables)] pub fn tensor_for_fact( fact: &TypedFact, streaming_dim: Option<usize>, tv: Option<&TensorValues>, ) -> TractResult<Tensor> { if let Some(value) = &fact.konst { return Ok(value.clone().into_tensor()); } #[cfg(pulse)] { if fact.shape.stream_info().is_some() { use tract_pulse::fact::StreamFact; use tract_pulse::internal::stream_symbol; let s = stream_symbol(); if let Some(dim) = streaming_dim { let shape = fact .shape .iter() .map(|d| { d.eval(&SymbolValues::default().with(s, dim as i64)).to_usize().unwrap() }) .collect::<TVec<_>>(); return Ok(random(&shape, fact.datum_type)); } else { bail!("random tensor requires a streaming dim") } } } Ok(random( fact.shape .as_concrete() .with_context(|| format!("Expected concrete shape, found: {fact:?}"))?, fact.datum_type, tv, )) } /// Generates a random tensor of a given size and type. pub fn random(sizes: &[usize], datum_type: DatumType, tv: Option<&TensorValues>) -> Tensor { use rand::{Rng, SeedableRng}; let mut rng = rand::rngs::StdRng::seed_from_u64(21242); let mut tensor = Tensor::zero::<f32>(sizes).unwrap(); let slice = tensor.as_slice_mut::<f32>().unwrap(); if let Some(range) = tv.and_then(|tv| tv.random_range.as_ref()) { slice.iter_mut().for_each(|x| *x = rng.gen_range(range.clone())) } else { slice.iter_mut().for_each(|x| *x = rng.gen()) }; tensor.cast_to_dt(datum_type).unwrap().into_owned() }
} Ok((0..tmp[0].len()).map(|turn| tmp.iter().map(|t| t[turn].clone()).collect()).collect()) } fn make_inputs(values: &[impl std::borrow::Borrow<TypedFact>]) -> TractResult<TVec<TValue>> {
random_line_split
tensor.rs
use std::collections::HashSet; use std::io::{Read, Seek}; use std::ops::Range; use std::str::FromStr; use std::sync::Mutex; use crate::model::Model; use tract_hir::internal::*; #[derive(Debug, Default, Clone)] pub struct TensorsValues(pub Vec<TensorValues>); impl TensorsValues { pub fn by_name(&self, name: &str) -> Option<&TensorValues> { self.0.iter().find(|t| t.name.as_deref() == Some(name)) } pub fn by_name_mut(&mut self, name: &str) -> Option<&mut TensorValues> { self.0.iter_mut().find(|t| t.name.as_deref() == Some(name)) } pub fn by_name_mut_with_default(&mut self, name: &str) -> &mut TensorValues { if self.by_name_mut(name).is_none() { self.add(TensorValues { name: Some(name.to_string()),..TensorValues::default() }); } self.by_name_mut(name).unwrap() } pub fn by_input_ix(&self, ix: usize) -> Option<&TensorValues> { self.0.iter().find(|t| t.input_index == Some(ix)) } pub fn by_input_ix_mut(&mut self, ix: usize) -> Option<&mut TensorValues> { self.0.iter_mut().find(|t| t.input_index == Some(ix)) } pub fn by_input_ix_mut_with_default(&mut self, ix: usize) -> &mut TensorValues { if self.by_input_ix_mut(ix).is_none() { self.add(TensorValues { input_index: Some(ix),..TensorValues::default() }); } self.by_input_ix_mut(ix).unwrap() } pub fn add(&mut self, other: TensorValues) { let mut tensor = other.input_index.and_then(|ix| self.by_input_ix_mut(ix)); if tensor.is_none() { tensor = other.name.as_deref().and_then(|ix| self.by_name_mut(ix)) } if let Some(tensor) = tensor { if tensor.fact.is_none() { tensor.fact = other.fact; } if tensor.values.is_none() { tensor.values = other.values; } } else { self.0.push(other.clone()); }; } } #[derive(Debug, PartialEq, Clone, Default)] pub struct TensorValues { pub input_index: Option<usize>, pub output_index: Option<usize>, pub name: Option<String>, pub fact: Option<InferenceFact>, pub values: Option<Vec<TValue>>, pub random_range: Option<Range<f32>>, } fn parse_dt(dt: &str) -> TractResult<DatumType> { Ok(match dt.to_lowercase().as_ref() { "bool" => DatumType::Bool, "f16" => DatumType::F16, "f32" => DatumType::F32, "f64" => DatumType::F64, "i8" => DatumType::I8, "i16" => DatumType::I16, "i32" => DatumType::I32, "i64" => DatumType::I64, "u8" => DatumType::U8, "u16" => DatumType::U16, "u32" => DatumType::U32, "u64" => DatumType::U64, "tdim" => DatumType::TDim, _ => bail!( "Type of the input should be f16, f32, f64, i8, i16, i16, i32, u8, u16, u32, u64, TDim." ), }) } pub fn parse_spec(symbol_table: &SymbolTable, size: &str) -> TractResult<InferenceFact> { if size.is_empty() { return Ok(InferenceFact::default()); } parse_coma_spec(symbol_table, size) } pub fn parse_coma_spec(symbol_table: &SymbolTable, size: &str) -> TractResult<InferenceFact> { let splits = size.split(',').collect::<Vec<_>>(); if splits.is_empty() { // Hide '{' in this error message from the formatting machinery in bail macro let msg = "The <size> argument should be formatted as {size},{...},{type}."; bail!(msg); } let last = splits.last().unwrap(); let (datum_type, shape) = if let Ok(dt) = parse_dt(last) { (Some(dt), &splits[0..splits.len() - 1]) } else { (None, &*splits) }; let shape = ShapeFactoid::closed( shape .iter() .map(|&s| { Ok(if s == "_" { GenericFactoid::Any } else { GenericFactoid::Only(parse_tdim(symbol_table, s)?) }) }) .collect::<TractResult<TVec<DimFact>>>()?, ); if let Some(dt) = datum_type { Ok(InferenceFact::dt_shape(dt, shape)) } else { Ok(InferenceFact::shape(shape)) } } fn parse_values<T: Datum + FromStr>(shape: &[usize], it: Vec<&str>) -> TractResult<Tensor> { let values = it .into_iter() .map(|v| v.parse::<T>().map_err(|_| format_err!("Failed to parse {}", v))) .collect::<TractResult<Vec<T>>>()?; Ok(tract_ndarray::Array::from_shape_vec(shape, values)?.into()) } fn tensor_for_text_data( symbol_table: &SymbolTable, _filename: &str, mut reader: impl Read, ) -> TractResult<Tensor> { let mut data = String::new(); reader.read_to_string(&mut data)?; let mut lines = data.lines(); let proto = parse_spec(symbol_table, lines.next().context("Empty data file")?)?; let shape = proto.shape.concretize().unwrap(); let values = lines.flat_map(|l| l.split_whitespace()).collect::<Vec<&str>>(); // We know there is at most one streaming dimension, so we can deduce the // missing value with a simple division. let product: usize = shape.iter().map(|o| o.to_usize().unwrap_or(1)).product(); let missing = values.len() / product; let shape: Vec<_> = shape.iter().map(|d| d.to_usize().unwrap_or(missing)).collect(); dispatch_numbers!(parse_values(proto.datum_type.concretize().unwrap())(&*shape, values)) } /// Parses the `data` command-line argument. pub fn for_data( symbol_table: &SymbolTable, filename: &str, reader: impl Read + std::io::Seek, ) -> TractResult<(Option<String>, InferenceFact)> { #[allow(unused_imports)] use std::convert::TryFrom; if filename.ends_with(".pb") { #[cfg(feature = "onnx")] { /* let file = fs::File::open(filename).with_context(|| format!("Can't open {filename:?}"))?; */ let proto = ::tract_onnx::tensor::proto_from_reader(reader)?; Ok(( Some(proto.name.to_string()).filter(|s|!s.is_empty()), Tensor::try_from(proto)?.into(), )) } #[cfg(not(feature = "onnx"))] { panic!("Loading tensor from protobuf requires onnx features"); } } else if filename.contains(".npz:") { let mut tokens = filename.split(':'); let (_filename, inner) = (tokens.next().unwrap(), tokens.next().unwrap()); let mut npz = ndarray_npy::NpzReader::new(reader)?; Ok((None, for_npz(&mut npz, inner)?.into())) } else { Ok((None, tensor_for_text_data(symbol_table, filename, reader)?.into())) } } pub fn for_npz( npz: &mut ndarray_npy::NpzReader<impl Read + Seek>, name: &str, ) -> TractResult<Tensor> { if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<f32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<f64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i8>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i16>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<i64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u8>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u16>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u32>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<u64>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } if let Ok(t) = npz.by_name::<tract_ndarray::OwnedRepr<bool>, tract_ndarray::IxDyn>(name) { return Ok(t.into_tensor()); } bail!("Can not extract tensor from {}", name); } pub fn for_string( symbol_table: &SymbolTable, value: &str, ) -> TractResult<(Option<String>, InferenceFact)> { let (name, value) = if value.contains(':') { let mut splits = value.split(':'); (Some(splits.next().unwrap().to_string()), splits.next().unwrap()) } else { (None, value) }; if value.contains('=') { let mut split = value.split('='); let spec = parse_spec(symbol_table, split.next().unwrap())?; let value = split.next().unwrap().split(','); let dt = spec.datum_type.concretize().context("Must specify type when giving tensor value")?; let shape = spec .shape .as_concrete_finite()? .context("Must specify concrete shape when giving tensor value")?; let tensor = dispatch_numbers!(parse_values(dt)(&*shape, value.collect()))?; Ok((name, tensor.into())) } else { Ok((name, parse_spec(symbol_table, value)?)) } } lazy_static::lazy_static! { static ref WARNING_ONCE: Mutex<HashSet<String>> = Mutex::new(HashSet::new()); } fn warn_once(msg: String) { if WARNING_ONCE.lock().unwrap().insert(msg.clone()) { warn!("{}", msg); } } pub struct RunParams { pub tensors_values: TensorsValues, pub allow_random_input: bool, pub allow_float_casts: bool, } pub fn retrieve_or_make_inputs( tract: &dyn Model, params: &RunParams, ) -> TractResult<Vec<TVec<TValue>>> { let mut tmp: TVec<Vec<TValue>> = tvec![]; for (ix, input) in tract.input_outlets().iter().enumerate() { let name = tract.node_name(input.node); let fact = tract.outlet_typedfact(*input)?; if let Some(mut value) = params.tensors_values.by_name(name).and_then(|t| t.values.clone()) { if!value[0].datum_type().is_quantized() && fact.datum_type.is_quantized() && value[0].datum_type() == fact.datum_type.unquantized() { value = value .iter() .map(|v| { let mut v = v.clone().into_tensor(); unsafe { v.set_datum_type(fact.datum_type) }; v.into() }) .collect(); } if TypedFact::from(&*value[0]).compatible_with(&fact) { info!("Using fixed input for input called {} ({} turn(s))", name, value.len()); tmp.push(value.iter().map(|t| t.clone().into_tensor().into()).collect()) } else if fact.datum_type == f16::datum_type() && value[0].datum_type() == f32::datum_type() && params.allow_float_casts { tmp.push( value.iter().map(|t| t.cast_to::<f16>().unwrap().into_owned().into()).collect(), ) } else if value.len() == 1 && tract.properties().contains_key("pulse.delay") { let value = &value[0]; let input_pulse_axis = tract .properties() .get("pulse.input_axes") .context("Expect pulse.input_axes property")? .cast_to::<i64>()? .as_slice::<i64>()?[ix] as usize; let input_pulse = fact.shape.get(input_pulse_axis).unwrap().to_usize().unwrap(); let input_len = value.shape()[input_pulse_axis]; // how many pulses do we need to push full result out? // guess by looking at len and delay of the first output let output_pulse_axis = tract .properties() .get("pulse.output_axes") .context("Expect pulse.output_axes property")? .cast_to::<i64>()? .as_slice::<i64>()?[0] as usize; let output_fact = tract.outlet_typedfact(tract.output_outlets()[0])?; let output_pulse = output_fact.shape.get(output_pulse_axis).unwrap().to_usize().unwrap(); let output_len = input_len * output_pulse / input_pulse; let output_delay = tract.properties()["pulse.delay"].as_slice::<i64>()?[0] as usize; let last_frame = output_len + output_delay; let needed_pulses = last_frame.divceil(output_pulse); let mut values = vec![]; for ix in 0..needed_pulses { let mut t = Tensor::zero_dt(fact.datum_type, fact.shape.as_concrete().unwrap())?; let start = ix * input_pulse; let end = (start + input_pulse).min(input_len); if end > start { t.assign_slice(0..end - start, value, start..end, input_pulse_axis)?; } values.push(t.into()); } info!( "Generated {} pulses of shape {:?} for input {}.", needed_pulses, fact.shape, ix ); tmp.push(values); } else { bail!("For input {}, can not reconcile model input fact {:?} with provided input {:?}", name, fact, value[0]); }; } else if params.allow_random_input { let fact = tract.outlet_typedfact(*input)?; warn_once(format!("Using random input for input called {name:?}: {fact:?}")); let tv = params .tensors_values .by_name(name) .or_else(|| params.tensors_values.by_input_ix(ix)); tmp.push(vec![crate::tensor::tensor_for_fact(&fact, None, tv)?.into()]); } else { bail!("Unmatched tensor {}. Fix the input or use \"--allow-random-input\" if this was intended", name); } } Ok((0..tmp[0].len()).map(|turn| tmp.iter().map(|t| t[turn].clone()).collect()).collect()) } fn make_inputs(values: &[impl std::borrow::Borrow<TypedFact>]) -> TractResult<TVec<TValue>> { values.iter().map(|v| tensor_for_fact(v.borrow(), None, None).map(|t| t.into())).collect() } pub fn make_inputs_for_model(model: &dyn Model) -> TractResult<TVec<TValue>>
#[allow(unused_variables)] pub fn tensor_for_fact( fact: &TypedFact, streaming_dim: Option<usize>, tv: Option<&TensorValues>, ) -> TractResult<Tensor> { if let Some(value) = &fact.konst { return Ok(value.clone().into_tensor()); } #[cfg(pulse)] { if fact.shape.stream_info().is_some() { use tract_pulse::fact::StreamFact; use tract_pulse::internal::stream_symbol; let s = stream_symbol(); if let Some(dim) = streaming_dim { let shape = fact .shape .iter() .map(|d| { d.eval(&SymbolValues::default().with(s, dim as i64)).to_usize().unwrap() }) .collect::<TVec<_>>(); return Ok(random(&shape, fact.datum_type)); } else { bail!("random tensor requires a streaming dim") } } } Ok(random( fact.shape .as_concrete() .with_context(|| format!("Expected concrete shape, found: {fact:?}"))?, fact.datum_type, tv, )) } /// Generates a random tensor of a given size and type. pub fn random(sizes: &[usize], datum_type: DatumType, tv: Option<&TensorValues>) -> Tensor { use rand::{Rng, SeedableRng}; let mut rng = rand::rngs::StdRng::seed_from_u64(21242); let mut tensor = Tensor::zero::<f32>(sizes).unwrap(); let slice = tensor.as_slice_mut::<f32>().unwrap(); if let Some(range) = tv.and_then(|tv| tv.random_range.as_ref()) { slice.iter_mut().for_each(|x| *x = rng.gen_range(range.clone())) } else { slice.iter_mut().for_each(|x| *x = rng.gen()) }; tensor.cast_to_dt(datum_type).unwrap().into_owned() }
{ make_inputs( &model .input_outlets() .iter() .map(|&t| model.outlet_typedfact(t)) .collect::<TractResult<Vec<TypedFact>>>()?, ) }
identifier_body
rtic-i2s-audio-in-out.rs
//! # I2S example with rtic //! //! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong //! operation can trigger loud noise on the DAC output. //! //! # Hardware required //! //! * a STM32F411 based board //! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI //! * Audio signal at ADC input, and something to ear at DAC output. //! //! # Hardware Wiring //! //! The wiring assume using PCM1808 and PCM5102 module that can be found on Aliexpress, ebay, //! Amazon... //! //! ## Stm32 //! //! | stm32 | PCM1808 | PCM5102 | //! |-------------|---------|---------| //! | pb12 + pa4 | LRC | LCK | //! | pb13 + pc10 | BCK | BCK | //! | pc6 | SCK | SCK | //! | pc12 | | DIN | //! | pb15 | OUT | | //! //! ## PCM1808 ADC module //! //! | Pin | Connected To | //! |-----|----------------| //! | LIN | audio in left | //! | - | audio in gnd | //! | RIN | audio in right | //! | FMT | Gnd or NC | //! | MD1 | Gnd or NC | //! | MD0 | Gnd or NC | //! | Gnd | Gnd | //! | 3.3 | +3V3 | //! | +5V | +5v | //! | BCK | pb13 + pc10 | //! | OUT | pb15 | //! | LRC | pb12 + pa4 | //! | SCK | pc6 | //! //! ## PCM5102 module //! //! | Pin | Connected to | //! |-------|-----------------| //! | SCK | pc6 | //! | BCK | pb13 + pc10 | //! | DIN | pc12 | //! | LCK | pb12 + pa4 | //! | GND | Gnd | //! | VIN | +3V3 | //! | FLT | Gnd or +3V3 | //! | DEMP | Gnd | //! | XSMT | +3V3 | //! | A3V3 | | //! | AGND | audio out gnd | //! | ROUT | audio out left | //! | LROUT | audio out right | //! //! Notes: on the module (not the chip) A3V3 is connected to VIN and AGND is connected to GND //! //! //! Expected behavior: you should ear a crappy stereo effect. This is actually 2 square tremolo //! applied with a 90 degrees phase shift. #![no_std] #![no_main] use core::panic::PanicInfo; use rtt_target::rprintln; use stm32f4xx_hal as hal; #[rtic::app(device = stm32f4xx_hal::pac, peripherals = true,dispatchers = [EXTI0, EXTI1, EXTI2])] mod app { use core::fmt::Write; use super::hal; use hal::gpio::{Edge, NoPin}; use hal::i2s::stm32_i2s_v12x::driver::*; use hal::i2s::I2s; use hal::pac::Interrupt; use hal::pac::{EXTI, SPI2, SPI3}; use hal::prelude::*; use heapless::spsc::*; use rtt_target::{rprintln, rtt_init, set_print_channel}; type I2s2Driver = I2sDriver<I2s<SPI2>, Master, Receive, Philips>; type I2s3Driver = I2sDriver<I2s<SPI3>, Slave, Transmit, Philips>; // Part of the frame we currently transmit or receive #[derive(Copy, Clone)] pub enum FrameState { LeftMsb, LeftLsb, RightMsb, RightLsb, } use FrameState::{LeftLsb, LeftMsb, RightLsb, RightMsb}; impl Default for FrameState { fn default() -> Self { Self::LeftMsb } } #[shared] struct Shared { #[lock_free] i2s2_driver: I2s2Driver, #[lock_free] i2s3_driver: I2s3Driver, #[lock_free] exti: EXTI, } #[local] struct Local { logs_chan: rtt_target::UpChannel, adc_p: Producer<'static, (i32, i32), 2>, process_c: Consumer<'static, (i32, i32), 2>, process_p: Producer<'static, (i32, i32), 2>, dac_c: Consumer<'static, (i32, i32), 2>, } #[init(local = [queue_1: Queue<(i32,i32), 2> = Queue::new(),queue_2: Queue<(i32,i32), 2> = Queue::new()])] fn init(cx: init::Context) -> (Shared, Local, init::Monotonics) { let queue_1 = cx.local.queue_1; let queue_2 = cx.local.queue_2; let channels = rtt_init! { up: { 0: { size: 128 name: "Logs" } 1: { size: 128 name: "Panics" } } }; let logs_chan = channels.up.0; let panics_chan = channels.up.1; set_print_channel(panics_chan); let (adc_p, process_c) = queue_1.split(); let (process_p, dac_c) = queue_2.split(); let device = cx.device; let mut syscfg = device.SYSCFG.constrain(); let mut exti = device.EXTI; let gpioa = device.GPIOA.split(); let gpiob = device.GPIOB.split(); let gpioc = device.GPIOC.split(); let rcc = device.RCC.constrain(); let clocks = rcc .cfgr .use_hse(8u32.MHz()) .sysclk(96.MHz()) .hclk(96.MHz()) .pclk1(50.MHz()) .pclk2(100.MHz()) .i2s_clk(61440.kHz()) .freeze(); // I2S pins: (WS, CK, MCLK, SD) for I2S2 let i2s2_pins = ( gpiob.pb12, //WS gpiob.pb13, //CK gpioc.pc6, //MCK gpiob.pb15, //SD ); let i2s2 = I2s::new(device.SPI2, i2s2_pins, &clocks); let i2s2_config = I2sDriverConfig::new_master() .receive() .standard(Philips) .data_format(DataFormat::Data24Channel32) .master_clock(true) .request_frequency(48_000); let mut i2s2_driver = I2sDriver::new(i2s2, i2s2_config); rprintln!("actual sample rate is {}", i2s2_driver.sample_rate()); i2s2_driver.set_rx_interrupt(true); i2s2_driver.set_error_interrupt(true); // I2S3 pins: (WS, CK, NoPin, SD) for I2S3 let i2s3_pins = (gpioa.pa4, gpioc.pc10, NoPin::new(), gpioc.pc12); let i2s3 = I2s::new(device.SPI3, i2s3_pins, &clocks); let i2s3_config = i2s2_config.to_slave().transmit(); let mut i2s3_driver = I2sDriver::new(i2s3, i2s3_config); i2s3_driver.set_tx_interrupt(true); i2s3_driver.set_error_interrupt(true); // set up an interrupt on WS pin let ws_pin = i2s3_driver.ws_pin_mut(); ws_pin.make_interrupt_source(&mut syscfg); ws_pin.trigger_on_edge(&mut exti, Edge::Rising); // we will enable i2s3 in interrupt ws_pin.enable_interrupt(&mut exti); i2s2_driver.enable(); ( Shared { i2s2_driver, i2s3_driver, exti, }, Local { logs_chan, adc_p, process_c, process_p, dac_c, }, init::Monotonics(), ) } #[idle(shared = [], local = [])] fn idle(_cx: idle::Context) ->! { #[allow(clippy::empty_loop)] loop {} } // Printing message directly in a i2s interrupt can cause timing issues. #[task(capacity = 10, local = [logs_chan])] fn log(cx: log::Context, message: &'static str)
// processing audio #[task(binds = SPI5, local = [count: u32 = 0,process_c,process_p])] fn process(cx: process::Context) { let count = cx.local.count; let process_c = cx.local.process_c; let process_p = cx.local.process_p; while let Some(mut smpl) = process_c.dequeue() { let period = 24000; if *count > period / 2 { smpl.0 >>= 1; } if *count > period / 4 && *count <= period * 3 / 4 { smpl.1 >>= 1; } *count += 1; if *count >= period { *count = 0; } process_p.enqueue(smpl).ok(); } } #[task( priority = 4, binds = SPI2, local = [frame_state: FrameState = LeftMsb, frame: (u32,u32) = (0,0),adc_p], shared = [i2s2_driver] )] fn i2s2(cx: i2s2::Context) { let frame_state = cx.local.frame_state; let frame = cx.local.frame; let adc_p = cx.local.adc_p; let i2s2_driver = cx.shared.i2s2_driver; let status = i2s2_driver.status(); // It's better to read first to avoid triggering ovr flag if status.rxne() { let data = i2s2_driver.read_data_register(); match (*frame_state, status.chside()) { (LeftMsb, Channel::Left) => { frame.0 = (data as u32) << 16; *frame_state = LeftLsb; } (LeftLsb, Channel::Left) => { frame.0 |= data as u32; *frame_state = RightMsb; } (RightMsb, Channel::Right) => { frame.1 = (data as u32) << 16; *frame_state = RightLsb; } (RightLsb, Channel::Right) => { frame.1 |= data as u32; // defer sample processing to another task let (l, r) = *frame; adc_p.enqueue((l as i32, r as i32)).ok(); rtic::pend(Interrupt::SPI5); *frame_state = LeftMsb; } // in case of ovr this resynchronize at start of new frame _ => *frame_state = LeftMsb, } } if status.ovr() { log::spawn("i2s2 Overrun").ok(); // sequence to delete ovr flag i2s2_driver.read_data_register(); i2s2_driver.status(); } } #[task( priority = 4, binds = SPI3, local = [frame_state: FrameState = LeftMsb,frame: (u32,u32) = (0,0),dac_c], shared = [i2s3_driver,exti] )] fn i2s3(cx: i2s3::Context) { let frame_state = cx.local.frame_state; let frame = cx.local.frame; let dac_c = cx.local.dac_c; let i2s3_driver = cx.shared.i2s3_driver; let exti = cx.shared.exti; let status = i2s3_driver.status(); // it's better to write data first to avoid to trigger udr flag if status.txe() { let data; match (*frame_state, status.chside()) { (LeftMsb, Channel::Left) => { let (l, r) = dac_c.dequeue().unwrap_or_default(); *frame = (l as u32, r as u32); data = (frame.0 >> 16) as u16; *frame_state = LeftLsb; } (LeftLsb, Channel::Left) => { data = (frame.0 & 0xFFFF) as u16; *frame_state = RightMsb; } (RightMsb, Channel::Right) => { data = (frame.1 >> 16) as u16; *frame_state = RightLsb; } (RightLsb, Channel::Right) => { data = (frame.1 & 0xFFFF) as u16; *frame_state = LeftMsb; } // in case of udr this resynchronize tracked and actual channel _ => { *frame_state = LeftMsb; data = 0; //garbage data to avoid additional underrun } } i2s3_driver.write_data_register(data); } if status.fre() { log::spawn("i2s3 Frame error").ok(); i2s3_driver.disable(); i2s3_driver.ws_pin_mut().enable_interrupt(exti); } if status.udr() { log::spawn("i2s3 udr").ok(); i2s3_driver.status(); i2s3_driver.write_data_register(0); } } // Look i2s3 WS line for (re) synchronisation #[task(priority = 4, binds = EXTI4, shared = [i2s3_driver,exti])] fn exti4(cx: exti4::Context) { let i2s3_driver = cx.shared.i2s3_driver; let exti = cx.shared.exti; let ws_pin = i2s3_driver.ws_pin_mut(); // check if that pin triggered the interrupt. if ws_pin.check_interrupt() { // Here we know ws pin is high because the interrupt was triggerd by it's rising edge ws_pin.clear_interrupt_pending_bit(); ws_pin.disable_interrupt(exti); i2s3_driver.write_data_register(0); i2s3_driver.enable(); } } } #[inline(never)] #[panic_handler] fn panic(info: &PanicInfo) ->! { rprintln!("{}", info); loop {} // You might need a compiler fence in here. }
{ writeln!(cx.local.logs_chan, "{}", message).unwrap(); }
identifier_body
rtic-i2s-audio-in-out.rs
//! # I2S example with rtic //! //! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong //! operation can trigger loud noise on the DAC output. //! //! # Hardware required //! //! * a STM32F411 based board //! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI //! * Audio signal at ADC input, and something to ear at DAC output. //! //! # Hardware Wiring //! //! The wiring assume using PCM1808 and PCM5102 module that can be found on Aliexpress, ebay, //! Amazon... //! //! ## Stm32 //! //! | stm32 | PCM1808 | PCM5102 | //! |-------------|---------|---------| //! | pb12 + pa4 | LRC | LCK | //! | pb13 + pc10 | BCK | BCK | //! | pc6 | SCK | SCK | //! | pc12 | | DIN | //! | pb15 | OUT | | //! //! ## PCM1808 ADC module //! //! | Pin | Connected To | //! |-----|----------------| //! | LIN | audio in left | //! | - | audio in gnd | //! | RIN | audio in right | //! | FMT | Gnd or NC | //! | MD1 | Gnd or NC | //! | MD0 | Gnd or NC | //! | Gnd | Gnd | //! | 3.3 | +3V3 | //! | +5V | +5v | //! | BCK | pb13 + pc10 | //! | OUT | pb15 | //! | LRC | pb12 + pa4 | //! | SCK | pc6 | //! //! ## PCM5102 module //! //! | Pin | Connected to | //! |-------|-----------------| //! | SCK | pc6 | //! | BCK | pb13 + pc10 | //! | DIN | pc12 | //! | LCK | pb12 + pa4 | //! | GND | Gnd | //! | VIN | +3V3 | //! | FLT | Gnd or +3V3 | //! | DEMP | Gnd | //! | XSMT | +3V3 | //! | A3V3 | | //! | AGND | audio out gnd | //! | ROUT | audio out left | //! | LROUT | audio out right | //! //! Notes: on the module (not the chip) A3V3 is connected to VIN and AGND is connected to GND //! //! //! Expected behavior: you should ear a crappy stereo effect. This is actually 2 square tremolo //! applied with a 90 degrees phase shift. #![no_std] #![no_main] use core::panic::PanicInfo; use rtt_target::rprintln; use stm32f4xx_hal as hal; #[rtic::app(device = stm32f4xx_hal::pac, peripherals = true,dispatchers = [EXTI0, EXTI1, EXTI2])] mod app { use core::fmt::Write; use super::hal; use hal::gpio::{Edge, NoPin}; use hal::i2s::stm32_i2s_v12x::driver::*; use hal::i2s::I2s; use hal::pac::Interrupt; use hal::pac::{EXTI, SPI2, SPI3}; use hal::prelude::*; use heapless::spsc::*; use rtt_target::{rprintln, rtt_init, set_print_channel}; type I2s2Driver = I2sDriver<I2s<SPI2>, Master, Receive, Philips>; type I2s3Driver = I2sDriver<I2s<SPI3>, Slave, Transmit, Philips>; // Part of the frame we currently transmit or receive #[derive(Copy, Clone)] pub enum FrameState { LeftMsb, LeftLsb, RightMsb, RightLsb, } use FrameState::{LeftLsb, LeftMsb, RightLsb, RightMsb}; impl Default for FrameState { fn default() -> Self { Self::LeftMsb } } #[shared] struct Shared { #[lock_free] i2s2_driver: I2s2Driver, #[lock_free] i2s3_driver: I2s3Driver, #[lock_free] exti: EXTI, } #[local] struct Local { logs_chan: rtt_target::UpChannel, adc_p: Producer<'static, (i32, i32), 2>, process_c: Consumer<'static, (i32, i32), 2>, process_p: Producer<'static, (i32, i32), 2>, dac_c: Consumer<'static, (i32, i32), 2>, } #[init(local = [queue_1: Queue<(i32,i32), 2> = Queue::new(),queue_2: Queue<(i32,i32), 2> = Queue::new()])] fn init(cx: init::Context) -> (Shared, Local, init::Monotonics) { let queue_1 = cx.local.queue_1; let queue_2 = cx.local.queue_2; let channels = rtt_init! { up: { 0: { size: 128 name: "Logs" } 1: { size: 128 name: "Panics" } } }; let logs_chan = channels.up.0; let panics_chan = channels.up.1; set_print_channel(panics_chan); let (adc_p, process_c) = queue_1.split(); let (process_p, dac_c) = queue_2.split(); let device = cx.device; let mut syscfg = device.SYSCFG.constrain(); let mut exti = device.EXTI; let gpioa = device.GPIOA.split(); let gpiob = device.GPIOB.split(); let gpioc = device.GPIOC.split(); let rcc = device.RCC.constrain(); let clocks = rcc .cfgr .use_hse(8u32.MHz()) .sysclk(96.MHz()) .hclk(96.MHz()) .pclk1(50.MHz()) .pclk2(100.MHz()) .i2s_clk(61440.kHz()) .freeze(); // I2S pins: (WS, CK, MCLK, SD) for I2S2 let i2s2_pins = ( gpiob.pb12, //WS gpiob.pb13, //CK gpioc.pc6, //MCK gpiob.pb15, //SD ); let i2s2 = I2s::new(device.SPI2, i2s2_pins, &clocks); let i2s2_config = I2sDriverConfig::new_master() .receive() .standard(Philips) .data_format(DataFormat::Data24Channel32) .master_clock(true) .request_frequency(48_000); let mut i2s2_driver = I2sDriver::new(i2s2, i2s2_config); rprintln!("actual sample rate is {}", i2s2_driver.sample_rate()); i2s2_driver.set_rx_interrupt(true); i2s2_driver.set_error_interrupt(true); // I2S3 pins: (WS, CK, NoPin, SD) for I2S3 let i2s3_pins = (gpioa.pa4, gpioc.pc10, NoPin::new(), gpioc.pc12); let i2s3 = I2s::new(device.SPI3, i2s3_pins, &clocks); let i2s3_config = i2s2_config.to_slave().transmit(); let mut i2s3_driver = I2sDriver::new(i2s3, i2s3_config); i2s3_driver.set_tx_interrupt(true); i2s3_driver.set_error_interrupt(true); // set up an interrupt on WS pin let ws_pin = i2s3_driver.ws_pin_mut(); ws_pin.make_interrupt_source(&mut syscfg); ws_pin.trigger_on_edge(&mut exti, Edge::Rising); // we will enable i2s3 in interrupt ws_pin.enable_interrupt(&mut exti); i2s2_driver.enable(); ( Shared { i2s2_driver, i2s3_driver, exti, }, Local { logs_chan, adc_p, process_c, process_p, dac_c, }, init::Monotonics(), ) } #[idle(shared = [], local = [])] fn idle(_cx: idle::Context) ->! { #[allow(clippy::empty_loop)] loop {} } // Printing message directly in a i2s interrupt can cause timing issues. #[task(capacity = 10, local = [logs_chan])] fn log(cx: log::Context, message: &'static str) { writeln!(cx.local.logs_chan, "{}", message).unwrap(); } // processing audio #[task(binds = SPI5, local = [count: u32 = 0,process_c,process_p])] fn process(cx: process::Context) { let count = cx.local.count; let process_c = cx.local.process_c; let process_p = cx.local.process_p; while let Some(mut smpl) = process_c.dequeue() { let period = 24000; if *count > period / 2 { smpl.0 >>= 1; } if *count > period / 4 && *count <= period * 3 / 4 { smpl.1 >>= 1; } *count += 1; if *count >= period { *count = 0; } process_p.enqueue(smpl).ok(); } } #[task( priority = 4, binds = SPI2, local = [frame_state: FrameState = LeftMsb, frame: (u32,u32) = (0,0),adc_p], shared = [i2s2_driver] )] fn
(cx: i2s2::Context) { let frame_state = cx.local.frame_state; let frame = cx.local.frame; let adc_p = cx.local.adc_p; let i2s2_driver = cx.shared.i2s2_driver; let status = i2s2_driver.status(); // It's better to read first to avoid triggering ovr flag if status.rxne() { let data = i2s2_driver.read_data_register(); match (*frame_state, status.chside()) { (LeftMsb, Channel::Left) => { frame.0 = (data as u32) << 16; *frame_state = LeftLsb; } (LeftLsb, Channel::Left) => { frame.0 |= data as u32; *frame_state = RightMsb; } (RightMsb, Channel::Right) => { frame.1 = (data as u32) << 16; *frame_state = RightLsb; } (RightLsb, Channel::Right) => { frame.1 |= data as u32; // defer sample processing to another task let (l, r) = *frame; adc_p.enqueue((l as i32, r as i32)).ok(); rtic::pend(Interrupt::SPI5); *frame_state = LeftMsb; } // in case of ovr this resynchronize at start of new frame _ => *frame_state = LeftMsb, } } if status.ovr() { log::spawn("i2s2 Overrun").ok(); // sequence to delete ovr flag i2s2_driver.read_data_register(); i2s2_driver.status(); } } #[task( priority = 4, binds = SPI3, local = [frame_state: FrameState = LeftMsb,frame: (u32,u32) = (0,0),dac_c], shared = [i2s3_driver,exti] )] fn i2s3(cx: i2s3::Context) { let frame_state = cx.local.frame_state; let frame = cx.local.frame; let dac_c = cx.local.dac_c; let i2s3_driver = cx.shared.i2s3_driver; let exti = cx.shared.exti; let status = i2s3_driver.status(); // it's better to write data first to avoid to trigger udr flag if status.txe() { let data; match (*frame_state, status.chside()) { (LeftMsb, Channel::Left) => { let (l, r) = dac_c.dequeue().unwrap_or_default(); *frame = (l as u32, r as u32); data = (frame.0 >> 16) as u16; *frame_state = LeftLsb; } (LeftLsb, Channel::Left) => { data = (frame.0 & 0xFFFF) as u16; *frame_state = RightMsb; } (RightMsb, Channel::Right) => { data = (frame.1 >> 16) as u16; *frame_state = RightLsb; } (RightLsb, Channel::Right) => { data = (frame.1 & 0xFFFF) as u16; *frame_state = LeftMsb; } // in case of udr this resynchronize tracked and actual channel _ => { *frame_state = LeftMsb; data = 0; //garbage data to avoid additional underrun } } i2s3_driver.write_data_register(data); } if status.fre() { log::spawn("i2s3 Frame error").ok(); i2s3_driver.disable(); i2s3_driver.ws_pin_mut().enable_interrupt(exti); } if status.udr() { log::spawn("i2s3 udr").ok(); i2s3_driver.status(); i2s3_driver.write_data_register(0); } } // Look i2s3 WS line for (re) synchronisation #[task(priority = 4, binds = EXTI4, shared = [i2s3_driver,exti])] fn exti4(cx: exti4::Context) { let i2s3_driver = cx.shared.i2s3_driver; let exti = cx.shared.exti; let ws_pin = i2s3_driver.ws_pin_mut(); // check if that pin triggered the interrupt. if ws_pin.check_interrupt() { // Here we know ws pin is high because the interrupt was triggerd by it's rising edge ws_pin.clear_interrupt_pending_bit(); ws_pin.disable_interrupt(exti); i2s3_driver.write_data_register(0); i2s3_driver.enable(); } } } #[inline(never)] #[panic_handler] fn panic(info: &PanicInfo) ->! { rprintln!("{}", info); loop {} // You might need a compiler fence in here. }
i2s2
identifier_name
rtic-i2s-audio-in-out.rs
//! # I2S example with rtic //! //! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong //! operation can trigger loud noise on the DAC output. //! //! # Hardware required //! //! * a STM32F411 based board //! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI //! * Audio signal at ADC input, and something to ear at DAC output. //! //! # Hardware Wiring //! //! The wiring assume using PCM1808 and PCM5102 module that can be found on Aliexpress, ebay, //! Amazon... //! //! ## Stm32 //! //! | stm32 | PCM1808 | PCM5102 | //! |-------------|---------|---------| //! | pb12 + pa4 | LRC | LCK | //! | pb13 + pc10 | BCK | BCK | //! | pc6 | SCK | SCK | //! | pc12 | | DIN | //! | pb15 | OUT | | //! //! ## PCM1808 ADC module //! //! | Pin | Connected To | //! |-----|----------------| //! | LIN | audio in left | //! | - | audio in gnd | //! | RIN | audio in right | //! | FMT | Gnd or NC | //! | MD1 | Gnd or NC | //! | MD0 | Gnd or NC | //! | Gnd | Gnd | //! | 3.3 | +3V3 | //! | +5V | +5v | //! | BCK | pb13 + pc10 | //! | OUT | pb15 | //! | LRC | pb12 + pa4 | //! | SCK | pc6 | //! //! ## PCM5102 module //! //! | Pin | Connected to | //! |-------|-----------------| //! | SCK | pc6 | //! | BCK | pb13 + pc10 | //! | DIN | pc12 | //! | LCK | pb12 + pa4 | //! | GND | Gnd | //! | VIN | +3V3 | //! | FLT | Gnd or +3V3 | //! | DEMP | Gnd | //! | XSMT | +3V3 | //! | A3V3 | | //! | AGND | audio out gnd | //! | ROUT | audio out left | //! | LROUT | audio out right | //! //! Notes: on the module (not the chip) A3V3 is connected to VIN and AGND is connected to GND //! //! //! Expected behavior: you should ear a crappy stereo effect. This is actually 2 square tremolo //! applied with a 90 degrees phase shift. #![no_std] #![no_main] use core::panic::PanicInfo; use rtt_target::rprintln; use stm32f4xx_hal as hal; #[rtic::app(device = stm32f4xx_hal::pac, peripherals = true,dispatchers = [EXTI0, EXTI1, EXTI2])] mod app { use core::fmt::Write; use super::hal; use hal::gpio::{Edge, NoPin}; use hal::i2s::stm32_i2s_v12x::driver::*; use hal::i2s::I2s; use hal::pac::Interrupt; use hal::pac::{EXTI, SPI2, SPI3}; use hal::prelude::*; use heapless::spsc::*; use rtt_target::{rprintln, rtt_init, set_print_channel}; type I2s2Driver = I2sDriver<I2s<SPI2>, Master, Receive, Philips>; type I2s3Driver = I2sDriver<I2s<SPI3>, Slave, Transmit, Philips>; // Part of the frame we currently transmit or receive #[derive(Copy, Clone)] pub enum FrameState { LeftMsb, LeftLsb, RightMsb, RightLsb, } use FrameState::{LeftLsb, LeftMsb, RightLsb, RightMsb}; impl Default for FrameState { fn default() -> Self { Self::LeftMsb } } #[shared] struct Shared { #[lock_free] i2s2_driver: I2s2Driver, #[lock_free] i2s3_driver: I2s3Driver, #[lock_free] exti: EXTI, } #[local] struct Local { logs_chan: rtt_target::UpChannel, adc_p: Producer<'static, (i32, i32), 2>, process_c: Consumer<'static, (i32, i32), 2>, process_p: Producer<'static, (i32, i32), 2>, dac_c: Consumer<'static, (i32, i32), 2>, } #[init(local = [queue_1: Queue<(i32,i32), 2> = Queue::new(),queue_2: Queue<(i32,i32), 2> = Queue::new()])] fn init(cx: init::Context) -> (Shared, Local, init::Monotonics) { let queue_1 = cx.local.queue_1; let queue_2 = cx.local.queue_2; let channels = rtt_init! { up: { 0: { size: 128 name: "Logs" } 1: { size: 128 name: "Panics" } } }; let logs_chan = channels.up.0; let panics_chan = channels.up.1; set_print_channel(panics_chan); let (adc_p, process_c) = queue_1.split(); let (process_p, dac_c) = queue_2.split(); let device = cx.device; let mut syscfg = device.SYSCFG.constrain(); let mut exti = device.EXTI;
let gpiob = device.GPIOB.split(); let gpioc = device.GPIOC.split(); let rcc = device.RCC.constrain(); let clocks = rcc .cfgr .use_hse(8u32.MHz()) .sysclk(96.MHz()) .hclk(96.MHz()) .pclk1(50.MHz()) .pclk2(100.MHz()) .i2s_clk(61440.kHz()) .freeze(); // I2S pins: (WS, CK, MCLK, SD) for I2S2 let i2s2_pins = ( gpiob.pb12, //WS gpiob.pb13, //CK gpioc.pc6, //MCK gpiob.pb15, //SD ); let i2s2 = I2s::new(device.SPI2, i2s2_pins, &clocks); let i2s2_config = I2sDriverConfig::new_master() .receive() .standard(Philips) .data_format(DataFormat::Data24Channel32) .master_clock(true) .request_frequency(48_000); let mut i2s2_driver = I2sDriver::new(i2s2, i2s2_config); rprintln!("actual sample rate is {}", i2s2_driver.sample_rate()); i2s2_driver.set_rx_interrupt(true); i2s2_driver.set_error_interrupt(true); // I2S3 pins: (WS, CK, NoPin, SD) for I2S3 let i2s3_pins = (gpioa.pa4, gpioc.pc10, NoPin::new(), gpioc.pc12); let i2s3 = I2s::new(device.SPI3, i2s3_pins, &clocks); let i2s3_config = i2s2_config.to_slave().transmit(); let mut i2s3_driver = I2sDriver::new(i2s3, i2s3_config); i2s3_driver.set_tx_interrupt(true); i2s3_driver.set_error_interrupt(true); // set up an interrupt on WS pin let ws_pin = i2s3_driver.ws_pin_mut(); ws_pin.make_interrupt_source(&mut syscfg); ws_pin.trigger_on_edge(&mut exti, Edge::Rising); // we will enable i2s3 in interrupt ws_pin.enable_interrupt(&mut exti); i2s2_driver.enable(); ( Shared { i2s2_driver, i2s3_driver, exti, }, Local { logs_chan, adc_p, process_c, process_p, dac_c, }, init::Monotonics(), ) } #[idle(shared = [], local = [])] fn idle(_cx: idle::Context) ->! { #[allow(clippy::empty_loop)] loop {} } // Printing message directly in a i2s interrupt can cause timing issues. #[task(capacity = 10, local = [logs_chan])] fn log(cx: log::Context, message: &'static str) { writeln!(cx.local.logs_chan, "{}", message).unwrap(); } // processing audio #[task(binds = SPI5, local = [count: u32 = 0,process_c,process_p])] fn process(cx: process::Context) { let count = cx.local.count; let process_c = cx.local.process_c; let process_p = cx.local.process_p; while let Some(mut smpl) = process_c.dequeue() { let period = 24000; if *count > period / 2 { smpl.0 >>= 1; } if *count > period / 4 && *count <= period * 3 / 4 { smpl.1 >>= 1; } *count += 1; if *count >= period { *count = 0; } process_p.enqueue(smpl).ok(); } } #[task( priority = 4, binds = SPI2, local = [frame_state: FrameState = LeftMsb, frame: (u32,u32) = (0,0),adc_p], shared = [i2s2_driver] )] fn i2s2(cx: i2s2::Context) { let frame_state = cx.local.frame_state; let frame = cx.local.frame; let adc_p = cx.local.adc_p; let i2s2_driver = cx.shared.i2s2_driver; let status = i2s2_driver.status(); // It's better to read first to avoid triggering ovr flag if status.rxne() { let data = i2s2_driver.read_data_register(); match (*frame_state, status.chside()) { (LeftMsb, Channel::Left) => { frame.0 = (data as u32) << 16; *frame_state = LeftLsb; } (LeftLsb, Channel::Left) => { frame.0 |= data as u32; *frame_state = RightMsb; } (RightMsb, Channel::Right) => { frame.1 = (data as u32) << 16; *frame_state = RightLsb; } (RightLsb, Channel::Right) => { frame.1 |= data as u32; // defer sample processing to another task let (l, r) = *frame; adc_p.enqueue((l as i32, r as i32)).ok(); rtic::pend(Interrupt::SPI5); *frame_state = LeftMsb; } // in case of ovr this resynchronize at start of new frame _ => *frame_state = LeftMsb, } } if status.ovr() { log::spawn("i2s2 Overrun").ok(); // sequence to delete ovr flag i2s2_driver.read_data_register(); i2s2_driver.status(); } } #[task( priority = 4, binds = SPI3, local = [frame_state: FrameState = LeftMsb,frame: (u32,u32) = (0,0),dac_c], shared = [i2s3_driver,exti] )] fn i2s3(cx: i2s3::Context) { let frame_state = cx.local.frame_state; let frame = cx.local.frame; let dac_c = cx.local.dac_c; let i2s3_driver = cx.shared.i2s3_driver; let exti = cx.shared.exti; let status = i2s3_driver.status(); // it's better to write data first to avoid to trigger udr flag if status.txe() { let data; match (*frame_state, status.chside()) { (LeftMsb, Channel::Left) => { let (l, r) = dac_c.dequeue().unwrap_or_default(); *frame = (l as u32, r as u32); data = (frame.0 >> 16) as u16; *frame_state = LeftLsb; } (LeftLsb, Channel::Left) => { data = (frame.0 & 0xFFFF) as u16; *frame_state = RightMsb; } (RightMsb, Channel::Right) => { data = (frame.1 >> 16) as u16; *frame_state = RightLsb; } (RightLsb, Channel::Right) => { data = (frame.1 & 0xFFFF) as u16; *frame_state = LeftMsb; } // in case of udr this resynchronize tracked and actual channel _ => { *frame_state = LeftMsb; data = 0; //garbage data to avoid additional underrun } } i2s3_driver.write_data_register(data); } if status.fre() { log::spawn("i2s3 Frame error").ok(); i2s3_driver.disable(); i2s3_driver.ws_pin_mut().enable_interrupt(exti); } if status.udr() { log::spawn("i2s3 udr").ok(); i2s3_driver.status(); i2s3_driver.write_data_register(0); } } // Look i2s3 WS line for (re) synchronisation #[task(priority = 4, binds = EXTI4, shared = [i2s3_driver,exti])] fn exti4(cx: exti4::Context) { let i2s3_driver = cx.shared.i2s3_driver; let exti = cx.shared.exti; let ws_pin = i2s3_driver.ws_pin_mut(); // check if that pin triggered the interrupt. if ws_pin.check_interrupt() { // Here we know ws pin is high because the interrupt was triggerd by it's rising edge ws_pin.clear_interrupt_pending_bit(); ws_pin.disable_interrupt(exti); i2s3_driver.write_data_register(0); i2s3_driver.enable(); } } } #[inline(never)] #[panic_handler] fn panic(info: &PanicInfo) ->! { rprintln!("{}", info); loop {} // You might need a compiler fence in here. }
let gpioa = device.GPIOA.split();
random_line_split
crypto_box.rs
use crate::internal::rayon::rayon_exec; use crate::internal::x25519; use block_padding::Padding; use crypto_box as lib_crypto_box; use std::sync::Arc; /// Length of the crypto box aead nonce. /// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly. pub const NONCE_BYTES: usize = 24; /// The size of blocks to pad encrypted data to. /// We have no idea how big incoming data is, but probably it is generally smallish. /// Devs can always do their own padding on top of this, but we want some safety for unpadded data. /// Libsodium optionally supports ISO 7816-4 padding algorithm. /// @see https://doc.libsodium.org/padding#algorithm pub const BLOCK_PADDING_SIZE: usize = 32; /// The delimiter for padding as per ISO 7816-4. pub const BLOCK_PADDING_DELIMITER: u8 = 0x80; /// Newtype for the nonce for safety. #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxNonce([u8; NONCE_BYTES]); impl CryptoBoxNonce { async fn new_random() -> Self { rayon_exec(move || { let mut rng = rand::thread_rng(); let mut bytes = [0; NONCE_BYTES]; // We rely on the lib_crypto_box nonce length being the same as what we expect. // Should be a reasonably safe bet as 24 bytes is dictated by the crypto_box algorithm. bytes.copy_from_slice( lib_crypto_box::generate_nonce(&mut rng).as_slice(), ); Self(bytes) }) .await } } impl AsRef<[u8; NONCE_BYTES]> for CryptoBoxNonce { fn as_ref(&self) -> &[u8; NONCE_BYTES] { &self.0 } } impl AsRef<[u8]> for CryptoBoxNonce { fn as_ref(&self) -> &[u8] { &self.0 } } impl From<[u8; NONCE_BYTES]> for CryptoBoxNonce { fn from(array: [u8; NONCE_BYTES]) -> Self { Self(array) } } impl std::convert::TryFrom<&[u8]> for CryptoBoxNonce { type Error = crate::error::LairError; fn try_from(slice: &[u8]) -> Result<Self, Self::Error> { if slice.len() == NONCE_BYTES { let mut inner = [0; NONCE_BYTES]; inner.copy_from_slice(slice); Ok(Self(inner)) } else { Err(crate::error::LairError::CryptoBoxNonceLength) } } } impl CryptoBoxNonce { /// Always NONCE_BYTES. pub fn len(&self) -> usize { NONCE_BYTES } /// For clippy. pub fn is_empty(&self) -> bool { self.len() == 0 } } /// "Additional associated data" as per the aead rust crate Payload. /// May be empty. Must be valid if present. pub struct CryptoBoxAad(Vec<u8>); /// The nonce and encrypted data together. /// @todo include additional associated data? #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxEncryptedData { /// The nonce generated during encryption. /// We never allow nonce to be set externally so we need to return it. pub nonce: CryptoBoxNonce, /// The encrypted version of our input data. #[allow(clippy::rc_buffer)] pub encrypted_data: Arc<Vec<u8>>, } /// Data to be encrypted. /// Not associated with a nonce because we enforce random nonces. #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxData { /// Data to be encrypted. #[allow(clippy::rc_buffer)] pub data: Arc<Vec<u8>>, } impl AsRef<[u8]> for CryptoBoxData { fn as_ref(&self) -> &[u8] { self.data.as_ref() } } impl CryptoBoxData { /// Length of newtype is length of inner. pub fn len(&self) -> usize { AsRef::<[u8]>::as_ref(self).len() } /// For clippy. pub fn is_empty(&self) -> bool { self.len() == 0 } } impl From<Vec<u8>> for CryptoBoxData { fn from(v: Vec<u8>) -> Self { Self { data: Arc::new(v) } } } /// @todo all of this can be opened up to be more flexible over time. /// Eventually all possible input such as nonces and associated data should be settable by the /// external interface. /// In the short term everyone is getting their heads around the 80/20 usage patterns that are as /// safe as we can possibly make them to avoid subtleties that lead to nonce or key re-use etc. /// /// Wrapper around crypto_box from whatever lib we use. /// No BYO nonces. Nonces always random and returned as part of `CryptoBoxEncryptedData`. /// No BYO algorithms (cipher agility). Algorithm always X25519XSalsa20Poly1305. /// Currently no additional associated data but DNA space may be included in the future. /// The sender's private key encrypts _for_ the recipient's pubkey. /// /// FYI allowing nonces could be dangerous as it's exposed as a general purpose authenticated /// encryption mechanism (or will be) via. crypto_box from libsodium. /// The main thing is that if a secret/nonce combination is _ever_ used more than once it /// completely breaks encryption. // /// Example ways a nonce could accidentally be reused: /// - If two DNAs are the same or similar (e.g. cloned DNAs) then they will have the same /// nonce generation logic, so may create collisions when run in parallel. /// - Collision of initialization vectors in a key exchange/crypto session. /// - Use of a counter based nonce in a way that isn't 100% reliably incrementing. /// /// Example ways a secret could accidentally be reused: /// - If two agents both commit their pubkeys then share them with each other, then the same /// shared key will be 'negotiated' by x25519 ECDH every time it is called. /// - If a pubkey is used across two different DNAs the secrets will collide at the lair /// and the DNAs won't have a way to co-ordinate or detect this. /// /// E.g. Ring is very wary of secret key re-use e.g. it makes explicit the use-case where an /// ephemeral (single use) key is generated to establish an ephemeral (single use) shared /// key. Our use-case is the libsodium `crypto_box` function that uses an x25519 keypair to /// perform authenticated encryption, so it makes more sense for us to be storing our /// private keys for later use BUT see above for the dangers of key re-use that the app dev /// really needs to be wary of. /// /// @see https://eprint.iacr.org/2019/519.pdf for 'context separable interfaces' pub async fn crypto_box( sender: x25519::X25519PrivKey, recipient: x25519::X25519PubKey, data: Arc<CryptoBoxData>, ) -> crate::error::LairResult<CryptoBoxEncryptedData> { let nonce = CryptoBoxNonce::new_random().await; rayon_exec(move || { use lib_crypto_box::aead::Aead; let sender_box = lib_crypto_box::SalsaBox::new(recipient.as_ref(), sender.as_ref()); // It's actually easier and clearer to directly pad the vector than use the block_padding // crate, as that is optimised for blocks. let mut to_encrypt = data.data.to_vec(); let padding_delimiter = vec![BLOCK_PADDING_DELIMITER]; let padding = vec![ 0x0; BLOCK_PADDING_SIZE - (data.data.len() + 1) % BLOCK_PADDING_SIZE ]; to_encrypt.extend(padding_delimiter); to_encrypt.extend(padding); let encrypted_data = Arc::new(sender_box.encrypt( AsRef::<[u8; NONCE_BYTES]>::as_ref(&nonce).into(), to_encrypt.as_slice(), )?); // @todo do we want associated data to enforce the originating DHT space? // https://eprint.iacr.org/2019/519.pdf for 'context separable interfaces' Ok(CryptoBoxEncryptedData { nonce, encrypted_data, }) }) .await } /// Wrapper around crypto_box_open from whatever lib we use. /// Exact inverse of `crypto_box_open` so nonce must be provided in `CryptoBoxEncryptedData`. /// The recipient's private key encrypts _from_ the sender's pubkey. pub async fn crypto_box_open( recipient: x25519::X25519PrivKey, sender: x25519::X25519PubKey, encrypted_data: Arc<CryptoBoxEncryptedData>, ) -> crate::error::LairResult<Option<CryptoBoxData>> { rayon_exec(move || { use lib_crypto_box::aead::Aead; let recipient_box = lib_crypto_box::SalsaBox::new(sender.as_ref(), recipient.as_ref()); match recipient_box.decrypt( AsRef::<[u8; NONCE_BYTES]>::as_ref(&encrypted_data.nonce).into(), encrypted_data.encrypted_data.as_slice(), ) { Ok(decrypted_data) =>
Err(_) => Ok(None), } }) .await } #[cfg(test)] mod tests { use super::*; #[tokio::test(flavor = "multi_thread")] async fn it_can_encrypt_and_decrypt() { for input in [ // Empty vec. vec![], // Small vec. vec![0], vec![0, 1, 2], vec![0, 1, 2, 3], // Vec ending in padding delimiter. vec![0x80], vec![0, 0x80], vec![0x80; BLOCK_PADDING_SIZE - 1], vec![0x80; BLOCK_PADDING_SIZE], vec![0x80; BLOCK_PADDING_SIZE + 1], // Larger vec. vec![0; BLOCK_PADDING_SIZE - 1], vec![0; BLOCK_PADDING_SIZE], vec![0; BLOCK_PADDING_SIZE + 1], vec![0; BLOCK_PADDING_SIZE * 2 - 1], vec![0; BLOCK_PADDING_SIZE * 2], vec![0; BLOCK_PADDING_SIZE * 2 + 1], ] .iter() { // Fresh keys. let alice = crate::internal::x25519::x25519_keypair_new_from_entropy() .await .unwrap(); let bob = crate::internal::x25519::x25519_keypair_new_from_entropy() .await .unwrap(); let data = CryptoBoxData { data: Arc::new(input.to_vec()), }; // from alice to bob. let encrypted_data = super::crypto_box( alice.priv_key, bob.pub_key, Arc::new(data.clone()), ) .await .unwrap(); // The length excluding the 16 byte overhead should always be a multiple of 32 as this // is our padding. assert_eq!((encrypted_data.encrypted_data.len() - 16) % 32, 0); let decrypted_data = super::crypto_box_open( bob.priv_key, alice.pub_key, Arc::new(encrypted_data), ) .await .unwrap(); // If we can decrypt we managed to pad and unpad as well as encrypt and decrypt. assert_eq!(&decrypted_data, &Some(data)); } } }
{ match block_padding::Iso7816::unpad(&decrypted_data) { // @todo do we want associated data to enforce the originating DHT space? Ok(unpadded) => Ok(Some(CryptoBoxData { data: Arc::new(unpadded.to_vec()), })), Err(_) => Ok(None), } }
conditional_block
crypto_box.rs
use crate::internal::rayon::rayon_exec; use crate::internal::x25519; use block_padding::Padding; use crypto_box as lib_crypto_box; use std::sync::Arc; /// Length of the crypto box aead nonce. /// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly. pub const NONCE_BYTES: usize = 24; /// The size of blocks to pad encrypted data to. /// We have no idea how big incoming data is, but probably it is generally smallish. /// Devs can always do their own padding on top of this, but we want some safety for unpadded data. /// Libsodium optionally supports ISO 7816-4 padding algorithm. /// @see https://doc.libsodium.org/padding#algorithm pub const BLOCK_PADDING_SIZE: usize = 32; /// The delimiter for padding as per ISO 7816-4. pub const BLOCK_PADDING_DELIMITER: u8 = 0x80; /// Newtype for the nonce for safety. #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxNonce([u8; NONCE_BYTES]); impl CryptoBoxNonce { async fn new_random() -> Self { rayon_exec(move || { let mut rng = rand::thread_rng(); let mut bytes = [0; NONCE_BYTES]; // We rely on the lib_crypto_box nonce length being the same as what we expect. // Should be a reasonably safe bet as 24 bytes is dictated by the crypto_box algorithm. bytes.copy_from_slice( lib_crypto_box::generate_nonce(&mut rng).as_slice(), ); Self(bytes) }) .await } } impl AsRef<[u8; NONCE_BYTES]> for CryptoBoxNonce { fn as_ref(&self) -> &[u8; NONCE_BYTES] { &self.0 } } impl AsRef<[u8]> for CryptoBoxNonce { fn as_ref(&self) -> &[u8] { &self.0 } } impl From<[u8; NONCE_BYTES]> for CryptoBoxNonce { fn from(array: [u8; NONCE_BYTES]) -> Self { Self(array) } } impl std::convert::TryFrom<&[u8]> for CryptoBoxNonce { type Error = crate::error::LairError; fn try_from(slice: &[u8]) -> Result<Self, Self::Error> { if slice.len() == NONCE_BYTES { let mut inner = [0; NONCE_BYTES]; inner.copy_from_slice(slice); Ok(Self(inner)) } else { Err(crate::error::LairError::CryptoBoxNonceLength) } } } impl CryptoBoxNonce { /// Always NONCE_BYTES. pub fn len(&self) -> usize { NONCE_BYTES } /// For clippy. pub fn is_empty(&self) -> bool { self.len() == 0 } } /// "Additional associated data" as per the aead rust crate Payload. /// May be empty. Must be valid if present. pub struct CryptoBoxAad(Vec<u8>); /// The nonce and encrypted data together. /// @todo include additional associated data? #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxEncryptedData { /// The nonce generated during encryption. /// We never allow nonce to be set externally so we need to return it. pub nonce: CryptoBoxNonce, /// The encrypted version of our input data. #[allow(clippy::rc_buffer)] pub encrypted_data: Arc<Vec<u8>>, } /// Data to be encrypted. /// Not associated with a nonce because we enforce random nonces. #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxData { /// Data to be encrypted. #[allow(clippy::rc_buffer)] pub data: Arc<Vec<u8>>, } impl AsRef<[u8]> for CryptoBoxData { fn as_ref(&self) -> &[u8] { self.data.as_ref() } } impl CryptoBoxData { /// Length of newtype is length of inner. pub fn len(&self) -> usize { AsRef::<[u8]>::as_ref(self).len() } /// For clippy. pub fn is_empty(&self) -> bool { self.len() == 0 } } impl From<Vec<u8>> for CryptoBoxData { fn from(v: Vec<u8>) -> Self { Self { data: Arc::new(v) } } } /// @todo all of this can be opened up to be more flexible over time. /// Eventually all possible input such as nonces and associated data should be settable by the /// external interface. /// In the short term everyone is getting their heads around the 80/20 usage patterns that are as /// safe as we can possibly make them to avoid subtleties that lead to nonce or key re-use etc. /// /// Wrapper around crypto_box from whatever lib we use. /// No BYO nonces. Nonces always random and returned as part of `CryptoBoxEncryptedData`. /// No BYO algorithms (cipher agility). Algorithm always X25519XSalsa20Poly1305. /// Currently no additional associated data but DNA space may be included in the future. /// The sender's private key encrypts _for_ the recipient's pubkey. /// /// FYI allowing nonces could be dangerous as it's exposed as a general purpose authenticated /// encryption mechanism (or will be) via. crypto_box from libsodium. /// The main thing is that if a secret/nonce combination is _ever_ used more than once it /// completely breaks encryption. // /// Example ways a nonce could accidentally be reused: /// - If two DNAs are the same or similar (e.g. cloned DNAs) then they will have the same /// nonce generation logic, so may create collisions when run in parallel. /// - Collision of initialization vectors in a key exchange/crypto session. /// - Use of a counter based nonce in a way that isn't 100% reliably incrementing. /// /// Example ways a secret could accidentally be reused: /// - If two agents both commit their pubkeys then share them with each other, then the same /// shared key will be 'negotiated' by x25519 ECDH every time it is called. /// - If a pubkey is used across two different DNAs the secrets will collide at the lair /// and the DNAs won't have a way to co-ordinate or detect this. /// /// E.g. Ring is very wary of secret key re-use e.g. it makes explicit the use-case where an /// ephemeral (single use) key is generated to establish an ephemeral (single use) shared /// key. Our use-case is the libsodium `crypto_box` function that uses an x25519 keypair to /// perform authenticated encryption, so it makes more sense for us to be storing our /// private keys for later use BUT see above for the dangers of key re-use that the app dev /// really needs to be wary of. /// /// @see https://eprint.iacr.org/2019/519.pdf for 'context separable interfaces' pub async fn crypto_box( sender: x25519::X25519PrivKey, recipient: x25519::X25519PubKey, data: Arc<CryptoBoxData>, ) -> crate::error::LairResult<CryptoBoxEncryptedData> { let nonce = CryptoBoxNonce::new_random().await; rayon_exec(move || { use lib_crypto_box::aead::Aead; let sender_box = lib_crypto_box::SalsaBox::new(recipient.as_ref(), sender.as_ref()); // It's actually easier and clearer to directly pad the vector than use the block_padding // crate, as that is optimised for blocks. let mut to_encrypt = data.data.to_vec(); let padding_delimiter = vec![BLOCK_PADDING_DELIMITER]; let padding = vec![ 0x0;
]; to_encrypt.extend(padding_delimiter); to_encrypt.extend(padding); let encrypted_data = Arc::new(sender_box.encrypt( AsRef::<[u8; NONCE_BYTES]>::as_ref(&nonce).into(), to_encrypt.as_slice(), )?); // @todo do we want associated data to enforce the originating DHT space? // https://eprint.iacr.org/2019/519.pdf for 'context separable interfaces' Ok(CryptoBoxEncryptedData { nonce, encrypted_data, }) }) .await } /// Wrapper around crypto_box_open from whatever lib we use. /// Exact inverse of `crypto_box_open` so nonce must be provided in `CryptoBoxEncryptedData`. /// The recipient's private key encrypts _from_ the sender's pubkey. pub async fn crypto_box_open( recipient: x25519::X25519PrivKey, sender: x25519::X25519PubKey, encrypted_data: Arc<CryptoBoxEncryptedData>, ) -> crate::error::LairResult<Option<CryptoBoxData>> { rayon_exec(move || { use lib_crypto_box::aead::Aead; let recipient_box = lib_crypto_box::SalsaBox::new(sender.as_ref(), recipient.as_ref()); match recipient_box.decrypt( AsRef::<[u8; NONCE_BYTES]>::as_ref(&encrypted_data.nonce).into(), encrypted_data.encrypted_data.as_slice(), ) { Ok(decrypted_data) => { match block_padding::Iso7816::unpad(&decrypted_data) { // @todo do we want associated data to enforce the originating DHT space? Ok(unpadded) => Ok(Some(CryptoBoxData { data: Arc::new(unpadded.to_vec()), })), Err(_) => Ok(None), } } Err(_) => Ok(None), } }) .await } #[cfg(test)] mod tests { use super::*; #[tokio::test(flavor = "multi_thread")] async fn it_can_encrypt_and_decrypt() { for input in [ // Empty vec. vec![], // Small vec. vec![0], vec![0, 1, 2], vec![0, 1, 2, 3], // Vec ending in padding delimiter. vec![0x80], vec![0, 0x80], vec![0x80; BLOCK_PADDING_SIZE - 1], vec![0x80; BLOCK_PADDING_SIZE], vec![0x80; BLOCK_PADDING_SIZE + 1], // Larger vec. vec![0; BLOCK_PADDING_SIZE - 1], vec![0; BLOCK_PADDING_SIZE], vec![0; BLOCK_PADDING_SIZE + 1], vec![0; BLOCK_PADDING_SIZE * 2 - 1], vec![0; BLOCK_PADDING_SIZE * 2], vec![0; BLOCK_PADDING_SIZE * 2 + 1], ] .iter() { // Fresh keys. let alice = crate::internal::x25519::x25519_keypair_new_from_entropy() .await .unwrap(); let bob = crate::internal::x25519::x25519_keypair_new_from_entropy() .await .unwrap(); let data = CryptoBoxData { data: Arc::new(input.to_vec()), }; // from alice to bob. let encrypted_data = super::crypto_box( alice.priv_key, bob.pub_key, Arc::new(data.clone()), ) .await .unwrap(); // The length excluding the 16 byte overhead should always be a multiple of 32 as this // is our padding. assert_eq!((encrypted_data.encrypted_data.len() - 16) % 32, 0); let decrypted_data = super::crypto_box_open( bob.priv_key, alice.pub_key, Arc::new(encrypted_data), ) .await .unwrap(); // If we can decrypt we managed to pad and unpad as well as encrypt and decrypt. assert_eq!(&decrypted_data, &Some(data)); } } }
BLOCK_PADDING_SIZE - (data.data.len() + 1) % BLOCK_PADDING_SIZE
random_line_split
crypto_box.rs
use crate::internal::rayon::rayon_exec; use crate::internal::x25519; use block_padding::Padding; use crypto_box as lib_crypto_box; use std::sync::Arc; /// Length of the crypto box aead nonce. /// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly. pub const NONCE_BYTES: usize = 24; /// The size of blocks to pad encrypted data to. /// We have no idea how big incoming data is, but probably it is generally smallish. /// Devs can always do their own padding on top of this, but we want some safety for unpadded data. /// Libsodium optionally supports ISO 7816-4 padding algorithm. /// @see https://doc.libsodium.org/padding#algorithm pub const BLOCK_PADDING_SIZE: usize = 32; /// The delimiter for padding as per ISO 7816-4. pub const BLOCK_PADDING_DELIMITER: u8 = 0x80; /// Newtype for the nonce for safety. #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxNonce([u8; NONCE_BYTES]); impl CryptoBoxNonce { async fn new_random() -> Self { rayon_exec(move || { let mut rng = rand::thread_rng(); let mut bytes = [0; NONCE_BYTES]; // We rely on the lib_crypto_box nonce length being the same as what we expect. // Should be a reasonably safe bet as 24 bytes is dictated by the crypto_box algorithm. bytes.copy_from_slice( lib_crypto_box::generate_nonce(&mut rng).as_slice(), ); Self(bytes) }) .await } } impl AsRef<[u8; NONCE_BYTES]> for CryptoBoxNonce { fn as_ref(&self) -> &[u8; NONCE_BYTES] { &self.0 } } impl AsRef<[u8]> for CryptoBoxNonce { fn as_ref(&self) -> &[u8] { &self.0 } } impl From<[u8; NONCE_BYTES]> for CryptoBoxNonce { fn from(array: [u8; NONCE_BYTES]) -> Self { Self(array) } } impl std::convert::TryFrom<&[u8]> for CryptoBoxNonce { type Error = crate::error::LairError; fn
(slice: &[u8]) -> Result<Self, Self::Error> { if slice.len() == NONCE_BYTES { let mut inner = [0; NONCE_BYTES]; inner.copy_from_slice(slice); Ok(Self(inner)) } else { Err(crate::error::LairError::CryptoBoxNonceLength) } } } impl CryptoBoxNonce { /// Always NONCE_BYTES. pub fn len(&self) -> usize { NONCE_BYTES } /// For clippy. pub fn is_empty(&self) -> bool { self.len() == 0 } } /// "Additional associated data" as per the aead rust crate Payload. /// May be empty. Must be valid if present. pub struct CryptoBoxAad(Vec<u8>); /// The nonce and encrypted data together. /// @todo include additional associated data? #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxEncryptedData { /// The nonce generated during encryption. /// We never allow nonce to be set externally so we need to return it. pub nonce: CryptoBoxNonce, /// The encrypted version of our input data. #[allow(clippy::rc_buffer)] pub encrypted_data: Arc<Vec<u8>>, } /// Data to be encrypted. /// Not associated with a nonce because we enforce random nonces. #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxData { /// Data to be encrypted. #[allow(clippy::rc_buffer)] pub data: Arc<Vec<u8>>, } impl AsRef<[u8]> for CryptoBoxData { fn as_ref(&self) -> &[u8] { self.data.as_ref() } } impl CryptoBoxData { /// Length of newtype is length of inner. pub fn len(&self) -> usize { AsRef::<[u8]>::as_ref(self).len() } /// For clippy. pub fn is_empty(&self) -> bool { self.len() == 0 } } impl From<Vec<u8>> for CryptoBoxData { fn from(v: Vec<u8>) -> Self { Self { data: Arc::new(v) } } } /// @todo all of this can be opened up to be more flexible over time. /// Eventually all possible input such as nonces and associated data should be settable by the /// external interface. /// In the short term everyone is getting their heads around the 80/20 usage patterns that are as /// safe as we can possibly make them to avoid subtleties that lead to nonce or key re-use etc. /// /// Wrapper around crypto_box from whatever lib we use. /// No BYO nonces. Nonces always random and returned as part of `CryptoBoxEncryptedData`. /// No BYO algorithms (cipher agility). Algorithm always X25519XSalsa20Poly1305. /// Currently no additional associated data but DNA space may be included in the future. /// The sender's private key encrypts _for_ the recipient's pubkey. /// /// FYI allowing nonces could be dangerous as it's exposed as a general purpose authenticated /// encryption mechanism (or will be) via. crypto_box from libsodium. /// The main thing is that if a secret/nonce combination is _ever_ used more than once it /// completely breaks encryption. // /// Example ways a nonce could accidentally be reused: /// - If two DNAs are the same or similar (e.g. cloned DNAs) then they will have the same /// nonce generation logic, so may create collisions when run in parallel. /// - Collision of initialization vectors in a key exchange/crypto session. /// - Use of a counter based nonce in a way that isn't 100% reliably incrementing. /// /// Example ways a secret could accidentally be reused: /// - If two agents both commit their pubkeys then share them with each other, then the same /// shared key will be 'negotiated' by x25519 ECDH every time it is called. /// - If a pubkey is used across two different DNAs the secrets will collide at the lair /// and the DNAs won't have a way to co-ordinate or detect this. /// /// E.g. Ring is very wary of secret key re-use e.g. it makes explicit the use-case where an /// ephemeral (single use) key is generated to establish an ephemeral (single use) shared /// key. Our use-case is the libsodium `crypto_box` function that uses an x25519 keypair to /// perform authenticated encryption, so it makes more sense for us to be storing our /// private keys for later use BUT see above for the dangers of key re-use that the app dev /// really needs to be wary of. /// /// @see https://eprint.iacr.org/2019/519.pdf for 'context separable interfaces' pub async fn crypto_box( sender: x25519::X25519PrivKey, recipient: x25519::X25519PubKey, data: Arc<CryptoBoxData>, ) -> crate::error::LairResult<CryptoBoxEncryptedData> { let nonce = CryptoBoxNonce::new_random().await; rayon_exec(move || { use lib_crypto_box::aead::Aead; let sender_box = lib_crypto_box::SalsaBox::new(recipient.as_ref(), sender.as_ref()); // It's actually easier and clearer to directly pad the vector than use the block_padding // crate, as that is optimised for blocks. let mut to_encrypt = data.data.to_vec(); let padding_delimiter = vec![BLOCK_PADDING_DELIMITER]; let padding = vec![ 0x0; BLOCK_PADDING_SIZE - (data.data.len() + 1) % BLOCK_PADDING_SIZE ]; to_encrypt.extend(padding_delimiter); to_encrypt.extend(padding); let encrypted_data = Arc::new(sender_box.encrypt( AsRef::<[u8; NONCE_BYTES]>::as_ref(&nonce).into(), to_encrypt.as_slice(), )?); // @todo do we want associated data to enforce the originating DHT space? // https://eprint.iacr.org/2019/519.pdf for 'context separable interfaces' Ok(CryptoBoxEncryptedData { nonce, encrypted_data, }) }) .await } /// Wrapper around crypto_box_open from whatever lib we use. /// Exact inverse of `crypto_box_open` so nonce must be provided in `CryptoBoxEncryptedData`. /// The recipient's private key encrypts _from_ the sender's pubkey. pub async fn crypto_box_open( recipient: x25519::X25519PrivKey, sender: x25519::X25519PubKey, encrypted_data: Arc<CryptoBoxEncryptedData>, ) -> crate::error::LairResult<Option<CryptoBoxData>> { rayon_exec(move || { use lib_crypto_box::aead::Aead; let recipient_box = lib_crypto_box::SalsaBox::new(sender.as_ref(), recipient.as_ref()); match recipient_box.decrypt( AsRef::<[u8; NONCE_BYTES]>::as_ref(&encrypted_data.nonce).into(), encrypted_data.encrypted_data.as_slice(), ) { Ok(decrypted_data) => { match block_padding::Iso7816::unpad(&decrypted_data) { // @todo do we want associated data to enforce the originating DHT space? Ok(unpadded) => Ok(Some(CryptoBoxData { data: Arc::new(unpadded.to_vec()), })), Err(_) => Ok(None), } } Err(_) => Ok(None), } }) .await } #[cfg(test)] mod tests { use super::*; #[tokio::test(flavor = "multi_thread")] async fn it_can_encrypt_and_decrypt() { for input in [ // Empty vec. vec![], // Small vec. vec![0], vec![0, 1, 2], vec![0, 1, 2, 3], // Vec ending in padding delimiter. vec![0x80], vec![0, 0x80], vec![0x80; BLOCK_PADDING_SIZE - 1], vec![0x80; BLOCK_PADDING_SIZE], vec![0x80; BLOCK_PADDING_SIZE + 1], // Larger vec. vec![0; BLOCK_PADDING_SIZE - 1], vec![0; BLOCK_PADDING_SIZE], vec![0; BLOCK_PADDING_SIZE + 1], vec![0; BLOCK_PADDING_SIZE * 2 - 1], vec![0; BLOCK_PADDING_SIZE * 2], vec![0; BLOCK_PADDING_SIZE * 2 + 1], ] .iter() { // Fresh keys. let alice = crate::internal::x25519::x25519_keypair_new_from_entropy() .await .unwrap(); let bob = crate::internal::x25519::x25519_keypair_new_from_entropy() .await .unwrap(); let data = CryptoBoxData { data: Arc::new(input.to_vec()), }; // from alice to bob. let encrypted_data = super::crypto_box( alice.priv_key, bob.pub_key, Arc::new(data.clone()), ) .await .unwrap(); // The length excluding the 16 byte overhead should always be a multiple of 32 as this // is our padding. assert_eq!((encrypted_data.encrypted_data.len() - 16) % 32, 0); let decrypted_data = super::crypto_box_open( bob.priv_key, alice.pub_key, Arc::new(encrypted_data), ) .await .unwrap(); // If we can decrypt we managed to pad and unpad as well as encrypt and decrypt. assert_eq!(&decrypted_data, &Some(data)); } } }
try_from
identifier_name
crypto_box.rs
use crate::internal::rayon::rayon_exec; use crate::internal::x25519; use block_padding::Padding; use crypto_box as lib_crypto_box; use std::sync::Arc; /// Length of the crypto box aead nonce. /// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly. pub const NONCE_BYTES: usize = 24; /// The size of blocks to pad encrypted data to. /// We have no idea how big incoming data is, but probably it is generally smallish. /// Devs can always do their own padding on top of this, but we want some safety for unpadded data. /// Libsodium optionally supports ISO 7816-4 padding algorithm. /// @see https://doc.libsodium.org/padding#algorithm pub const BLOCK_PADDING_SIZE: usize = 32; /// The delimiter for padding as per ISO 7816-4. pub const BLOCK_PADDING_DELIMITER: u8 = 0x80; /// Newtype for the nonce for safety. #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxNonce([u8; NONCE_BYTES]); impl CryptoBoxNonce { async fn new_random() -> Self { rayon_exec(move || { let mut rng = rand::thread_rng(); let mut bytes = [0; NONCE_BYTES]; // We rely on the lib_crypto_box nonce length being the same as what we expect. // Should be a reasonably safe bet as 24 bytes is dictated by the crypto_box algorithm. bytes.copy_from_slice( lib_crypto_box::generate_nonce(&mut rng).as_slice(), ); Self(bytes) }) .await } } impl AsRef<[u8; NONCE_BYTES]> for CryptoBoxNonce { fn as_ref(&self) -> &[u8; NONCE_BYTES] { &self.0 } } impl AsRef<[u8]> for CryptoBoxNonce { fn as_ref(&self) -> &[u8] { &self.0 } } impl From<[u8; NONCE_BYTES]> for CryptoBoxNonce { fn from(array: [u8; NONCE_BYTES]) -> Self { Self(array) } } impl std::convert::TryFrom<&[u8]> for CryptoBoxNonce { type Error = crate::error::LairError; fn try_from(slice: &[u8]) -> Result<Self, Self::Error> { if slice.len() == NONCE_BYTES { let mut inner = [0; NONCE_BYTES]; inner.copy_from_slice(slice); Ok(Self(inner)) } else { Err(crate::error::LairError::CryptoBoxNonceLength) } } } impl CryptoBoxNonce { /// Always NONCE_BYTES. pub fn len(&self) -> usize { NONCE_BYTES } /// For clippy. pub fn is_empty(&self) -> bool { self.len() == 0 } } /// "Additional associated data" as per the aead rust crate Payload. /// May be empty. Must be valid if present. pub struct CryptoBoxAad(Vec<u8>); /// The nonce and encrypted data together. /// @todo include additional associated data? #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxEncryptedData { /// The nonce generated during encryption. /// We never allow nonce to be set externally so we need to return it. pub nonce: CryptoBoxNonce, /// The encrypted version of our input data. #[allow(clippy::rc_buffer)] pub encrypted_data: Arc<Vec<u8>>, } /// Data to be encrypted. /// Not associated with a nonce because we enforce random nonces. #[derive(Debug, PartialEq, Clone)] pub struct CryptoBoxData { /// Data to be encrypted. #[allow(clippy::rc_buffer)] pub data: Arc<Vec<u8>>, } impl AsRef<[u8]> for CryptoBoxData { fn as_ref(&self) -> &[u8]
} impl CryptoBoxData { /// Length of newtype is length of inner. pub fn len(&self) -> usize { AsRef::<[u8]>::as_ref(self).len() } /// For clippy. pub fn is_empty(&self) -> bool { self.len() == 0 } } impl From<Vec<u8>> for CryptoBoxData { fn from(v: Vec<u8>) -> Self { Self { data: Arc::new(v) } } } /// @todo all of this can be opened up to be more flexible over time. /// Eventually all possible input such as nonces and associated data should be settable by the /// external interface. /// In the short term everyone is getting their heads around the 80/20 usage patterns that are as /// safe as we can possibly make them to avoid subtleties that lead to nonce or key re-use etc. /// /// Wrapper around crypto_box from whatever lib we use. /// No BYO nonces. Nonces always random and returned as part of `CryptoBoxEncryptedData`. /// No BYO algorithms (cipher agility). Algorithm always X25519XSalsa20Poly1305. /// Currently no additional associated data but DNA space may be included in the future. /// The sender's private key encrypts _for_ the recipient's pubkey. /// /// FYI allowing nonces could be dangerous as it's exposed as a general purpose authenticated /// encryption mechanism (or will be) via. crypto_box from libsodium. /// The main thing is that if a secret/nonce combination is _ever_ used more than once it /// completely breaks encryption. // /// Example ways a nonce could accidentally be reused: /// - If two DNAs are the same or similar (e.g. cloned DNAs) then they will have the same /// nonce generation logic, so may create collisions when run in parallel. /// - Collision of initialization vectors in a key exchange/crypto session. /// - Use of a counter based nonce in a way that isn't 100% reliably incrementing. /// /// Example ways a secret could accidentally be reused: /// - If two agents both commit their pubkeys then share them with each other, then the same /// shared key will be 'negotiated' by x25519 ECDH every time it is called. /// - If a pubkey is used across two different DNAs the secrets will collide at the lair /// and the DNAs won't have a way to co-ordinate or detect this. /// /// E.g. Ring is very wary of secret key re-use e.g. it makes explicit the use-case where an /// ephemeral (single use) key is generated to establish an ephemeral (single use) shared /// key. Our use-case is the libsodium `crypto_box` function that uses an x25519 keypair to /// perform authenticated encryption, so it makes more sense for us to be storing our /// private keys for later use BUT see above for the dangers of key re-use that the app dev /// really needs to be wary of. /// /// @see https://eprint.iacr.org/2019/519.pdf for 'context separable interfaces' pub async fn crypto_box( sender: x25519::X25519PrivKey, recipient: x25519::X25519PubKey, data: Arc<CryptoBoxData>, ) -> crate::error::LairResult<CryptoBoxEncryptedData> { let nonce = CryptoBoxNonce::new_random().await; rayon_exec(move || { use lib_crypto_box::aead::Aead; let sender_box = lib_crypto_box::SalsaBox::new(recipient.as_ref(), sender.as_ref()); // It's actually easier and clearer to directly pad the vector than use the block_padding // crate, as that is optimised for blocks. let mut to_encrypt = data.data.to_vec(); let padding_delimiter = vec![BLOCK_PADDING_DELIMITER]; let padding = vec![ 0x0; BLOCK_PADDING_SIZE - (data.data.len() + 1) % BLOCK_PADDING_SIZE ]; to_encrypt.extend(padding_delimiter); to_encrypt.extend(padding); let encrypted_data = Arc::new(sender_box.encrypt( AsRef::<[u8; NONCE_BYTES]>::as_ref(&nonce).into(), to_encrypt.as_slice(), )?); // @todo do we want associated data to enforce the originating DHT space? // https://eprint.iacr.org/2019/519.pdf for 'context separable interfaces' Ok(CryptoBoxEncryptedData { nonce, encrypted_data, }) }) .await } /// Wrapper around crypto_box_open from whatever lib we use. /// Exact inverse of `crypto_box_open` so nonce must be provided in `CryptoBoxEncryptedData`. /// The recipient's private key encrypts _from_ the sender's pubkey. pub async fn crypto_box_open( recipient: x25519::X25519PrivKey, sender: x25519::X25519PubKey, encrypted_data: Arc<CryptoBoxEncryptedData>, ) -> crate::error::LairResult<Option<CryptoBoxData>> { rayon_exec(move || { use lib_crypto_box::aead::Aead; let recipient_box = lib_crypto_box::SalsaBox::new(sender.as_ref(), recipient.as_ref()); match recipient_box.decrypt( AsRef::<[u8; NONCE_BYTES]>::as_ref(&encrypted_data.nonce).into(), encrypted_data.encrypted_data.as_slice(), ) { Ok(decrypted_data) => { match block_padding::Iso7816::unpad(&decrypted_data) { // @todo do we want associated data to enforce the originating DHT space? Ok(unpadded) => Ok(Some(CryptoBoxData { data: Arc::new(unpadded.to_vec()), })), Err(_) => Ok(None), } } Err(_) => Ok(None), } }) .await } #[cfg(test)] mod tests { use super::*; #[tokio::test(flavor = "multi_thread")] async fn it_can_encrypt_and_decrypt() { for input in [ // Empty vec. vec![], // Small vec. vec![0], vec![0, 1, 2], vec![0, 1, 2, 3], // Vec ending in padding delimiter. vec![0x80], vec![0, 0x80], vec![0x80; BLOCK_PADDING_SIZE - 1], vec![0x80; BLOCK_PADDING_SIZE], vec![0x80; BLOCK_PADDING_SIZE + 1], // Larger vec. vec![0; BLOCK_PADDING_SIZE - 1], vec![0; BLOCK_PADDING_SIZE], vec![0; BLOCK_PADDING_SIZE + 1], vec![0; BLOCK_PADDING_SIZE * 2 - 1], vec![0; BLOCK_PADDING_SIZE * 2], vec![0; BLOCK_PADDING_SIZE * 2 + 1], ] .iter() { // Fresh keys. let alice = crate::internal::x25519::x25519_keypair_new_from_entropy() .await .unwrap(); let bob = crate::internal::x25519::x25519_keypair_new_from_entropy() .await .unwrap(); let data = CryptoBoxData { data: Arc::new(input.to_vec()), }; // from alice to bob. let encrypted_data = super::crypto_box( alice.priv_key, bob.pub_key, Arc::new(data.clone()), ) .await .unwrap(); // The length excluding the 16 byte overhead should always be a multiple of 32 as this // is our padding. assert_eq!((encrypted_data.encrypted_data.len() - 16) % 32, 0); let decrypted_data = super::crypto_box_open( bob.priv_key, alice.pub_key, Arc::new(encrypted_data), ) .await .unwrap(); // If we can decrypt we managed to pad and unpad as well as encrypt and decrypt. assert_eq!(&decrypted_data, &Some(data)); } } }
{ self.data.as_ref() }
identifier_body
scoped_signal_handler.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Provides a struct for registering signal handlers that get cleared on drop. use std::convert::TryFrom; use std::fmt; use std::io::{Cursor, Write}; use std::panic::catch_unwind; use std::result; use libc::{c_int, c_void, STDERR_FILENO}; use remain::sorted; use thiserror::Error; use crate::errno; use crate::signal::{ clear_signal_handler, has_default_signal_handler, register_signal_handler, wait_for_signal, Signal, }; #[sorted] #[derive(Error, Debug)] pub enum Error { /// Already waiting for interrupt. #[error("already waiting for interrupt.")] AlreadyWaiting, /// Signal already has a handler. #[error("signal handler already set for {0:?}")] HandlerAlreadySet(Signal), /// Failed to check if signal has the default signal handler. #[error("failed to check the signal handler for {0:?}: {1}")] HasDefaultSignalHandler(Signal, errno::Error), /// Failed to register a signal handler. #[error("failed to register a signal handler for {0:?}: {1}")] RegisterSignalHandler(Signal, errno::Error), /// Sigaction failed. #[error("sigaction failed for {0:?}: {1}")] Sigaction(Signal, errno::Error), /// Failed to wait for signal. #[error("wait_for_signal failed: {0}")] WaitForSignal(errno::Error), } pub type Result<T> = result::Result<T, Error>; /// The interface used by Scoped Signal handler. /// /// # Safety /// The implementation of handle_signal needs to be async signal-safe. /// /// NOTE: panics are caught when possible because a panic inside ffi is undefined behavior. pub unsafe trait SignalHandler { /// A function that is called to handle the passed signal. fn handle_signal(signal: Signal); } /// Wrap the handler with an extern "C" function. extern "C" fn call_handler<H: SignalHandler>(signum: c_int)
let mut buffer = [0u8; 64]; let mut cursor = Cursor::new(buffer.as_mut()); if writeln!(cursor, "signal handler got error for: {:?}", signal_debug).is_ok() { let len = cursor.position() as usize; // Safe in the sense that buffer is owned and the length is checked. This may print in // the middle of an existing write, but that is considered better than dropping the // error. unsafe { libc::write( STDERR_FILENO, cursor.get_ref().as_ptr() as *const c_void, len, ) }; } else { // This should never happen, but write an error message just in case. const ERROR_DROPPED: &str = "Error dropped by signal handler."; let bytes = ERROR_DROPPED.as_bytes(); unsafe { libc::write(STDERR_FILENO, bytes.as_ptr() as *const c_void, bytes.len()) }; } } } /// Represents a signal handler that is registered with a set of signals that unregistered when the /// struct goes out of scope. Prefer a signalfd based solution before using this. pub struct ScopedSignalHandler { signals: Vec<Signal>, } impl ScopedSignalHandler { /// Attempts to register `handler` with the provided `signals`. It will fail if there is already /// an existing handler on any of `signals`. /// /// # Safety /// This is safe if H::handle_signal is async-signal safe. pub fn new<H: SignalHandler>(signals: &[Signal]) -> Result<Self> { let mut scoped_handler = ScopedSignalHandler { signals: Vec::with_capacity(signals.len()), }; for &signal in signals { if!has_default_signal_handler((signal).into()) .map_err(|err| Error::HasDefaultSignalHandler(signal, err))? { return Err(Error::HandlerAlreadySet(signal)); } // Requires an async-safe callback. unsafe { register_signal_handler((signal).into(), call_handler::<H>) .map_err(|err| Error::RegisterSignalHandler(signal, err))? }; scoped_handler.signals.push(signal); } Ok(scoped_handler) } } /// Clears the signal handler for any of the associated signals. impl Drop for ScopedSignalHandler { fn drop(&mut self) { for signal in &self.signals { if let Err(err) = clear_signal_handler((*signal).into()) { eprintln!("Error: failed to clear signal handler: {:?}", err); } } } } /// A signal handler that does nothing. /// /// This is useful in cases where wait_for_signal is used since it will never trigger if the signal /// is blocked and the default handler may have undesired effects like terminating the process. pub struct EmptySignalHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for EmptySignalHandler { fn handle_signal(_: Signal) {} } /// Blocks until SIGINT is received, which often happens because Ctrl-C was pressed in an /// interactive terminal. /// /// Note: if you are using a multi-threaded application you need to block SIGINT on all other /// threads or they may receive the signal instead of the desired thread. pub fn wait_for_interrupt() -> Result<()> { // Register a signal handler if there is not one already so the thread is not killed. let ret = ScopedSignalHandler::new::<EmptySignalHandler>(&[Signal::Interrupt]); if!matches!(&ret, Ok(_) | Err(Error::HandlerAlreadySet(_))) { ret?; } match wait_for_signal(&[Signal::Interrupt.into()], None) { Ok(_) => Ok(()), Err(err) => Err(Error::WaitForSignal(err)), } } #[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::{BufRead, BufReader}; use std::mem::zeroed; use std::ptr::{null, null_mut}; use std::sync::atomic::{AtomicI32, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, Once}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use libc::sigaction; use crate::{gettid, kill, Pid}; const TEST_SIGNAL: Signal = Signal::User1; const TEST_SIGNALS: &[Signal] = &[Signal::User1, Signal::User2]; static TEST_SIGNAL_COUNTER: AtomicUsize = AtomicUsize::new(0); /// Only allows one test case to execute at a time. fn get_mutex() -> MutexGuard<'static, ()> { static INIT: Once = Once::new(); static mut VAL: Option<Arc<Mutex<()>>> = None; INIT.call_once(|| { let val = Some(Arc::new(Mutex::new(()))); // Safe because the mutation is protected by the Once. unsafe { VAL = val } }); // Safe mutation only happens in the Once. unsafe { VAL.as_ref() }.unwrap().lock().unwrap() } fn reset_counter() { TEST_SIGNAL_COUNTER.swap(0, Ordering::SeqCst); } fn get_sigaction(signal: Signal) -> Result<sigaction> { // Safe because sigaction is owned and expected to be initialized ot zeros. let mut sigact: sigaction = unsafe { zeroed() }; if unsafe { sigaction(signal.into(), null(), &mut sigact) } < 0 { Err(Error::Sigaction(signal, errno::Error::last())) } else { Ok(sigact) } } /// Safety: /// This is only safe if the signal handler set in sigaction is safe. unsafe fn restore_sigaction(signal: Signal, sigact: sigaction) -> Result<sigaction> { if sigaction(signal.into(), &sigact, null_mut()) < 0 { Err(Error::Sigaction(signal, errno::Error::last())) } else { Ok(sigact) } } /// Safety: /// Safe if the signal handler for Signal::User1 is safe. unsafe fn send_test_signal() { kill(gettid(), Signal::User1.into()).unwrap() } macro_rules! assert_counter_eq { ($compare_to:expr) => {{ let expected: usize = $compare_to; let got: usize = TEST_SIGNAL_COUNTER.load(Ordering::SeqCst); if got!= expected { panic!( "wrong signal counter value: got {}; expected {}", got, expected ); } }}; } struct TestHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for TestHandler { fn handle_signal(signal: Signal) { if TEST_SIGNAL == signal { TEST_SIGNAL_COUNTER.fetch_add(1, Ordering::SeqCst); } } } #[test] fn scopedsignalhandler_success() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); reset_counter(); assert_counter_eq!(0); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); let handler = ScopedSignalHandler::new::<TestHandler>(&[TEST_SIGNAL]).unwrap(); assert!(!has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because test_handler is safe. unsafe { send_test_signal() }; // Give the handler time to run in case it is on a different thread. for _ in 1..40 { if TEST_SIGNAL_COUNTER.load(Ordering::SeqCst) > 0 { break; } sleep(Duration::from_millis(250)); } assert_counter_eq!(1); drop(handler); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); } #[test] fn scopedsignalhandler_handleralreadyset() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); reset_counter(); assert_counter_eq!(0); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because TestHandler is async-signal safe. let handler = ScopedSignalHandler::new::<TestHandler>(&[TEST_SIGNAL]).unwrap(); assert!(!has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because TestHandler is async-signal safe. assert!(matches!( ScopedSignalHandler::new::<TestHandler>(TEST_SIGNALS), Err(Error::HandlerAlreadySet(Signal::User1)) )); assert_counter_eq!(0); drop(handler); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); } /// Stores the thread used by WaitForInterruptHandler. static WAIT_FOR_INTERRUPT_THREAD_ID: AtomicI32 = AtomicI32::new(0); /// Forwards SIGINT to the appropriate thread. struct WaitForInterruptHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for WaitForInterruptHandler { fn handle_signal(_: Signal) { let tid = WAIT_FOR_INTERRUPT_THREAD_ID.load(Ordering::SeqCst); // If the thread ID is set and executed on the wrong thread, forward the signal. if tid!= 0 && gettid()!= tid { // Safe because the handler is safe and the target thread id is expecting the signal. unsafe { kill(tid, Signal::Interrupt.into()) }.unwrap(); } } } /// Query /proc/${tid}/status for its State and check if it is either S (sleeping) or in /// D (disk sleep). fn thread_is_sleeping(tid: Pid) -> result::Result<bool, errno::Error> { const PREFIX: &str = "State:"; let mut status_reader = BufReader::new(File::open(format!("/proc/{}/status", tid))?); let mut line = String::new(); loop { let count = status_reader.read_line(&mut line)?; if count == 0 { return Err(errno::Error::new(libc::EIO)); } if let Some(stripped) = line.strip_prefix(PREFIX) { return Ok(matches!( stripped.trim_start().chars().next(), Some('S') | Some('D') )); } line.clear(); } } /// Wait for a process to block either in a sleeping or disk sleep state. fn wait_for_thread_to_sleep(tid: Pid, timeout: Duration) -> result::Result<(), errno::Error> { let start = Instant::now(); loop { if thread_is_sleeping(tid)? { return Ok(()); } if start.elapsed() > timeout { return Err(errno::Error::new(libc::EAGAIN)); } sleep(Duration::from_millis(50)); } } #[test] fn waitforinterrupt_success() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); let to_restore = get_sigaction(Signal::Interrupt).unwrap(); clear_signal_handler(Signal::Interrupt.into()).unwrap(); // Safe because TestHandler is async-signal safe. let handler = ScopedSignalHandler::new::<WaitForInterruptHandler>(&[Signal::Interrupt]).unwrap(); let tid = gettid(); WAIT_FOR_INTERRUPT_THREAD_ID.store(tid, Ordering::SeqCst); let join_handle = spawn(move || -> result::Result<(), errno::Error> { // Wait unitl the thread is ready to receive the signal. wait_for_thread_to_sleep(tid, Duration::from_secs(10)).unwrap(); // Safe because the SIGINT handler is safe. unsafe { kill(tid, Signal::Interrupt.into()) } }); let wait_ret = wait_for_interrupt(); let join_ret = join_handle.join(); drop(handler); // Safe because we are restoring the previous SIGINT handler. unsafe { restore_sigaction(Signal::Interrupt, to_restore) }.unwrap(); wait_ret.unwrap(); join_ret.unwrap().unwrap(); } }
{ // Make an effort to surface an error. if catch_unwind(|| H::handle_signal(Signal::try_from(signum).unwrap())).is_err() { // Note the following cannot be used: // eprintln! - uses std::io which has locks that may be held. // format! - uses the allocator which enforces mutual exclusion. // Get the debug representation of signum. let signal: Signal; let signal_debug: &dyn fmt::Debug = match Signal::try_from(signum) { Ok(s) => { signal = s; &signal as &dyn fmt::Debug } Err(_) => &signum as &dyn fmt::Debug, }; // Buffer the output, so a single call to write can be used. // The message accounts for 29 chars, that leaves 35 for the string representation of the // signal which is more than enough.
identifier_body
scoped_signal_handler.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Provides a struct for registering signal handlers that get cleared on drop. use std::convert::TryFrom; use std::fmt; use std::io::{Cursor, Write}; use std::panic::catch_unwind; use std::result; use libc::{c_int, c_void, STDERR_FILENO}; use remain::sorted; use thiserror::Error; use crate::errno; use crate::signal::{ clear_signal_handler, has_default_signal_handler, register_signal_handler, wait_for_signal, Signal, }; #[sorted] #[derive(Error, Debug)] pub enum Error { /// Already waiting for interrupt. #[error("already waiting for interrupt.")] AlreadyWaiting, /// Signal already has a handler. #[error("signal handler already set for {0:?}")] HandlerAlreadySet(Signal), /// Failed to check if signal has the default signal handler. #[error("failed to check the signal handler for {0:?}: {1}")] HasDefaultSignalHandler(Signal, errno::Error), /// Failed to register a signal handler. #[error("failed to register a signal handler for {0:?}: {1}")] RegisterSignalHandler(Signal, errno::Error), /// Sigaction failed. #[error("sigaction failed for {0:?}: {1}")] Sigaction(Signal, errno::Error), /// Failed to wait for signal. #[error("wait_for_signal failed: {0}")] WaitForSignal(errno::Error), } pub type Result<T> = result::Result<T, Error>; /// The interface used by Scoped Signal handler. /// /// # Safety /// The implementation of handle_signal needs to be async signal-safe. /// /// NOTE: panics are caught when possible because a panic inside ffi is undefined behavior. pub unsafe trait SignalHandler { /// A function that is called to handle the passed signal. fn handle_signal(signal: Signal); } /// Wrap the handler with an extern "C" function. extern "C" fn call_handler<H: SignalHandler>(signum: c_int) { // Make an effort to surface an error. if catch_unwind(|| H::handle_signal(Signal::try_from(signum).unwrap())).is_err() { // Note the following cannot be used: // eprintln! - uses std::io which has locks that may be held. // format! - uses the allocator which enforces mutual exclusion. // Get the debug representation of signum. let signal: Signal; let signal_debug: &dyn fmt::Debug = match Signal::try_from(signum) { Ok(s) => { signal = s; &signal as &dyn fmt::Debug } Err(_) => &signum as &dyn fmt::Debug, }; // Buffer the output, so a single call to write can be used. // The message accounts for 29 chars, that leaves 35 for the string representation of the // signal which is more than enough. let mut buffer = [0u8; 64]; let mut cursor = Cursor::new(buffer.as_mut()); if writeln!(cursor, "signal handler got error for: {:?}", signal_debug).is_ok() { let len = cursor.position() as usize; // Safe in the sense that buffer is owned and the length is checked. This may print in // the middle of an existing write, but that is considered better than dropping the // error. unsafe { libc::write( STDERR_FILENO, cursor.get_ref().as_ptr() as *const c_void, len, ) }; } else { // This should never happen, but write an error message just in case. const ERROR_DROPPED: &str = "Error dropped by signal handler."; let bytes = ERROR_DROPPED.as_bytes(); unsafe { libc::write(STDERR_FILENO, bytes.as_ptr() as *const c_void, bytes.len()) }; } } } /// Represents a signal handler that is registered with a set of signals that unregistered when the /// struct goes out of scope. Prefer a signalfd based solution before using this. pub struct ScopedSignalHandler { signals: Vec<Signal>, } impl ScopedSignalHandler { /// Attempts to register `handler` with the provided `signals`. It will fail if there is already /// an existing handler on any of `signals`. /// /// # Safety /// This is safe if H::handle_signal is async-signal safe. pub fn new<H: SignalHandler>(signals: &[Signal]) -> Result<Self> { let mut scoped_handler = ScopedSignalHandler { signals: Vec::with_capacity(signals.len()), }; for &signal in signals { if!has_default_signal_handler((signal).into()) .map_err(|err| Error::HasDefaultSignalHandler(signal, err))? { return Err(Error::HandlerAlreadySet(signal)); } // Requires an async-safe callback. unsafe { register_signal_handler((signal).into(), call_handler::<H>) .map_err(|err| Error::RegisterSignalHandler(signal, err))? }; scoped_handler.signals.push(signal); } Ok(scoped_handler) } } /// Clears the signal handler for any of the associated signals. impl Drop for ScopedSignalHandler { fn drop(&mut self) { for signal in &self.signals { if let Err(err) = clear_signal_handler((*signal).into()) { eprintln!("Error: failed to clear signal handler: {:?}", err); } } } } /// A signal handler that does nothing. /// /// This is useful in cases where wait_for_signal is used since it will never trigger if the signal /// is blocked and the default handler may have undesired effects like terminating the process. pub struct EmptySignalHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for EmptySignalHandler { fn handle_signal(_: Signal) {} } /// Blocks until SIGINT is received, which often happens because Ctrl-C was pressed in an /// interactive terminal. /// /// Note: if you are using a multi-threaded application you need to block SIGINT on all other /// threads or they may receive the signal instead of the desired thread. pub fn wait_for_interrupt() -> Result<()> { // Register a signal handler if there is not one already so the thread is not killed. let ret = ScopedSignalHandler::new::<EmptySignalHandler>(&[Signal::Interrupt]); if!matches!(&ret, Ok(_) | Err(Error::HandlerAlreadySet(_))) { ret?; } match wait_for_signal(&[Signal::Interrupt.into()], None) { Ok(_) => Ok(()), Err(err) => Err(Error::WaitForSignal(err)), } } #[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::{BufRead, BufReader}; use std::mem::zeroed; use std::ptr::{null, null_mut}; use std::sync::atomic::{AtomicI32, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, Once}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use libc::sigaction; use crate::{gettid, kill, Pid}; const TEST_SIGNAL: Signal = Signal::User1; const TEST_SIGNALS: &[Signal] = &[Signal::User1, Signal::User2]; static TEST_SIGNAL_COUNTER: AtomicUsize = AtomicUsize::new(0); /// Only allows one test case to execute at a time. fn get_mutex() -> MutexGuard<'static, ()> { static INIT: Once = Once::new(); static mut VAL: Option<Arc<Mutex<()>>> = None; INIT.call_once(|| { let val = Some(Arc::new(Mutex::new(()))); // Safe because the mutation is protected by the Once. unsafe { VAL = val } }); // Safe mutation only happens in the Once. unsafe { VAL.as_ref() }.unwrap().lock().unwrap() } fn reset_counter() { TEST_SIGNAL_COUNTER.swap(0, Ordering::SeqCst); } fn get_sigaction(signal: Signal) -> Result<sigaction> { // Safe because sigaction is owned and expected to be initialized ot zeros. let mut sigact: sigaction = unsafe { zeroed() }; if unsafe { sigaction(signal.into(), null(), &mut sigact) } < 0 { Err(Error::Sigaction(signal, errno::Error::last())) } else { Ok(sigact) } } /// Safety: /// This is only safe if the signal handler set in sigaction is safe. unsafe fn restore_sigaction(signal: Signal, sigact: sigaction) -> Result<sigaction> { if sigaction(signal.into(), &sigact, null_mut()) < 0 { Err(Error::Sigaction(signal, errno::Error::last())) } else { Ok(sigact) } } /// Safety: /// Safe if the signal handler for Signal::User1 is safe. unsafe fn send_test_signal() { kill(gettid(), Signal::User1.into()).unwrap() } macro_rules! assert_counter_eq { ($compare_to:expr) => {{ let expected: usize = $compare_to; let got: usize = TEST_SIGNAL_COUNTER.load(Ordering::SeqCst); if got!= expected { panic!( "wrong signal counter value: got {}; expected {}", got, expected ); } }}; } struct TestHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for TestHandler { fn handle_signal(signal: Signal) { if TEST_SIGNAL == signal { TEST_SIGNAL_COUNTER.fetch_add(1, Ordering::SeqCst); } } } #[test] fn scopedsignalhandler_success() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); reset_counter(); assert_counter_eq!(0); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); let handler = ScopedSignalHandler::new::<TestHandler>(&[TEST_SIGNAL]).unwrap(); assert!(!has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because test_handler is safe. unsafe { send_test_signal() }; // Give the handler time to run in case it is on a different thread. for _ in 1..40 { if TEST_SIGNAL_COUNTER.load(Ordering::SeqCst) > 0 { break; } sleep(Duration::from_millis(250)); } assert_counter_eq!(1); drop(handler); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); } #[test] fn scopedsignalhandler_handleralreadyset() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); reset_counter(); assert_counter_eq!(0); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because TestHandler is async-signal safe. let handler = ScopedSignalHandler::new::<TestHandler>(&[TEST_SIGNAL]).unwrap(); assert!(!has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because TestHandler is async-signal safe. assert!(matches!( ScopedSignalHandler::new::<TestHandler>(TEST_SIGNALS), Err(Error::HandlerAlreadySet(Signal::User1)) )); assert_counter_eq!(0); drop(handler); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); } /// Stores the thread used by WaitForInterruptHandler. static WAIT_FOR_INTERRUPT_THREAD_ID: AtomicI32 = AtomicI32::new(0); /// Forwards SIGINT to the appropriate thread. struct WaitForInterruptHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for WaitForInterruptHandler { fn handle_signal(_: Signal) { let tid = WAIT_FOR_INTERRUPT_THREAD_ID.load(Ordering::SeqCst); // If the thread ID is set and executed on the wrong thread, forward the signal. if tid!= 0 && gettid()!= tid { // Safe because the handler is safe and the target thread id is expecting the signal. unsafe { kill(tid, Signal::Interrupt.into()) }.unwrap(); } } } /// Query /proc/${tid}/status for its State and check if it is either S (sleeping) or in /// D (disk sleep). fn thread_is_sleeping(tid: Pid) -> result::Result<bool, errno::Error> { const PREFIX: &str = "State:"; let mut status_reader = BufReader::new(File::open(format!("/proc/{}/status", tid))?); let mut line = String::new(); loop { let count = status_reader.read_line(&mut line)?; if count == 0 { return Err(errno::Error::new(libc::EIO)); } if let Some(stripped) = line.strip_prefix(PREFIX)
line.clear(); } } /// Wait for a process to block either in a sleeping or disk sleep state. fn wait_for_thread_to_sleep(tid: Pid, timeout: Duration) -> result::Result<(), errno::Error> { let start = Instant::now(); loop { if thread_is_sleeping(tid)? { return Ok(()); } if start.elapsed() > timeout { return Err(errno::Error::new(libc::EAGAIN)); } sleep(Duration::from_millis(50)); } } #[test] fn waitforinterrupt_success() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); let to_restore = get_sigaction(Signal::Interrupt).unwrap(); clear_signal_handler(Signal::Interrupt.into()).unwrap(); // Safe because TestHandler is async-signal safe. let handler = ScopedSignalHandler::new::<WaitForInterruptHandler>(&[Signal::Interrupt]).unwrap(); let tid = gettid(); WAIT_FOR_INTERRUPT_THREAD_ID.store(tid, Ordering::SeqCst); let join_handle = spawn(move || -> result::Result<(), errno::Error> { // Wait unitl the thread is ready to receive the signal. wait_for_thread_to_sleep(tid, Duration::from_secs(10)).unwrap(); // Safe because the SIGINT handler is safe. unsafe { kill(tid, Signal::Interrupt.into()) } }); let wait_ret = wait_for_interrupt(); let join_ret = join_handle.join(); drop(handler); // Safe because we are restoring the previous SIGINT handler. unsafe { restore_sigaction(Signal::Interrupt, to_restore) }.unwrap(); wait_ret.unwrap(); join_ret.unwrap().unwrap(); } }
{ return Ok(matches!( stripped.trim_start().chars().next(), Some('S') | Some('D') )); }
conditional_block
scoped_signal_handler.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Provides a struct for registering signal handlers that get cleared on drop. use std::convert::TryFrom; use std::fmt; use std::io::{Cursor, Write}; use std::panic::catch_unwind; use std::result; use libc::{c_int, c_void, STDERR_FILENO}; use remain::sorted; use thiserror::Error; use crate::errno; use crate::signal::{ clear_signal_handler, has_default_signal_handler, register_signal_handler, wait_for_signal, Signal, }; #[sorted] #[derive(Error, Debug)] pub enum Error { /// Already waiting for interrupt. #[error("already waiting for interrupt.")] AlreadyWaiting, /// Signal already has a handler. #[error("signal handler already set for {0:?}")] HandlerAlreadySet(Signal), /// Failed to check if signal has the default signal handler. #[error("failed to check the signal handler for {0:?}: {1}")] HasDefaultSignalHandler(Signal, errno::Error), /// Failed to register a signal handler. #[error("failed to register a signal handler for {0:?}: {1}")] RegisterSignalHandler(Signal, errno::Error), /// Sigaction failed. #[error("sigaction failed for {0:?}: {1}")] Sigaction(Signal, errno::Error), /// Failed to wait for signal. #[error("wait_for_signal failed: {0}")] WaitForSignal(errno::Error), } pub type Result<T> = result::Result<T, Error>; /// The interface used by Scoped Signal handler. /// /// # Safety /// The implementation of handle_signal needs to be async signal-safe. /// /// NOTE: panics are caught when possible because a panic inside ffi is undefined behavior. pub unsafe trait SignalHandler { /// A function that is called to handle the passed signal. fn handle_signal(signal: Signal); } /// Wrap the handler with an extern "C" function. extern "C" fn call_handler<H: SignalHandler>(signum: c_int) { // Make an effort to surface an error. if catch_unwind(|| H::handle_signal(Signal::try_from(signum).unwrap())).is_err() { // Note the following cannot be used:
// format! - uses the allocator which enforces mutual exclusion. // Get the debug representation of signum. let signal: Signal; let signal_debug: &dyn fmt::Debug = match Signal::try_from(signum) { Ok(s) => { signal = s; &signal as &dyn fmt::Debug } Err(_) => &signum as &dyn fmt::Debug, }; // Buffer the output, so a single call to write can be used. // The message accounts for 29 chars, that leaves 35 for the string representation of the // signal which is more than enough. let mut buffer = [0u8; 64]; let mut cursor = Cursor::new(buffer.as_mut()); if writeln!(cursor, "signal handler got error for: {:?}", signal_debug).is_ok() { let len = cursor.position() as usize; // Safe in the sense that buffer is owned and the length is checked. This may print in // the middle of an existing write, but that is considered better than dropping the // error. unsafe { libc::write( STDERR_FILENO, cursor.get_ref().as_ptr() as *const c_void, len, ) }; } else { // This should never happen, but write an error message just in case. const ERROR_DROPPED: &str = "Error dropped by signal handler."; let bytes = ERROR_DROPPED.as_bytes(); unsafe { libc::write(STDERR_FILENO, bytes.as_ptr() as *const c_void, bytes.len()) }; } } } /// Represents a signal handler that is registered with a set of signals that unregistered when the /// struct goes out of scope. Prefer a signalfd based solution before using this. pub struct ScopedSignalHandler { signals: Vec<Signal>, } impl ScopedSignalHandler { /// Attempts to register `handler` with the provided `signals`. It will fail if there is already /// an existing handler on any of `signals`. /// /// # Safety /// This is safe if H::handle_signal is async-signal safe. pub fn new<H: SignalHandler>(signals: &[Signal]) -> Result<Self> { let mut scoped_handler = ScopedSignalHandler { signals: Vec::with_capacity(signals.len()), }; for &signal in signals { if!has_default_signal_handler((signal).into()) .map_err(|err| Error::HasDefaultSignalHandler(signal, err))? { return Err(Error::HandlerAlreadySet(signal)); } // Requires an async-safe callback. unsafe { register_signal_handler((signal).into(), call_handler::<H>) .map_err(|err| Error::RegisterSignalHandler(signal, err))? }; scoped_handler.signals.push(signal); } Ok(scoped_handler) } } /// Clears the signal handler for any of the associated signals. impl Drop for ScopedSignalHandler { fn drop(&mut self) { for signal in &self.signals { if let Err(err) = clear_signal_handler((*signal).into()) { eprintln!("Error: failed to clear signal handler: {:?}", err); } } } } /// A signal handler that does nothing. /// /// This is useful in cases where wait_for_signal is used since it will never trigger if the signal /// is blocked and the default handler may have undesired effects like terminating the process. pub struct EmptySignalHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for EmptySignalHandler { fn handle_signal(_: Signal) {} } /// Blocks until SIGINT is received, which often happens because Ctrl-C was pressed in an /// interactive terminal. /// /// Note: if you are using a multi-threaded application you need to block SIGINT on all other /// threads or they may receive the signal instead of the desired thread. pub fn wait_for_interrupt() -> Result<()> { // Register a signal handler if there is not one already so the thread is not killed. let ret = ScopedSignalHandler::new::<EmptySignalHandler>(&[Signal::Interrupt]); if!matches!(&ret, Ok(_) | Err(Error::HandlerAlreadySet(_))) { ret?; } match wait_for_signal(&[Signal::Interrupt.into()], None) { Ok(_) => Ok(()), Err(err) => Err(Error::WaitForSignal(err)), } } #[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::{BufRead, BufReader}; use std::mem::zeroed; use std::ptr::{null, null_mut}; use std::sync::atomic::{AtomicI32, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, Once}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use libc::sigaction; use crate::{gettid, kill, Pid}; const TEST_SIGNAL: Signal = Signal::User1; const TEST_SIGNALS: &[Signal] = &[Signal::User1, Signal::User2]; static TEST_SIGNAL_COUNTER: AtomicUsize = AtomicUsize::new(0); /// Only allows one test case to execute at a time. fn get_mutex() -> MutexGuard<'static, ()> { static INIT: Once = Once::new(); static mut VAL: Option<Arc<Mutex<()>>> = None; INIT.call_once(|| { let val = Some(Arc::new(Mutex::new(()))); // Safe because the mutation is protected by the Once. unsafe { VAL = val } }); // Safe mutation only happens in the Once. unsafe { VAL.as_ref() }.unwrap().lock().unwrap() } fn reset_counter() { TEST_SIGNAL_COUNTER.swap(0, Ordering::SeqCst); } fn get_sigaction(signal: Signal) -> Result<sigaction> { // Safe because sigaction is owned and expected to be initialized ot zeros. let mut sigact: sigaction = unsafe { zeroed() }; if unsafe { sigaction(signal.into(), null(), &mut sigact) } < 0 { Err(Error::Sigaction(signal, errno::Error::last())) } else { Ok(sigact) } } /// Safety: /// This is only safe if the signal handler set in sigaction is safe. unsafe fn restore_sigaction(signal: Signal, sigact: sigaction) -> Result<sigaction> { if sigaction(signal.into(), &sigact, null_mut()) < 0 { Err(Error::Sigaction(signal, errno::Error::last())) } else { Ok(sigact) } } /// Safety: /// Safe if the signal handler for Signal::User1 is safe. unsafe fn send_test_signal() { kill(gettid(), Signal::User1.into()).unwrap() } macro_rules! assert_counter_eq { ($compare_to:expr) => {{ let expected: usize = $compare_to; let got: usize = TEST_SIGNAL_COUNTER.load(Ordering::SeqCst); if got!= expected { panic!( "wrong signal counter value: got {}; expected {}", got, expected ); } }}; } struct TestHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for TestHandler { fn handle_signal(signal: Signal) { if TEST_SIGNAL == signal { TEST_SIGNAL_COUNTER.fetch_add(1, Ordering::SeqCst); } } } #[test] fn scopedsignalhandler_success() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); reset_counter(); assert_counter_eq!(0); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); let handler = ScopedSignalHandler::new::<TestHandler>(&[TEST_SIGNAL]).unwrap(); assert!(!has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because test_handler is safe. unsafe { send_test_signal() }; // Give the handler time to run in case it is on a different thread. for _ in 1..40 { if TEST_SIGNAL_COUNTER.load(Ordering::SeqCst) > 0 { break; } sleep(Duration::from_millis(250)); } assert_counter_eq!(1); drop(handler); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); } #[test] fn scopedsignalhandler_handleralreadyset() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); reset_counter(); assert_counter_eq!(0); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because TestHandler is async-signal safe. let handler = ScopedSignalHandler::new::<TestHandler>(&[TEST_SIGNAL]).unwrap(); assert!(!has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because TestHandler is async-signal safe. assert!(matches!( ScopedSignalHandler::new::<TestHandler>(TEST_SIGNALS), Err(Error::HandlerAlreadySet(Signal::User1)) )); assert_counter_eq!(0); drop(handler); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); } /// Stores the thread used by WaitForInterruptHandler. static WAIT_FOR_INTERRUPT_THREAD_ID: AtomicI32 = AtomicI32::new(0); /// Forwards SIGINT to the appropriate thread. struct WaitForInterruptHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for WaitForInterruptHandler { fn handle_signal(_: Signal) { let tid = WAIT_FOR_INTERRUPT_THREAD_ID.load(Ordering::SeqCst); // If the thread ID is set and executed on the wrong thread, forward the signal. if tid!= 0 && gettid()!= tid { // Safe because the handler is safe and the target thread id is expecting the signal. unsafe { kill(tid, Signal::Interrupt.into()) }.unwrap(); } } } /// Query /proc/${tid}/status for its State and check if it is either S (sleeping) or in /// D (disk sleep). fn thread_is_sleeping(tid: Pid) -> result::Result<bool, errno::Error> { const PREFIX: &str = "State:"; let mut status_reader = BufReader::new(File::open(format!("/proc/{}/status", tid))?); let mut line = String::new(); loop { let count = status_reader.read_line(&mut line)?; if count == 0 { return Err(errno::Error::new(libc::EIO)); } if let Some(stripped) = line.strip_prefix(PREFIX) { return Ok(matches!( stripped.trim_start().chars().next(), Some('S') | Some('D') )); } line.clear(); } } /// Wait for a process to block either in a sleeping or disk sleep state. fn wait_for_thread_to_sleep(tid: Pid, timeout: Duration) -> result::Result<(), errno::Error> { let start = Instant::now(); loop { if thread_is_sleeping(tid)? { return Ok(()); } if start.elapsed() > timeout { return Err(errno::Error::new(libc::EAGAIN)); } sleep(Duration::from_millis(50)); } } #[test] fn waitforinterrupt_success() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); let to_restore = get_sigaction(Signal::Interrupt).unwrap(); clear_signal_handler(Signal::Interrupt.into()).unwrap(); // Safe because TestHandler is async-signal safe. let handler = ScopedSignalHandler::new::<WaitForInterruptHandler>(&[Signal::Interrupt]).unwrap(); let tid = gettid(); WAIT_FOR_INTERRUPT_THREAD_ID.store(tid, Ordering::SeqCst); let join_handle = spawn(move || -> result::Result<(), errno::Error> { // Wait unitl the thread is ready to receive the signal. wait_for_thread_to_sleep(tid, Duration::from_secs(10)).unwrap(); // Safe because the SIGINT handler is safe. unsafe { kill(tid, Signal::Interrupt.into()) } }); let wait_ret = wait_for_interrupt(); let join_ret = join_handle.join(); drop(handler); // Safe because we are restoring the previous SIGINT handler. unsafe { restore_sigaction(Signal::Interrupt, to_restore) }.unwrap(); wait_ret.unwrap(); join_ret.unwrap().unwrap(); } }
// eprintln! - uses std::io which has locks that may be held.
random_line_split
scoped_signal_handler.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Provides a struct for registering signal handlers that get cleared on drop. use std::convert::TryFrom; use std::fmt; use std::io::{Cursor, Write}; use std::panic::catch_unwind; use std::result; use libc::{c_int, c_void, STDERR_FILENO}; use remain::sorted; use thiserror::Error; use crate::errno; use crate::signal::{ clear_signal_handler, has_default_signal_handler, register_signal_handler, wait_for_signal, Signal, }; #[sorted] #[derive(Error, Debug)] pub enum Error { /// Already waiting for interrupt. #[error("already waiting for interrupt.")] AlreadyWaiting, /// Signal already has a handler. #[error("signal handler already set for {0:?}")] HandlerAlreadySet(Signal), /// Failed to check if signal has the default signal handler. #[error("failed to check the signal handler for {0:?}: {1}")] HasDefaultSignalHandler(Signal, errno::Error), /// Failed to register a signal handler. #[error("failed to register a signal handler for {0:?}: {1}")] RegisterSignalHandler(Signal, errno::Error), /// Sigaction failed. #[error("sigaction failed for {0:?}: {1}")] Sigaction(Signal, errno::Error), /// Failed to wait for signal. #[error("wait_for_signal failed: {0}")] WaitForSignal(errno::Error), } pub type Result<T> = result::Result<T, Error>; /// The interface used by Scoped Signal handler. /// /// # Safety /// The implementation of handle_signal needs to be async signal-safe. /// /// NOTE: panics are caught when possible because a panic inside ffi is undefined behavior. pub unsafe trait SignalHandler { /// A function that is called to handle the passed signal. fn handle_signal(signal: Signal); } /// Wrap the handler with an extern "C" function. extern "C" fn call_handler<H: SignalHandler>(signum: c_int) { // Make an effort to surface an error. if catch_unwind(|| H::handle_signal(Signal::try_from(signum).unwrap())).is_err() { // Note the following cannot be used: // eprintln! - uses std::io which has locks that may be held. // format! - uses the allocator which enforces mutual exclusion. // Get the debug representation of signum. let signal: Signal; let signal_debug: &dyn fmt::Debug = match Signal::try_from(signum) { Ok(s) => { signal = s; &signal as &dyn fmt::Debug } Err(_) => &signum as &dyn fmt::Debug, }; // Buffer the output, so a single call to write can be used. // The message accounts for 29 chars, that leaves 35 for the string representation of the // signal which is more than enough. let mut buffer = [0u8; 64]; let mut cursor = Cursor::new(buffer.as_mut()); if writeln!(cursor, "signal handler got error for: {:?}", signal_debug).is_ok() { let len = cursor.position() as usize; // Safe in the sense that buffer is owned and the length is checked. This may print in // the middle of an existing write, but that is considered better than dropping the // error. unsafe { libc::write( STDERR_FILENO, cursor.get_ref().as_ptr() as *const c_void, len, ) }; } else { // This should never happen, but write an error message just in case. const ERROR_DROPPED: &str = "Error dropped by signal handler."; let bytes = ERROR_DROPPED.as_bytes(); unsafe { libc::write(STDERR_FILENO, bytes.as_ptr() as *const c_void, bytes.len()) }; } } } /// Represents a signal handler that is registered with a set of signals that unregistered when the /// struct goes out of scope. Prefer a signalfd based solution before using this. pub struct ScopedSignalHandler { signals: Vec<Signal>, } impl ScopedSignalHandler { /// Attempts to register `handler` with the provided `signals`. It will fail if there is already /// an existing handler on any of `signals`. /// /// # Safety /// This is safe if H::handle_signal is async-signal safe. pub fn new<H: SignalHandler>(signals: &[Signal]) -> Result<Self> { let mut scoped_handler = ScopedSignalHandler { signals: Vec::with_capacity(signals.len()), }; for &signal in signals { if!has_default_signal_handler((signal).into()) .map_err(|err| Error::HasDefaultSignalHandler(signal, err))? { return Err(Error::HandlerAlreadySet(signal)); } // Requires an async-safe callback. unsafe { register_signal_handler((signal).into(), call_handler::<H>) .map_err(|err| Error::RegisterSignalHandler(signal, err))? }; scoped_handler.signals.push(signal); } Ok(scoped_handler) } } /// Clears the signal handler for any of the associated signals. impl Drop for ScopedSignalHandler { fn drop(&mut self) { for signal in &self.signals { if let Err(err) = clear_signal_handler((*signal).into()) { eprintln!("Error: failed to clear signal handler: {:?}", err); } } } } /// A signal handler that does nothing. /// /// This is useful in cases where wait_for_signal is used since it will never trigger if the signal /// is blocked and the default handler may have undesired effects like terminating the process. pub struct
; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for EmptySignalHandler { fn handle_signal(_: Signal) {} } /// Blocks until SIGINT is received, which often happens because Ctrl-C was pressed in an /// interactive terminal. /// /// Note: if you are using a multi-threaded application you need to block SIGINT on all other /// threads or they may receive the signal instead of the desired thread. pub fn wait_for_interrupt() -> Result<()> { // Register a signal handler if there is not one already so the thread is not killed. let ret = ScopedSignalHandler::new::<EmptySignalHandler>(&[Signal::Interrupt]); if!matches!(&ret, Ok(_) | Err(Error::HandlerAlreadySet(_))) { ret?; } match wait_for_signal(&[Signal::Interrupt.into()], None) { Ok(_) => Ok(()), Err(err) => Err(Error::WaitForSignal(err)), } } #[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::{BufRead, BufReader}; use std::mem::zeroed; use std::ptr::{null, null_mut}; use std::sync::atomic::{AtomicI32, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, Once}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use libc::sigaction; use crate::{gettid, kill, Pid}; const TEST_SIGNAL: Signal = Signal::User1; const TEST_SIGNALS: &[Signal] = &[Signal::User1, Signal::User2]; static TEST_SIGNAL_COUNTER: AtomicUsize = AtomicUsize::new(0); /// Only allows one test case to execute at a time. fn get_mutex() -> MutexGuard<'static, ()> { static INIT: Once = Once::new(); static mut VAL: Option<Arc<Mutex<()>>> = None; INIT.call_once(|| { let val = Some(Arc::new(Mutex::new(()))); // Safe because the mutation is protected by the Once. unsafe { VAL = val } }); // Safe mutation only happens in the Once. unsafe { VAL.as_ref() }.unwrap().lock().unwrap() } fn reset_counter() { TEST_SIGNAL_COUNTER.swap(0, Ordering::SeqCst); } fn get_sigaction(signal: Signal) -> Result<sigaction> { // Safe because sigaction is owned and expected to be initialized ot zeros. let mut sigact: sigaction = unsafe { zeroed() }; if unsafe { sigaction(signal.into(), null(), &mut sigact) } < 0 { Err(Error::Sigaction(signal, errno::Error::last())) } else { Ok(sigact) } } /// Safety: /// This is only safe if the signal handler set in sigaction is safe. unsafe fn restore_sigaction(signal: Signal, sigact: sigaction) -> Result<sigaction> { if sigaction(signal.into(), &sigact, null_mut()) < 0 { Err(Error::Sigaction(signal, errno::Error::last())) } else { Ok(sigact) } } /// Safety: /// Safe if the signal handler for Signal::User1 is safe. unsafe fn send_test_signal() { kill(gettid(), Signal::User1.into()).unwrap() } macro_rules! assert_counter_eq { ($compare_to:expr) => {{ let expected: usize = $compare_to; let got: usize = TEST_SIGNAL_COUNTER.load(Ordering::SeqCst); if got!= expected { panic!( "wrong signal counter value: got {}; expected {}", got, expected ); } }}; } struct TestHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for TestHandler { fn handle_signal(signal: Signal) { if TEST_SIGNAL == signal { TEST_SIGNAL_COUNTER.fetch_add(1, Ordering::SeqCst); } } } #[test] fn scopedsignalhandler_success() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); reset_counter(); assert_counter_eq!(0); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); let handler = ScopedSignalHandler::new::<TestHandler>(&[TEST_SIGNAL]).unwrap(); assert!(!has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because test_handler is safe. unsafe { send_test_signal() }; // Give the handler time to run in case it is on a different thread. for _ in 1..40 { if TEST_SIGNAL_COUNTER.load(Ordering::SeqCst) > 0 { break; } sleep(Duration::from_millis(250)); } assert_counter_eq!(1); drop(handler); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); } #[test] fn scopedsignalhandler_handleralreadyset() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); reset_counter(); assert_counter_eq!(0); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because TestHandler is async-signal safe. let handler = ScopedSignalHandler::new::<TestHandler>(&[TEST_SIGNAL]).unwrap(); assert!(!has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); // Safe because TestHandler is async-signal safe. assert!(matches!( ScopedSignalHandler::new::<TestHandler>(TEST_SIGNALS), Err(Error::HandlerAlreadySet(Signal::User1)) )); assert_counter_eq!(0); drop(handler); assert!(has_default_signal_handler(TEST_SIGNAL.into()).unwrap()); } /// Stores the thread used by WaitForInterruptHandler. static WAIT_FOR_INTERRUPT_THREAD_ID: AtomicI32 = AtomicI32::new(0); /// Forwards SIGINT to the appropriate thread. struct WaitForInterruptHandler; /// # Safety /// Safe because handle_signal is async-signal safe. unsafe impl SignalHandler for WaitForInterruptHandler { fn handle_signal(_: Signal) { let tid = WAIT_FOR_INTERRUPT_THREAD_ID.load(Ordering::SeqCst); // If the thread ID is set and executed on the wrong thread, forward the signal. if tid!= 0 && gettid()!= tid { // Safe because the handler is safe and the target thread id is expecting the signal. unsafe { kill(tid, Signal::Interrupt.into()) }.unwrap(); } } } /// Query /proc/${tid}/status for its State and check if it is either S (sleeping) or in /// D (disk sleep). fn thread_is_sleeping(tid: Pid) -> result::Result<bool, errno::Error> { const PREFIX: &str = "State:"; let mut status_reader = BufReader::new(File::open(format!("/proc/{}/status", tid))?); let mut line = String::new(); loop { let count = status_reader.read_line(&mut line)?; if count == 0 { return Err(errno::Error::new(libc::EIO)); } if let Some(stripped) = line.strip_prefix(PREFIX) { return Ok(matches!( stripped.trim_start().chars().next(), Some('S') | Some('D') )); } line.clear(); } } /// Wait for a process to block either in a sleeping or disk sleep state. fn wait_for_thread_to_sleep(tid: Pid, timeout: Duration) -> result::Result<(), errno::Error> { let start = Instant::now(); loop { if thread_is_sleeping(tid)? { return Ok(()); } if start.elapsed() > timeout { return Err(errno::Error::new(libc::EAGAIN)); } sleep(Duration::from_millis(50)); } } #[test] fn waitforinterrupt_success() { // Prevent other test cases from running concurrently since the signal // handlers are shared for the process. let _guard = get_mutex(); let to_restore = get_sigaction(Signal::Interrupt).unwrap(); clear_signal_handler(Signal::Interrupt.into()).unwrap(); // Safe because TestHandler is async-signal safe. let handler = ScopedSignalHandler::new::<WaitForInterruptHandler>(&[Signal::Interrupt]).unwrap(); let tid = gettid(); WAIT_FOR_INTERRUPT_THREAD_ID.store(tid, Ordering::SeqCst); let join_handle = spawn(move || -> result::Result<(), errno::Error> { // Wait unitl the thread is ready to receive the signal. wait_for_thread_to_sleep(tid, Duration::from_secs(10)).unwrap(); // Safe because the SIGINT handler is safe. unsafe { kill(tid, Signal::Interrupt.into()) } }); let wait_ret = wait_for_interrupt(); let join_ret = join_handle.join(); drop(handler); // Safe because we are restoring the previous SIGINT handler. unsafe { restore_sigaction(Signal::Interrupt, to_restore) }.unwrap(); wait_ret.unwrap(); join_ret.unwrap().unwrap(); } }
EmptySignalHandler
identifier_name
wavelet_tree_pointer.rs
use bio::data_structures::rank_select::RankSelect; use bv::BitVec; use bv::BitsMut; use itertools::Itertools; use serde::{Deserialize, Serialize}; use snafu::{ensure, Snafu}; use std::fmt::Debug; use std::hash::Hash; use std::ops::Index; ///custom errors for the tree with pointer #[derive(Debug, Snafu)] pub enum Error { #[snafu(display( "Es gibt kein 0tes Element, das erste Element wird mit access(1) angesprochen" ))] Access0, #[snafu(display("Eingabe darf bei select nicht kleiner als 1 sein"))] SelectSmaller0, #[snafu(display("Fehler bei root unwrap in access"))] RootUnwrapError, #[snafu(display("Index ist größer als die Länge der Sequence"))] IndexOutOfBound, #[snafu(display("Element nicht gefunden"))] NoSuchElement, #[snafu(display("Element nicht im Alphabet, Fehler bei select"))] NotInAlphabet, #[snafu(display("Das Symbol kommt nicht oft genug im Wort vor"))] NotEnoughElements, #[snafu(display("PlatzhalterError"))] TempError, } ///representation of the WaveletTree #[derive(Serialize, Deserialize)] pub struct WaveletTree<T> { //The alphabet of the sequence the tree is build from alphabet: Vec<T>, //the first node that holds a bitmap over the entire sequence root: Option<Box<BinNode>>, } ///representation of the nodes in the tree, ///they are managed by the tree and the user has no direct access #[derive(Serialize, Deserialize)] struct BinNode { ///The bitmap stored in the node value: RankSelect, ///The left Child of the node left: Option<Box<BinNode>>, ///The right child of the node right: Option<Box<BinNode>>, } ///The Iterator for WaveletTrees pub struct Iterhelper<'de, T> { position: usize, tree: &'de WaveletTree<T>, } impl<'de, T> WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { /// creates a WaveletTree out of a given sequence /// * `sequence` - the sequence that is representet in the tree pub fn create<S: Clone + Iterator<Item = T>>(sequence: S) -> WaveletTree<T> { let mut sequence = sequence.peekable(); if sequence.peek().is_none() { panic!("Die übergebene Sequence ist leer!") }; let seqvec = sequence.clone().collect::<Vec<_>>(); let mut alphabet: Vec<T> = Vec::new(); alphabet.extend(sequence.unique()); alphabet.sort(); let alphslice = &alphabet[..]; WaveletTree { root: Some(Box::new(BinNode::create_node(alphslice, seqvec))), alphabet: alphabet, } } ///Returns the element at index, or an error if something goes wrong. ///To make the use of this funktion more intuitiv index starts at 1, so if you want the xth element you can call access(x) pub fn access(&self, index: usize) -> Result<T, Error> { ensure!(index > 0, Access0); // Abfangen von fehlerhafter Eingabe, Index ist größer als Sequenz let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; ensure!(z.len() >= index as u64, IndexOutOfBound); let z = match &self.root { Some(x) => x.access((index - 1) as u64, 0, self.alphabet.len() - 1), None => return Err(Error::RootUnwrapError), }; match z { Some(x) => Ok(self.alphabet[x]), None => return Err(Error::NoSuchElement), } } fn access_ref(&self, index: usize) -> &T { let result = match self.access(index) { Ok(x) => x, Err(_) => panic!("Index out of Bounds"), }; for i in 0..self.alphabet.len() { if self.alphabet[i] == result { return &self.alphabet[i]; } } panic!("Index in Bounds but not found"); } ///Returns the the position of the index'th occurence of the character pub fn select(&self, character: T, index: usize) -> Result<u64, Error> { // Abfangen von fehlerhafter Eingabe, Index darf hier nicht 0 sein ensure!(index > 0, SelectSmaller0); //------------------------ let character_index1 = &self.alphabet.binary_search(&character); // speichere an welchem index steht das gesuchte zeichen im alphabet steht let character_index = match character_index1 { Ok(x) => x, Err(_) => return Err(Error::NotInAlphabet), }; //Abfangen dass der Buchstabe nicht index oft vorkommt let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; if &self.rank(character, z.len() as usize).unwrap() < &(index as u64) { return Err(Error::NotEnoughElements); } let result = match &self.root { Some(x) => x.select(index as u64, character_index, 0, self.alphabet.len() - 1), None => return Err(Error::TempError), //Err("Fehler"), }; match result { Some(x) => return Ok(x + 1), None => return Err(Error::TempError), } } /// Returns the number of occurences of the character in the Intervall [1..index]. pub fn rank(&self, character: T, index: usize) -> Result<u64, Error> { if index < 1 { return Ok(0); } let index = index - 1; let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; // Abfangen von fehlerhafter Eingabe, Index ist größer als Sequenz ensure!(z.len() > index as u64, IndexOutOfBound); //--------------------------------- let character_index1 = &self.alphabet.binary_search(&character); // speichere an welchem index das gesuchte zeichen im alphabet steht let character_index = match character_index1 { Ok(x) => x, Err(_) => return Ok(0), //element nicht in alphabet => gib 0 zurück }; let result = match &self.root { Some(x) => (*x).rank(index as u64, character_index, 0, &self.alphabet.len() - 1), None => return Err(Error::NoSuchElement), }; match result { Some(x) => return Ok(x), None => return Err(Error::NoSuchElement), } } /// Returns a Vector that holds the sequence, this does not consume the tree pub fn rebuild(&'de self) -> Vec<T> { let mut result: Vec<T> = Vec::new(); for x in self.into_iter() { result.push(x); } result } ///Returns the length of the sequence or an error if the root is missing pub fn len(&self) -> Result<u64, Error> { let root = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; Ok(root.len()) } ///Returns the lenght of the alphabet pub fn alphabet_len(&self) -> usize { self.alphabet.len() } } ///Implements the Index Trait to allow access with [index], since it uses the access function index starts at 1 impl<'de, T> Index<usize> for WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Output = T; fn index(&self, index: usize) -> &Self::Output { &self.access_ref(index) } } impl BinNode { fn create_no
+ Clone + Ord + Debug>(alphabet: &[E], sequence: Vec<E>) -> BinNode { let count = sequence.len(); if alphabet.len() <= 1 { let value = BitVec::new_fill(true, count as u64); BinNode { value: RankSelect::new(value, 1), left: None, right: None, } } else { let mut value = BitVec::new_fill(false, count as u64); let mid = (alphabet.len() + 1) / 2; //Das Alphabet wird geteilt, die 2. Hälfte wird in alphabet2 gespeichert let (alphabet1, alphabet2) = alphabet.split_at(mid); //Die Sequenzen für den nächsten Schritt let mut sequence1 = Vec::new(); let mut sequence2 = Vec::new(); //Es werden alle Elemente der Sequenz durchegangen for x in 0..(sequence.len()) { //wenn sie in der 2. Hälfte des Alphabets sind wird ihr Eintrag in der Bitmap auf 1 gesetzt if alphabet2.contains(&sequence[x]) { value.set_bit(x as u64, true) } } //Group_by teilt in Gruppen key ist true wenn Zeichen in alphabet1, sonst false for (key, group) in &sequence .into_iter() .group_by(|elem| alphabet1.contains(&elem)) { //neue Sequencen werden anhand der Keys gebaut if key { sequence1.extend(group) } else { sequence2.extend(group) } } BinNode { value: RankSelect::new(value, 1), left: Some(Box::new(BinNode::create_node(alphabet1, sequence1))), right: Some(Box::new(BinNode::create_node(alphabet2, sequence2))), } } } fn access(&self, index: u64, min: usize, max: usize) -> Option<usize> { if min == max { return Some(min); } else { if self.value.get((index) as u64) { let next_index = self.value.rank((index) as u64).unwrap(); match &self.right { Some(x) => return (*x).access(next_index - 1, 1 + (min + max) / 2, max), None => return None, } } else { let next_index = self.value.rank_0((index) as u64).unwrap(); match &self.left { Some(x) => return (*x).access(next_index - 1, min, (min + max) / 2), None => return None, } } } } fn select(&self, index: u64, character: &usize, min: usize, max: usize) -> Option<(u64)> { //Blatt erreicht if min == max { return Some(index - 1); } // Position wird in Index umgerechnet, da Eingabe mit Position erfolgt else { if character <= &((max + min) / 2) { let result = match &self.left { Some(x) => (*x).select(index, character, min, (min + max) / 2), None => return None, }; let new_index = match result { Some(x) => x, None => return None, }; return self.value.select_0(new_index + 1); //+1 da Index in Position umgerechnet wird } else { let result = match &self.right { Some(x) => (*x).select(index, character, (min + max) / 2 + 1, max), None => return None, }; let new_index = match result { Some(x) => x, None => return None, }; return self.value.select_1(new_index + 1); //+1 da Index in Position umgerechnet wird } } } fn rank(&self, index: u64, character: &usize, min: usize, max: usize) -> Option<u64> { if min == max { return Some(index + 1); } //Wenn nicht im blatt else { if character <= &((max + min) / 2) { let next_index = self.value.rank_0((index) as u64).unwrap(); match &self.left { Some(x) => return (*x).rank(next_index - 1, character, min, (min + max) / 2), None => return None, } } else { let next_index = self.value.rank((index) as u64).unwrap(); match &self.right { Some(x) => { return (*x).rank(next_index - 1, character, ((min + max) / 2) + 1, max); } None => return None, } } } } fn len(&self) -> u64 { self.value.bits().len() } } ///Implements a non-consuming Iterator for the WaveletTree impl<'de, T> IntoIterator for &'de WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Item = T; type IntoIter = Iterhelper<'de, T>; fn into_iter(self) -> Self::IntoIter { Iterhelper { position: 0, tree: self, } } } impl<'de, T> Iterator for Iterhelper<'de, T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.position += 1; let len = match self.tree.len() { Ok(x) => x, Err(_) => return None, }; if self.position <= len as usize { match self.tree.access(self.position) { Ok(x) => return Some(x), Err(_) => return None, }; } else { None } } }
de<E: Hash
identifier_name
wavelet_tree_pointer.rs
use bio::data_structures::rank_select::RankSelect; use bv::BitVec; use bv::BitsMut; use itertools::Itertools; use serde::{Deserialize, Serialize}; use snafu::{ensure, Snafu}; use std::fmt::Debug; use std::hash::Hash; use std::ops::Index; ///custom errors for the tree with pointer #[derive(Debug, Snafu)] pub enum Error { #[snafu(display( "Es gibt kein 0tes Element, das erste Element wird mit access(1) angesprochen" ))] Access0, #[snafu(display("Eingabe darf bei select nicht kleiner als 1 sein"))] SelectSmaller0, #[snafu(display("Fehler bei root unwrap in access"))] RootUnwrapError, #[snafu(display("Index ist größer als die Länge der Sequence"))] IndexOutOfBound, #[snafu(display("Element nicht gefunden"))] NoSuchElement, #[snafu(display("Element nicht im Alphabet, Fehler bei select"))] NotInAlphabet, #[snafu(display("Das Symbol kommt nicht oft genug im Wort vor"))] NotEnoughElements, #[snafu(display("PlatzhalterError"))] TempError, } ///representation of the WaveletTree #[derive(Serialize, Deserialize)] pub struct WaveletTree<T> { //The alphabet of the sequence the tree is build from alphabet: Vec<T>, //the first node that holds a bitmap over the entire sequence root: Option<Box<BinNode>>, } ///representation of the nodes in the tree, ///they are managed by the tree and the user has no direct access #[derive(Serialize, Deserialize)] struct BinNode { ///The bitmap stored in the node value: RankSelect, ///The left Child of the node left: Option<Box<BinNode>>, ///The right child of the node right: Option<Box<BinNode>>, } ///The Iterator for WaveletTrees pub struct Iterhelper<'de, T> { position: usize, tree: &'de WaveletTree<T>, } impl<'de, T> WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { /// creates a WaveletTree out of a given sequence /// * `sequence` - the sequence that is representet in the tree pub fn create<S: Clone + Iterator<Item = T>>(sequence: S) -> WaveletTree<T> { let mut sequence = sequence.peekable(); if sequence.peek().is_none() { panic!("Die übergebene Sequence ist leer!") }; let seqvec = sequence.clone().collect::<Vec<_>>(); let mut alphabet: Vec<T> = Vec::new(); alphabet.extend(sequence.unique()); alphabet.sort(); let alphslice = &alphabet[..]; WaveletTree { root: Some(Box::new(BinNode::create_node(alphslice, seqvec))), alphabet: alphabet, } } ///Returns the element at index, or an error if something goes wrong. ///To make the use of this funktion more intuitiv index starts at 1, so if you want the xth element you can call access(x) pub fn access(&self, index: usize) -> Result<T, Error> { ensure!(index > 0, Access0); // Abfangen von fehlerhafter Eingabe, Index ist größer als Sequenz let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; ensure!(z.len() >= index as u64, IndexOutOfBound); let z = match &self.root { Some(x) => x.access((index - 1) as u64, 0, self.alphabet.len() - 1), None => return Err(Error::RootUnwrapError), }; match z { Some(x) => Ok(self.alphabet[x]), None => return Err(Error::NoSuchElement), } } fn access_ref(&self, index: usize) -> &T { let result = match self.access(index) { Ok(x) => x, Err(_) => panic!("Index out of Bounds"), }; for i in 0..self.alphabet.len() { if self.alphabet[i] == result { return &self.alphabet[i]; } } panic!("Index in Bounds but not found"); } ///Returns the the position of the index'th occurence of the character pub fn select(&self, character: T, index: usize) -> Result<u64, Error> { // Abfangen von fehlerhafter Eingabe, Index darf hier nicht 0 sein ensure!(index > 0, SelectSmaller0); //------------------------ let character_index1 = &self.alphabet.binary_search(&character); // speichere an welchem index steht das gesuchte zeichen im alphabet steht let character_index = match character_index1 { Ok(x) => x, Err(_) => return Err(Error::NotInAlphabet), }; //Abfangen dass der Buchstabe nicht index oft vorkommt let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; if &self.rank(character, z.len() as usize).unwrap() < &(index as u64) { return Err(Error::NotEnoughElements); } let result = match &self.root { Some(x) => x.select(index as u64, character_index, 0, self.alphabet.len() - 1), None => return Err(Error::TempError), //Err("Fehler"), }; match result { Some(x) => return Ok(x + 1), None => return Err(Error::TempError), } } /// Returns the number of occurences of the character in the Intervall [1..index]. pub fn rank(&self, character: T, index: usize) -> Result<u64, Error> { if index < 1 { return Ok(0); } let index = index - 1; let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; // Abfangen von fehlerhafter Eingabe, Index ist größer als Sequenz ensure!(z.len() > index as u64, IndexOutOfBound); //--------------------------------- let character_index1 = &self.alphabet.binary_search(&character); // speichere an welchem index das gesuchte zeichen im alphabet steht let character_index = match character_index1 { Ok(x) => x, Err(_) => return Ok(0), //element nicht in alphabet => gib 0 zurück }; let result = match &self.root { Some(x) => (*x).rank(index as u64, character_index, 0, &self.alphabet.len() - 1), None => return Err(Error::NoSuchElement), }; match result { Some(x) => return Ok(x), None => return Err(Error::NoSuchElement), } } /// Returns a Vector that holds the sequence, this does not consume the tree pub fn rebuild(&'de self) -> Vec<T> { let mut result: Vec<T> = Vec::new(); for x in self.into_iter() { result.push(x); } result } ///Returns the length of the sequence or an error if the root is missing pub fn len(&self) -> Result<u64, Error> { let root = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; Ok(root.len()) } ///Returns the lenght of the alphabet pub fn alphabet_len(&self) -> usize { self.alphabet.len() } } ///Implements the Index Trait to allow access with [index], since it uses the access function index starts at 1 impl<'de, T> Index<usize> for WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Output = T; fn index(&self, index: usize) -> &Self::Output { &self.access_ref(index) } } impl BinNode { fn create_node<E: Hash + Clone + Ord + Debug>(alphabet: &[E], sequence: Vec<E>) -> BinNode { let count = sequence.len(); if alphabet.len() <= 1 { let value = BitVec::new_fill(true, count as u64); BinNode { value: RankSelect::new(value, 1), left: None, right: None, } } else { let mut value = BitVec::new_fill(false, count as u64); let mid = (alphabet.len() + 1) / 2; //Das Alphabet wird geteilt, die 2. Hälfte wird in alphabet2 gespeichert let (alphabet1, alphabet2) = alphabet.split_at(mid); //Die Sequenzen für den nächsten Schritt let mut sequence1 = Vec::new(); let mut sequence2 = Vec::new(); //Es werden alle Elemente der Sequenz durchegangen for x in 0..(sequence.len()) { //wenn sie in der 2. Hälfte des Alphabets sind wird ihr Eintrag in der Bitmap auf 1 gesetzt if alphabet2.contains(&sequence[x]) { value.set_bit(x as u64, true) } } //Group_by teilt in Gruppen key ist true wenn Zeichen in alphabet1, sonst false for (key, group) in &sequence .into_iter() .group_by(|elem| alphabet1.contains(&elem)) { //neue Sequencen werden anhand der Keys gebaut if key { sequence1.extend(group) } else { sequence2.extend(group) } } BinNode { value: RankSelect::new(value, 1), left: Some(Box::new(BinNode::create_node(alphabet1, sequence1))), right: Some(Box::new(BinNode::create_node(alphabet2, sequence2))), } } } fn access(&self, index: u64, min: usize, max: usize) -> Option<usize> { if min == max { return Some(min); } else { if self.value.get((index) as u64) { let next_index = self.value.rank((index) as u64).unwrap(); match &self.right { Some(x) => return (*x).access(next_index - 1, 1 + (min + max) / 2, max), None => return None, } } else { let next_index = self.value.rank_0((index) as u64).unwrap(); match &self.left { Some(x) => return (*x).access(next_index - 1, min, (min + max) / 2), None => return None, } } } } fn select(&self, index: u64, character: &usize, min: usize, max: usize) -> Option<(u64)> { //Blatt erreicht if min == max { return Some(index - 1); } // Position wird in Index umgerechnet, da Eingabe mit Position erfolgt else { if character <= &((max + min) / 2) { let result = match &self.left { Some(x) => (*x).select(index, character, min, (min + max) / 2), None => return None, }; let new_index = match result { Some(x) => x, None => return None, }; return self.value.select_0(new_index + 1); //+1 da Index in Position umgerechnet wird } else { let result = match &self.right { Some(x) => (*x).select(index, character, (min + max) / 2 + 1, max), None => return None, }; let new_index = match result { Some(x) => x, None => return None, }; return self.value.select_1(new_index + 1); //+1 da Index in Position umgerechnet wird } } } fn rank(&self, index: u64, character: &usize, min: usize, max: usize) -> Option<u64> { if min == max { return Some(index + 1); } //Wenn nicht im blatt else { if character <= &((max + min) / 2) { let next_index = self.value.rank_0((index) as u64).unwrap(); match &self.left { Some(x) => return (*x).rank(next_index - 1, character, min, (min + max) / 2), None => return None, } } else { let next_index = self.value.rank((index) as u64).unwrap(); match &self.right { Some(x) => { return (*x).rank(next_index - 1, character, ((min + max) / 2) + 1, max); } None => return None, } } } } fn len(&self) -> u64 { sel
nts a non-consuming Iterator for the WaveletTree impl<'de, T> IntoIterator for &'de WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Item = T; type IntoIter = Iterhelper<'de, T>; fn into_iter(self) -> Self::IntoIter { Iterhelper { position: 0, tree: self, } } } impl<'de, T> Iterator for Iterhelper<'de, T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.position += 1; let len = match self.tree.len() { Ok(x) => x, Err(_) => return None, }; if self.position <= len as usize { match self.tree.access(self.position) { Ok(x) => return Some(x), Err(_) => return None, }; } else { None } } }
f.value.bits().len() } } ///Impleme
identifier_body
wavelet_tree_pointer.rs
use bio::data_structures::rank_select::RankSelect; use bv::BitVec; use bv::BitsMut; use itertools::Itertools; use serde::{Deserialize, Serialize}; use snafu::{ensure, Snafu}; use std::fmt::Debug; use std::hash::Hash; use std::ops::Index; ///custom errors for the tree with pointer #[derive(Debug, Snafu)] pub enum Error { #[snafu(display( "Es gibt kein 0tes Element, das erste Element wird mit access(1) angesprochen" ))] Access0, #[snafu(display("Eingabe darf bei select nicht kleiner als 1 sein"))] SelectSmaller0, #[snafu(display("Fehler bei root unwrap in access"))] RootUnwrapError, #[snafu(display("Index ist größer als die Länge der Sequence"))] IndexOutOfBound, #[snafu(display("Element nicht gefunden"))] NoSuchElement, #[snafu(display("Element nicht im Alphabet, Fehler bei select"))] NotInAlphabet, #[snafu(display("Das Symbol kommt nicht oft genug im Wort vor"))] NotEnoughElements, #[snafu(display("PlatzhalterError"))] TempError, } ///representation of the WaveletTree #[derive(Serialize, Deserialize)] pub struct WaveletTree<T> { //The alphabet of the sequence the tree is build from alphabet: Vec<T>, //the first node that holds a bitmap over the entire sequence root: Option<Box<BinNode>>, } ///representation of the nodes in the tree, ///they are managed by the tree and the user has no direct access #[derive(Serialize, Deserialize)] struct BinNode { ///The bitmap stored in the node value: RankSelect, ///The left Child of the node left: Option<Box<BinNode>>, ///The right child of the node right: Option<Box<BinNode>>, } ///The Iterator for WaveletTrees pub struct Iterhelper<'de, T> { position: usize, tree: &'de WaveletTree<T>, } impl<'de, T> WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { /// creates a WaveletTree out of a given sequence /// * `sequence` - the sequence that is representet in the tree pub fn create<S: Clone + Iterator<Item = T>>(sequence: S) -> WaveletTree<T> { let mut sequence = sequence.peekable(); if sequence.peek().is_none() { panic!("Die übergebene Sequence ist leer!") }; let seqvec = sequence.clone().collect::<Vec<_>>(); let mut alphabet: Vec<T> = Vec::new(); alphabet.extend(sequence.unique()); alphabet.sort(); let alphslice = &alphabet[..]; WaveletTree { root: Some(Box::new(BinNode::create_node(alphslice, seqvec))), alphabet: alphabet, } } ///Returns the element at index, or an error if something goes wrong. ///To make the use of this funktion more intuitiv index starts at 1, so if you want the xth element you can call access(x) pub fn access(&self, index: usize) -> Result<T, Error> { ensure!(index > 0, Access0); // Abfangen von fehlerhafter Eingabe, Index ist größer als Sequenz let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; ensure!(z.len() >= index as u64, IndexOutOfBound); let z = match &self.root { Some(x) => x.access((index - 1) as u64, 0, self.alphabet.len() - 1), None => return Err(Error::RootUnwrapError), }; match z { Some(x) => Ok(self.alphabet[x]), None => return Err(Error::NoSuchElement), } } fn access_ref(&self, index: usize) -> &T { let result = match self.access(index) { Ok(x) => x, Err(_) => panic!("Index out of Bounds"), }; for i in 0..self.alphabet.len() { if self.alphabet[i] == result { return &self.alphabet[i]; } } panic!("Index in Bounds but not found"); } ///Returns the the position of the index'th occurence of the character pub fn select(&self, character: T, index: usize) -> Result<u64, Error> { // Abfangen von fehlerhafter Eingabe, Index darf hier nicht 0 sein ensure!(index > 0, SelectSmaller0); //------------------------ let character_index1 = &self.alphabet.binary_search(&character); // speichere an welchem index steht das gesuchte zeichen im alphabet steht let character_index = match character_index1 { Ok(x) => x, Err(_) => return Err(Error::NotInAlphabet), }; //Abfangen dass der Buchstabe nicht index oft vorkommt let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; if &self.rank(character, z.len() as usize).unwrap() < &(index as u64) { return Err(Error::NotEnoughElements); } let result = match &self.root { Some(x) => x.select(index as u64, character_index, 0, self.alphabet.len() - 1), None => return Err(Error::TempError), //Err("Fehler"), }; match result { Some(x) => return Ok(x + 1), None => return Err(Error::TempError), } } /// Returns the number of occurences of the character in the Intervall [1..index]. pub fn rank(&self, character: T, index: usize) -> Result<u64, Error> { if index < 1 { return Ok(0); } let index = index - 1; let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; // Abfangen von fehlerhafter Eingabe, Index ist größer als Sequenz ensure!(z.len() > index as u64, IndexOutOfBound); //--------------------------------- let character_index1 = &self.alphabet.binary_search(&character); // speichere an welchem index das gesuchte zeichen im alphabet steht let character_index = match character_index1 { Ok(x) => x, Err(_) => return Ok(0), //element nicht in alphabet => gib 0 zurück }; let result = match &self.root { Some(x) => (*x).rank(index as u64, character_index, 0, &self.alphabet.len() - 1), None => return Err(Error::NoSuchElement), }; match result { Some(x) => return Ok(x), None => return Err(Error::NoSuchElement), } } /// Returns a Vector that holds the sequence, this does not consume the tree pub fn rebuild(&'de self) -> Vec<T> { let mut result: Vec<T> = Vec::new(); for x in self.into_iter() { result.push(x); } result } ///Returns the length of the sequence or an error if the root is missing pub fn len(&self) -> Result<u64, Error> { let root = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; Ok(root.len()) } ///Returns the lenght of the alphabet pub fn alphabet_len(&self) -> usize { self.alphabet.len() } } ///Implements the Index Trait to allow access with [index], since it uses the access function index starts at 1 impl<'de, T> Index<usize> for WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Output = T; fn index(&self, index: usize) -> &Self::Output { &self.access_ref(index) } } impl BinNode { fn create_node<E: Hash + Clone + Ord + Debug>(alphabet: &[E], sequence: Vec<E>) -> BinNode { let count = sequence.len(); if alphabet.len() <= 1 { let value = BitVec::new_fill(true, count as u64); BinNode { value: RankSelect::new(value, 1), left: None, right: None, } } else { let mut value = BitVec::new_fill(false, count as u64); let mid = (alphabet.len() + 1) / 2; //Das Alphabet wird geteilt, die 2. Hälfte wird in alphabet2 gespeichert let (alphabet1, alphabet2) = alphabet.split_at(mid); //Die Sequenzen für den nächsten Schritt let mut sequence1 = Vec::new(); let mut sequence2 = Vec::new(); //Es werden alle Elemente der Sequenz durchegangen for x in 0..(sequence.len()) { //wenn sie in der 2. Hälfte des Alphabets sind wird ihr Eintrag in der Bitmap auf 1 gesetzt if alphabet2.contains(&sequence[x]) { value.set_bit(x as u64, true) } } //Group_by teilt in Gruppen key ist true wenn Zeichen in alphabet1, sonst false for (key, group) in &sequence .into_iter() .group_by(|elem| alphabet1.contains(&elem)) { //neue Sequencen werden anhand der Keys gebaut if key { sequence1.extend(group) } else { sequence2.extend(group) } } BinNode { value: RankSelect::new(value, 1), left: Some(Box::new(BinNode::create_node(alphabet1, sequence1))), right: Some(Box::new(BinNode::create_node(alphabet2, sequence2))), } } } fn access(&self, index: u64, min: usize, max: usize) -> Option<usize> { if min == max { return Some(min); } else { if self.value.get((index) as u64) { let next_index = self.value.rank((index) as u64).unwrap(); match &self.right { Some(x) => return (*x).access(next_index - 1, 1 + (min + max) / 2, max), None => return None, } } else { let next_index = self.value.rank_0((index) as u64).unwrap(); match &self.left { Some(x) => return (*x).access(next_index - 1, min, (min + max) / 2), None => return None, } } } } fn select(&self, index: u64, character: &usize, min: usize, max: usize) -> Option<(u64)> { //Blatt erreicht if min == max { return Some(index - 1); } // Position wird in Index umgerechnet, da Eingabe mit Position erfolgt else { if character <= &((max + min) / 2) { let result = match &self.left { Some(x) => (*x).select(index, character, min, (min + max) / 2), None => return None, }; let new_index = match result { Some(x) => x, None => return None, }; return self.value.select_0(new_index + 1); //+1 da Index in Position umgerechnet wird } else { let result = match &self.right { Some(x) => (*x).select(index, character, (min + max) / 2 + 1, max), None => return None, }; let new_index = match result { Some(x) => x, None => return None, }; return self.value.select_1(new_index + 1); //+1 da Index in Position umgerechnet wird } } } fn rank(&self, index: u64, character: &usize, min: usize, max: usize) -> Option<u64> { if min == max { return Some(index + 1); } //Wenn nicht im blatt else { if character <= &((max + min) / 2) { let next_index = self.value.rank_0((index) as u64).unwrap(); match &self.left { Some(x) => return (*x).rank(next_index - 1, character, min, (min + max) / 2), None => return None, } } else { let next_index = self.value.rank((index) as u64).unwrap(); match &self.right { Some(x) => { return (*x).rank(next_index - 1, character, ((min + max) / 2) + 1, max); } None => return None, } } } } fn len(&self) -> u64 { self.value.bits().len() } } ///Implements a non-consuming Iterator for the WaveletTree impl<'de, T> IntoIterator for &'de WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, {
Iterhelper { position: 0, tree: self, } } } impl<'de, T> Iterator for Iterhelper<'de, T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.position += 1; let len = match self.tree.len() { Ok(x) => x, Err(_) => return None, }; if self.position <= len as usize { match self.tree.access(self.position) { Ok(x) => return Some(x), Err(_) => return None, }; } else { None } } }
type Item = T; type IntoIter = Iterhelper<'de, T>; fn into_iter(self) -> Self::IntoIter {
random_line_split
wavelet_tree_pointer.rs
use bio::data_structures::rank_select::RankSelect; use bv::BitVec; use bv::BitsMut; use itertools::Itertools; use serde::{Deserialize, Serialize}; use snafu::{ensure, Snafu}; use std::fmt::Debug; use std::hash::Hash; use std::ops::Index; ///custom errors for the tree with pointer #[derive(Debug, Snafu)] pub enum Error { #[snafu(display( "Es gibt kein 0tes Element, das erste Element wird mit access(1) angesprochen" ))] Access0, #[snafu(display("Eingabe darf bei select nicht kleiner als 1 sein"))] SelectSmaller0, #[snafu(display("Fehler bei root unwrap in access"))] RootUnwrapError, #[snafu(display("Index ist größer als die Länge der Sequence"))] IndexOutOfBound, #[snafu(display("Element nicht gefunden"))] NoSuchElement, #[snafu(display("Element nicht im Alphabet, Fehler bei select"))] NotInAlphabet, #[snafu(display("Das Symbol kommt nicht oft genug im Wort vor"))] NotEnoughElements, #[snafu(display("PlatzhalterError"))] TempError, } ///representation of the WaveletTree #[derive(Serialize, Deserialize)] pub struct WaveletTree<T> { //The alphabet of the sequence the tree is build from alphabet: Vec<T>, //the first node that holds a bitmap over the entire sequence root: Option<Box<BinNode>>, } ///representation of the nodes in the tree, ///they are managed by the tree and the user has no direct access #[derive(Serialize, Deserialize)] struct BinNode { ///The bitmap stored in the node value: RankSelect, ///The left Child of the node left: Option<Box<BinNode>>, ///The right child of the node right: Option<Box<BinNode>>, } ///The Iterator for WaveletTrees pub struct Iterhelper<'de, T> { position: usize, tree: &'de WaveletTree<T>, } impl<'de, T> WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { /// creates a WaveletTree out of a given sequence /// * `sequence` - the sequence that is representet in the tree pub fn create<S: Clone + Iterator<Item = T>>(sequence: S) -> WaveletTree<T> { let mut sequence = sequence.peekable(); if sequence.peek().is_none() { panic!("Die übergebene Sequence ist leer!") }; let seqvec = sequence.clone().collect::<Vec<_>>(); let mut alphabet: Vec<T> = Vec::new(); alphabet.extend(sequence.unique()); alphabet.sort(); let alphslice = &alphabet[..]; WaveletTree { root: Some(Box::new(BinNode::create_node(alphslice, seqvec))), alphabet: alphabet, } } ///Returns the element at index, or an error if something goes wrong. ///To make the use of this funktion more intuitiv index starts at 1, so if you want the xth element you can call access(x) pub fn access(&self, index: usize) -> Result<T, Error> { ensure!(index > 0, Access0); // Abfangen von fehlerhafter Eingabe, Index ist größer als Sequenz let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; ensure!(z.len() >= index as u64, IndexOutOfBound); let z = match &self.root { Some(x) => x.access((index - 1) as u64, 0, self.alphabet.len() - 1), None => return Err(Error::RootUnwrapError), }; match z { Some(x) => Ok(self.alphabet[x]), None => return Err(Error::NoSuchElement), } } fn access_ref(&self, index: usize) -> &T { let result = match self.access(index) { Ok(x) => x, Err(_) => panic!("Index out of Bounds"), }; for i in 0..self.alphabet.len() { if self.alphabet[i] == result { return &self.alphabet[i]; } } panic!("Index in Bounds but not found"); } ///Returns the the position of the index'th occurence of the character pub fn select(&self, character: T, index: usize) -> Result<u64, Error> { // Abfangen von fehlerhafter Eingabe, Index darf hier nicht 0 sein ensure!(index > 0, SelectSmaller0); //------------------------ let character_index1 = &self.alphabet.binary_search(&character); // speichere an welchem index steht das gesuchte zeichen im alphabet steht let character_index = match character_index1 { Ok(x) => x, Err(_) => return Err(Error::NotInAlphabet), }; //Abfangen dass der Buchstabe nicht index oft vorkommt let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; if &self.rank(character, z.len() as usize).unwrap() < &(index as u64) { return Err(Error::NotEnoughElements); } let result = match &self.root { Some(x) => x.select(index as u64, character_index, 0, self.alphabet.len() - 1), None => return Err(Error::TempError), //Err("Fehler"), }; match result { Some(x) => return Ok(x + 1), None => return Err(Error::TempError), } } /// Returns the number of occurences of the character in the Intervall [1..index]. pub fn rank(&self, character: T, index: usize) -> Result<u64, Error> { if index < 1 { return Ok(0); } let index = index - 1; let z = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; // Abfangen von fehlerhafter Eingabe, Index ist größer als Sequenz ensure!(z.len() > index as u64, IndexOutOfBound); //--------------------------------- let character_index1 = &self.alphabet.binary_search(&character); // speichere an welchem index das gesuchte zeichen im alphabet steht let character_index = match character_index1 { Ok(x) => x, Err(_) => return Ok(0), //element nicht in alphabet => gib 0 zurück }; let result = match &self.root { Some(x) => (*x).rank(index as u64, character_index, 0, &self.alphabet.len() - 1), None => return Err(Error::NoSuchElement), }; match result { Some(x) => return Ok(x), None => return Err(Error::NoSuchElement), } } /// Returns a Vector that holds the sequence, this does not consume the tree pub fn rebuild(&'de self) -> Vec<T> { let mut result: Vec<T> = Vec::new(); for x in self.into_iter() { result.push(x); } result } ///Returns the length of the sequence or an error if the root is missing pub fn len(&self) -> Result<u64, Error> { let root = match &self.root { Some(x) => x, None => return Err(Error::RootUnwrapError), }; Ok(root.len()) } ///Returns the lenght of the alphabet pub fn alphabet_len(&self) -> usize { self.alphabet.len() } } ///Implements the Index Trait to allow access with [index], since it uses the access function index starts at 1 impl<'de, T> Index<usize> for WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Output = T; fn index(&self, index: usize) -> &Self::Output { &self.access_ref(index) } } impl BinNode { fn create_node<E: Hash + Clone + Ord + Debug>(alphabet: &[E], sequence: Vec<E>) -> BinNode { let count = sequence.len(); if alphabet.len() <= 1 { let value = BitVec::new_fill(true, count as u64); BinNode { value: RankSelect::new(value, 1), left: None, right: None, } } else { let mut value = BitVec::new_fill(false, count as u64); let mid = (alphabet.len() + 1) / 2; //Das Alphabet wird geteilt, die 2. Hälfte wird in alphabet2 gespeichert let (alphabet1, alphabet2) = alphabet.split_at(mid); //Die Sequenzen für den nächsten Schritt let mut sequence1 = Vec::new(); let mut sequence2 = Vec::new(); //Es werden alle Elemente der Sequenz durchegangen for x in 0..(sequence.len()) { //wenn sie in der 2. Hälfte des Alphabets sind wird ihr Eintrag in der Bitmap auf 1 gesetzt if alphabet2.contains(&sequence[x]) { value.set_bit(x as u64, true) } } //Group_by teilt in Gruppen key ist true wenn Zeichen in alphabet1, sonst false for (key, group) in &sequence .into_iter() .group_by(|elem| alphabet1.contains(&elem)) { //neue Sequencen werden anhand der Keys gebaut if key { sequence1.extend(group) } else { sequence2.extend(group) } } BinNode { value: RankSelect::new(value, 1), left: Some(Box::new(BinNode::create_node(alphabet1, sequence1))), right: Some(Box::new(BinNode::create_node(alphabet2, sequence2))), } } } fn access(&self, index: u64, min: usize, max: usize) -> Option<usize> { if min == max { return Some(min); } else { if self.value.get((index) as u64) { let next_index = self.value.rank((index) as u64).unwrap(); match &self.right { Some(x) => return (*x).access(next_index - 1, 1 + (min + max) / 2, max), None => return None, } } else { let next_index = self.value.rank_0((index) as u64).unwrap(); match &self.left { Some(x) => return (*x).access(next_index - 1, min, (min + max) / 2), None => return None, } } } } fn select(&self, index: u64, character: &usize, min: usize, max: usize) -> Option<(u64)> { //Blatt erreicht if min == max { return Some(index - 1); } // Position wird in Index umgerechnet, da Eingabe mit Position erfolgt else { if character <= &((max + min) / 2) { let result = match &self.left { Some(x) => (*x).select(index, character, min, (min + max) / 2), None => return None, }; let new_index = match result { Some(x) => x, None => return None, }; return self.value.select_0(new_index + 1); //+1 da Index in Position umgerechnet wird } else { let result = match &self.right { Some(x) => (*x).select(index, character, (min + max) / 2 + 1, max), None => return None, }; let new_index = match result { Some(x) => x, None => return None, }; return self.value.select_1(new_index + 1); //+1 da Index in Position umgerechnet wird } } } fn rank(&self, index: u64, character: &usize, min: usize, max: usize) -> Option<u64> { if min == max { return Some(index + 1); } //Wenn nicht im blatt else { if character <= &((max + min) / 2) { let next_index = self.value.rank_0((index) as u64).unwrap(); match &self.left { Some(x) => return (*x).rank(next_index - 1, character, min, (min + max) / 2), None => return None, } } else { let next_index = self.value.rank((index) as u64).unwrap(); match &self.right { Some(x) => { return (*x).rank(next_index - 1, character, ((min + max) / 2) + 1, max); } None => return None, } } } } fn len(&self) -> u64 { self.value.bits().len() } } ///Implements a non-consuming Iterator for the WaveletTree impl<'de, T> IntoIterator for &'de WaveletTree<T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Item = T; type IntoIter = Iterhelper<'de, T>; fn into_iter(self) -> Self::IntoIter { Iterhelper { position: 0, tree: self, } } } impl<'de, T> Iterator for Iterhelper<'de, T> where T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>, { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.position += 1; let len = match self.tree.len() { Ok(x) => x, Err(_) => return None, }; if self.position <= len as usize { match self.tree.access(self.position) { Ok(x) => return Some(x), Err(_) => return None, }; } else {
None } } }
conditional_block
mod.rs
// Import the rendering contract use crate::traits::RendererBase; use crate::traits::UIElement; use crate::traits::UIEvent; // We make use of the arguments of the event loop use piston::input::{UpdateArgs, RenderArgs, Key}; // Used to send events to the application use std::sync::mpsc; // Use the GlGraphics backend use opengl_graphics::GlGraphics; use graphics::character::CharacterCache; // Import drawing helper functions use graphics::{Context, rectangle, text, line, Transformed}; // Font imports use opengl_graphics::GlyphCache; use opengl_graphics::TextureSettings; // Needed to satisfy the trait use crate::audio::AnalyzedAudio; // Import UI elements mod dropdown; use dropdown::UIDropdown; mod util; use util::{cursor_in_rect, format_number, find_font}; // Needed for the timeout use std::time; // Needed to resolve the asset path use std::env::current_dir; use std::path::Path; // Necessary to retrieve a list of available input devices. use crate::audio::util::{fetch_devices, AudioDevice}; static AUDIO_IO_ID: usize = 1; static RENDERER_ID: usize = 2; pub struct UI<'a> { width: u32, height: u32, last_cursor_x: f64, last_cursor_y: f64, cursor_over_window: bool, should_display_ui: bool, menu_display_time: u64, // in seconds mouse_last_moved: time::Instant, ui_opacity: f64, target_opacity: f64, ui_font: graphics::glyph_cache::rusttype::GlyphCache<'a, (), opengl_graphics::Texture>, // Displayable settings available_devices: Vec<AudioDevice>, available_renderers: Vec<String>, ui_elements: Vec<Box<dyn UIElement>>, selected_device: usize, selected_renderer: usize, event_sender: Option<mpsc::Sender<UIEvent>>, device_info: String, base_font_size: f64, font_path: String, input_selector_button_rect: [f64; 4], renderer_selector_button_rect: [f64; 4], input_selector_index: i32, renderer_selector_index: i32, min_amp: f32, max_amp: f32 } impl UI<'static> { pub fn create () -> Self { let font_path = find_font(); if let Err(e) = font_path { use std::io::Write; let mut file = std::fs::File::create("/Users/hendrik/Desktop/log.txt").unwrap(); file.write_all(b"Could not find the font path!").unwrap(); } let glyph_cache = GlyphCache::new(find_font().unwrap(), (), TextureSettings::new()).unwrap(); Self { // General window parameters width: 0, height: 0, last_cursor_x: 0.0, last_cursor_y: 0.0, cursor_over_window: false, mouse_last_moved: time::Instant::now(), // General UI parameters should_display_ui: false, // If true, will increase the ui_opacity to the target ui_opacity: 0.0, // Will increase as long as display var is true, else decrease target_opacity: 0.7, // The final opacity of the UI when fully shown menu_display_time: 2, ui_font: glyph_cache, // Information available_devices: fetch_devices(), available_renderers: Vec::new(), selected_device: 0, selected_renderer: 0, event_sender: None, device_info: String::from("No device selected"), font_path: find_font().unwrap(), ui_elements: Vec::new(), base_font_size: 12.0, input_selector_button_rect: [0.0, 0.0, 0.0, 0.0], renderer_selector_button_rect: [0.0, 0.0, 0.0, 0.0], input_selector_index: -1, renderer_selector_index: -1, min_amp: 0.0, max_amp: 0.0 } } // Helper and utility functions pub fn selected_audio_device_changed (&mut self, idx: usize) { self.selected_device = idx; } pub fn selected_renderer_changed (&mut self, idx: usize) { self.selected_renderer = idx; } pub fn register_action_callback (&mut self, tx: mpsc::Sender<UIEvent>) { self.event_sender = Some(tx); } pub fn set_available_renderers (&mut self, rend: Vec<String>) { self.available_renderers = rend; } /// Draw a text button and return the actual rectangle where it has been drawn fn draw_text_button (&mut self, begin_point: [f64; 2], text: String, gl: &mut GlGraphics, context: Context) -> [f64; 4] { // Draws a text button with the UIs style let padding = 5.0; let real_width = self.ui_font.width(self.base_font_size as u32, text.as_str()).unwrap() + 2.0 * padding; let real_height = self.base_font_size + 2.0 * padding; let rect = [ begin_point[0], begin_point[1], begin_point[0] + real_width, begin_point[1] + real_height ]; // Hover effect // if cursor_in_rect([self.last_cursor_x, self.last_cursor_y], self.input_selector_button_rect) { let line_color = [0.9, 0.9, 0.9, self.ui_opacity as f32]; // Four lines surrounding the button line(line_color, 0.5, [rect[0], rect[1], rect[2], rect[1]], context.transform, gl); line(line_color, 0.5, [rect[2], rect[1], rect[2], rect[3]], context.transform, gl); line(line_color, 0.5, [rect[2], rect[3], rect[0], rect[3]], context.transform, gl); line(line_color, 0.5, [rect[0], rect[3], rect[0], rect[1]], context.transform, gl); // } // Now the text within it let fg_color = [1.0, 1.0, 1.0, self.ui_opacity as f32]; text::Text::new_color(fg_color, self.base_font_size as u32).draw( text.as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(begin_point[0] + padding, begin_point[1] + padding + self.base_font_size), gl ).unwrap(); // Finally return the actual rectangle [ begin_point[0], begin_point[1], real_width, real_height ] } } impl RendererBase for UI<'static> { fn render (&mut self, gl: &mut GlGraphics, context: Context, args: &RenderArgs, audio: &AnalyzedAudio) { if self.ui_opacity == 0.0 { return // If the opacity is zero, we don't need to waste resources } // Window size self.width = args.draw_size[0]; self.height = args.draw_size[1]; // Overlay size (width is always full) let overlay_top = self.height as f64 * 0.8; let overlay_height = self.height as f64 * 0.2; // Font size relative to UI overlay (always three lines high) self.base_font_size = (overlay_height / 3.0 * 0.95).floor(); if self.base_font_size > 14.0 { self.base_font_size = 14.0; // Don't overdo it } // Colors let bg_color = [0.0, 0.0, 0.0, self.ui_opacity as f32]; // Overlay area let overlay_rect = [ 0.0, overlay_top, self.width as f64, overlay_height ]; // Draw the overlay rectangle(bg_color, overlay_rect, context.transform, gl); let mut selected_device = String::from("No device selected"); // Check if we have a device selected if!self.available_devices.is_empty() && self.selected_device < self.available_devices.len() { selected_device = self.available_devices[self.selected_device].name.clone(); } self.device_info = format!("IN: {}", selected_device); // Draw the input selection button self.input_selector_button_rect = self.draw_text_button([10.0, overlay_rect[1] + 10.0], self.device_info.clone(), gl, context); //... and the renderer self.renderer_selector_button_rect = self.draw_text_button( [10.0 + self.input_selector_button_rect[2] + 20.0, overlay_rect[1] + 10.0], format!("Renderer: {}", self.available_renderers[self.selected_renderer].clone()), gl, context); let fg_color = [1.0, 1.0, 1.0, self.ui_opacity as f32]; // Draw a small spectrogram to indicate whether audio is actually being received let amp_bar_height = self.renderer_selector_button_rect[3] as f32; let start_x = self.renderer_selector_button_rect[0] + self.renderer_selector_button_rect[2] + 10.0; let start_y = self.renderer_selector_button_rect[1] + self.renderer_selector_button_rect[3]; let w = 50.0 / audio.amplitude[0].len() as f64; for (i, sample) in audio.amplitude[0].iter().enumerate() { let h = (sample.abs() * amp_bar_height) as f64; rectangle(fg_color, [start_x + i as f64 * w, start_y - h, w, h], context.transform, gl); } // Now provide audio information in the next lines let padding = 5.0; // Sample rate text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!("Sample rate: {} Hz", format_number(audio.sample_rate as f64)).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 2.0 + 3.0 * padding), gl ).unwrap(); // Buffer size text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!("Buffer size: {} samples", format_number(audio.buffer_size as f64)).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 3.0 + 4.0 * padding), gl ).unwrap(); let mut max_frequency = 0.0; for sample in audio.frequency[0].clone() { if sample > max_frequency { max_frequency = sample; } if sample < self.min_amp
if sample > self.max_amp { self.max_amp = sample } } // Min/max frequency // Buffer size text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!( "Analyzed frequencies: {} Hz to {} Hz (channels: {})", format_number(audio.bin_frequency.round() as f64), format_number((audio.bin_frequency * audio.frequency[0].len() as f32).round() as f64), audio.channels ).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 4.0 + 5.0 * padding), gl ).unwrap(); let mut items = Vec::new(); for device in self.available_devices.iter() { items.push(device.name.clone()); } // Now display all UI elements for elem in self.ui_elements.iter_mut() { elem.render(gl, context, args); } } fn update (&mut self, _args: &UpdateArgs) { let now = time::Instant::now(); if now.duration_since(self.mouse_last_moved) > time::Duration::new(self.menu_display_time, 0) { self.should_display_ui = false; } // Adapt the animation if!self.should_display_ui && self.ui_opacity > 0.0 { self.ui_opacity -= 0.1; } else if self.should_display_ui && self.ui_opacity < self.target_opacity { self.ui_opacity += 0.1; } } fn on_cursor_movement (&mut self, x: f64, y: f64) { self.last_cursor_x = x; self.last_cursor_y = y; self.mouse_last_moved = time::Instant::now(); self.should_display_ui = true; // Now propagate to all UI elements for elem in self.ui_elements.iter_mut() { elem.on_cursor_movement(x, y); } } fn on_cursor_state (&mut self, is_over_window: bool) { self.cursor_over_window = is_over_window; if!is_over_window { self.should_display_ui = false; } } fn on_click (&mut self) { // Check for generated events on the UI Elements // Now propagate to all UI elements for elem in self.ui_elements.iter_mut() { if let Some(event) = elem.on_click() { if let UIEvent::Selection(idx, id) = event { // Send event to application if self.event_sender.is_some() && id == AUDIO_IO_ID { self.event_sender.as_ref().unwrap().send(UIEvent::RequestChangeAudioDevice(idx)).unwrap(); } else if self.event_sender.is_some() && id == RENDERER_ID { // let event = match idx { // 1 => { // RendererType::Circle // }, // 2 => { // RendererType::Tree // }, // _ => { RendererType::Square } // Everything 0 and non-covered // }; self.event_sender.as_ref().unwrap().send(UIEvent::RequestChangeRenderer(idx)).unwrap(); } } } } // Display the dropdown if the cursor is currently in the input device selector button rect if cursor_in_rect( [self.last_cursor_x, self.last_cursor_y], self.input_selector_button_rect ) && self.input_selector_index < 0 { let mut items = Vec::new(); for device in self.available_devices.iter() { items.push((device.index, device.name.clone())); } self.ui_elements.push( Box::new( UIDropdown::create( AUDIO_IO_ID, items, true, [self.input_selector_button_rect[0], self.input_selector_button_rect[1]], self.input_selector_button_rect[2], self.base_font_size, self.font_path.clone() ) ) ); // Save the index for later self.input_selector_index = self.ui_elements.len() as i32 - 1; } else if self.input_selector_index > -1 &&!self.ui_elements.is_empty() { // Remove that thing again self.ui_elements.remove(self.input_selector_index as usize); self.input_selector_index = -1; } if cursor_in_rect([self.last_cursor_x, self.last_cursor_y], self.renderer_selector_button_rect) && self.renderer_selector_index < 0 { let mut items = Vec::new(); for (i, renderer) in self.available_renderers.iter().enumerate() { items.push((i, renderer.clone())); } self.ui_elements.push( Box::new( UIDropdown::create( RENDERER_ID, items, true, [self.renderer_selector_button_rect[0], self.renderer_selector_button_rect[1]], self.renderer_selector_button_rect[2], self.base_font_size, self.font_path.clone() ) ) ); // Save the index for later self.input_selector_index = self.ui_elements.len() as i32 - 1; } else if self.renderer_selector_index > -1 &&!self.ui_elements.is_empty() { self.ui_elements.remove(self.renderer_selector_index as usize); self.renderer_selector_index = -1; } } fn on_keypress (&mut self, _key: Key) { //... } }
{ self.min_amp = sample }
conditional_block
mod.rs
// Import the rendering contract use crate::traits::RendererBase; use crate::traits::UIElement; use crate::traits::UIEvent; // We make use of the arguments of the event loop use piston::input::{UpdateArgs, RenderArgs, Key}; // Used to send events to the application use std::sync::mpsc; // Use the GlGraphics backend use opengl_graphics::GlGraphics; use graphics::character::CharacterCache; // Import drawing helper functions use graphics::{Context, rectangle, text, line, Transformed}; // Font imports use opengl_graphics::GlyphCache; use opengl_graphics::TextureSettings; // Needed to satisfy the trait use crate::audio::AnalyzedAudio; // Import UI elements mod dropdown; use dropdown::UIDropdown; mod util; use util::{cursor_in_rect, format_number, find_font}; // Needed for the timeout use std::time; // Needed to resolve the asset path use std::env::current_dir; use std::path::Path; // Necessary to retrieve a list of available input devices. use crate::audio::util::{fetch_devices, AudioDevice}; static AUDIO_IO_ID: usize = 1; static RENDERER_ID: usize = 2; pub struct UI<'a> { width: u32, height: u32, last_cursor_x: f64, last_cursor_y: f64, cursor_over_window: bool, should_display_ui: bool, menu_display_time: u64, // in seconds mouse_last_moved: time::Instant, ui_opacity: f64, target_opacity: f64, ui_font: graphics::glyph_cache::rusttype::GlyphCache<'a, (), opengl_graphics::Texture>, // Displayable settings available_devices: Vec<AudioDevice>, available_renderers: Vec<String>, ui_elements: Vec<Box<dyn UIElement>>, selected_device: usize, selected_renderer: usize, event_sender: Option<mpsc::Sender<UIEvent>>, device_info: String, base_font_size: f64, font_path: String, input_selector_button_rect: [f64; 4], renderer_selector_button_rect: [f64; 4], input_selector_index: i32, renderer_selector_index: i32, min_amp: f32, max_amp: f32 } impl UI<'static> { pub fn create () -> Self { let font_path = find_font(); if let Err(e) = font_path { use std::io::Write; let mut file = std::fs::File::create("/Users/hendrik/Desktop/log.txt").unwrap(); file.write_all(b"Could not find the font path!").unwrap(); } let glyph_cache = GlyphCache::new(find_font().unwrap(), (), TextureSettings::new()).unwrap(); Self { // General window parameters width: 0, height: 0, last_cursor_x: 0.0, last_cursor_y: 0.0, cursor_over_window: false, mouse_last_moved: time::Instant::now(), // General UI parameters should_display_ui: false, // If true, will increase the ui_opacity to the target ui_opacity: 0.0, // Will increase as long as display var is true, else decrease target_opacity: 0.7, // The final opacity of the UI when fully shown menu_display_time: 2, ui_font: glyph_cache, // Information available_devices: fetch_devices(), available_renderers: Vec::new(), selected_device: 0, selected_renderer: 0, event_sender: None, device_info: String::from("No device selected"), font_path: find_font().unwrap(), ui_elements: Vec::new(), base_font_size: 12.0, input_selector_button_rect: [0.0, 0.0, 0.0, 0.0], renderer_selector_button_rect: [0.0, 0.0, 0.0, 0.0], input_selector_index: -1, renderer_selector_index: -1, min_amp: 0.0, max_amp: 0.0 } } // Helper and utility functions pub fn selected_audio_device_changed (&mut self, idx: usize) { self.selected_device = idx; } pub fn selected_renderer_changed (&mut self, idx: usize) { self.selected_renderer = idx; } pub fn register_action_callback (&mut self, tx: mpsc::Sender<UIEvent>) { self.event_sender = Some(tx); } pub fn set_available_renderers (&mut self, rend: Vec<String>) { self.available_renderers = rend; } /// Draw a text button and return the actual rectangle where it has been drawn fn draw_text_button (&mut self, begin_point: [f64; 2], text: String, gl: &mut GlGraphics, context: Context) -> [f64; 4] { // Draws a text button with the UIs style let padding = 5.0; let real_width = self.ui_font.width(self.base_font_size as u32, text.as_str()).unwrap() + 2.0 * padding; let real_height = self.base_font_size + 2.0 * padding; let rect = [ begin_point[0], begin_point[1], begin_point[0] + real_width, begin_point[1] + real_height ]; // Hover effect // if cursor_in_rect([self.last_cursor_x, self.last_cursor_y], self.input_selector_button_rect) { let line_color = [0.9, 0.9, 0.9, self.ui_opacity as f32]; // Four lines surrounding the button line(line_color, 0.5, [rect[0], rect[1], rect[2], rect[1]], context.transform, gl); line(line_color, 0.5, [rect[2], rect[1], rect[2], rect[3]], context.transform, gl); line(line_color, 0.5, [rect[2], rect[3], rect[0], rect[3]], context.transform, gl); line(line_color, 0.5, [rect[0], rect[3], rect[0], rect[1]], context.transform, gl); // } // Now the text within it let fg_color = [1.0, 1.0, 1.0, self.ui_opacity as f32]; text::Text::new_color(fg_color, self.base_font_size as u32).draw( text.as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(begin_point[0] + padding, begin_point[1] + padding + self.base_font_size), gl ).unwrap(); // Finally return the actual rectangle [ begin_point[0], begin_point[1], real_width, real_height ] } } impl RendererBase for UI<'static> { fn render (&mut self, gl: &mut GlGraphics, context: Context, args: &RenderArgs, audio: &AnalyzedAudio) { if self.ui_opacity == 0.0 { return // If the opacity is zero, we don't need to waste resources } // Window size self.width = args.draw_size[0]; self.height = args.draw_size[1]; // Overlay size (width is always full) let overlay_top = self.height as f64 * 0.8; let overlay_height = self.height as f64 * 0.2; // Font size relative to UI overlay (always three lines high) self.base_font_size = (overlay_height / 3.0 * 0.95).floor(); if self.base_font_size > 14.0 { self.base_font_size = 14.0; // Don't overdo it } // Colors let bg_color = [0.0, 0.0, 0.0, self.ui_opacity as f32]; // Overlay area let overlay_rect = [ 0.0, overlay_top, self.width as f64, overlay_height ]; // Draw the overlay rectangle(bg_color, overlay_rect, context.transform, gl); let mut selected_device = String::from("No device selected"); // Check if we have a device selected if!self.available_devices.is_empty() && self.selected_device < self.available_devices.len() { selected_device = self.available_devices[self.selected_device].name.clone(); } self.device_info = format!("IN: {}", selected_device); // Draw the input selection button self.input_selector_button_rect = self.draw_text_button([10.0, overlay_rect[1] + 10.0], self.device_info.clone(), gl, context); //... and the renderer self.renderer_selector_button_rect = self.draw_text_button( [10.0 + self.input_selector_button_rect[2] + 20.0, overlay_rect[1] + 10.0], format!("Renderer: {}", self.available_renderers[self.selected_renderer].clone()), gl, context); let fg_color = [1.0, 1.0, 1.0, self.ui_opacity as f32]; // Draw a small spectrogram to indicate whether audio is actually being received let amp_bar_height = self.renderer_selector_button_rect[3] as f32; let start_x = self.renderer_selector_button_rect[0] + self.renderer_selector_button_rect[2] + 10.0; let start_y = self.renderer_selector_button_rect[1] + self.renderer_selector_button_rect[3]; let w = 50.0 / audio.amplitude[0].len() as f64; for (i, sample) in audio.amplitude[0].iter().enumerate() { let h = (sample.abs() * amp_bar_height) as f64; rectangle(fg_color, [start_x + i as f64 * w, start_y - h, w, h], context.transform, gl); } // Now provide audio information in the next lines let padding = 5.0; // Sample rate text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!("Sample rate: {} Hz", format_number(audio.sample_rate as f64)).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 2.0 + 3.0 * padding), gl ).unwrap(); // Buffer size text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!("Buffer size: {} samples", format_number(audio.buffer_size as f64)).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 3.0 + 4.0 * padding), gl ).unwrap(); let mut max_frequency = 0.0; for sample in audio.frequency[0].clone() { if sample > max_frequency { max_frequency = sample; } if sample < self.min_amp { self.min_amp = sample } if sample > self.max_amp { self.max_amp = sample } } // Min/max frequency // Buffer size text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!( "Analyzed frequencies: {} Hz to {} Hz (channels: {})", format_number(audio.bin_frequency.round() as f64), format_number((audio.bin_frequency * audio.frequency[0].len() as f32).round() as f64), audio.channels ).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 4.0 + 5.0 * padding), gl ).unwrap(); let mut items = Vec::new(); for device in self.available_devices.iter() { items.push(device.name.clone()); } // Now display all UI elements for elem in self.ui_elements.iter_mut() { elem.render(gl, context, args); } } fn update (&mut self, _args: &UpdateArgs) { let now = time::Instant::now(); if now.duration_since(self.mouse_last_moved) > time::Duration::new(self.menu_display_time, 0) { self.should_display_ui = false; } // Adapt the animation if!self.should_display_ui && self.ui_opacity > 0.0 { self.ui_opacity -= 0.1; } else if self.should_display_ui && self.ui_opacity < self.target_opacity { self.ui_opacity += 0.1; } } fn on_cursor_movement (&mut self, x: f64, y: f64) { self.last_cursor_x = x; self.last_cursor_y = y; self.mouse_last_moved = time::Instant::now(); self.should_display_ui = true; // Now propagate to all UI elements for elem in self.ui_elements.iter_mut() { elem.on_cursor_movement(x, y); } } fn on_cursor_state (&mut self, is_over_window: bool) { self.cursor_over_window = is_over_window; if!is_over_window { self.should_display_ui = false; } } fn on_click (&mut self) { // Check for generated events on the UI Elements // Now propagate to all UI elements for elem in self.ui_elements.iter_mut() { if let Some(event) = elem.on_click() { if let UIEvent::Selection(idx, id) = event { // Send event to application if self.event_sender.is_some() && id == AUDIO_IO_ID { self.event_sender.as_ref().unwrap().send(UIEvent::RequestChangeAudioDevice(idx)).unwrap(); } else if self.event_sender.is_some() && id == RENDERER_ID { // let event = match idx { // 1 => { // RendererType::Circle // }, // 2 => { // RendererType::Tree // }, // _ => { RendererType::Square } // Everything 0 and non-covered // }; self.event_sender.as_ref().unwrap().send(UIEvent::RequestChangeRenderer(idx)).unwrap(); } } } } // Display the dropdown if the cursor is currently in the input device selector button rect if cursor_in_rect( [self.last_cursor_x, self.last_cursor_y], self.input_selector_button_rect ) && self.input_selector_index < 0 { let mut items = Vec::new(); for device in self.available_devices.iter() { items.push((device.index, device.name.clone())); } self.ui_elements.push( Box::new( UIDropdown::create( AUDIO_IO_ID, items, true, [self.input_selector_button_rect[0], self.input_selector_button_rect[1]], self.input_selector_button_rect[2], self.base_font_size, self.font_path.clone() ) ) ); // Save the index for later self.input_selector_index = self.ui_elements.len() as i32 - 1; } else if self.input_selector_index > -1 &&!self.ui_elements.is_empty() { // Remove that thing again self.ui_elements.remove(self.input_selector_index as usize); self.input_selector_index = -1; } if cursor_in_rect([self.last_cursor_x, self.last_cursor_y], self.renderer_selector_button_rect) && self.renderer_selector_index < 0 { let mut items = Vec::new(); for (i, renderer) in self.available_renderers.iter().enumerate() { items.push((i, renderer.clone())); } self.ui_elements.push( Box::new( UIDropdown::create( RENDERER_ID, items, true, [self.renderer_selector_button_rect[0], self.renderer_selector_button_rect[1]], self.renderer_selector_button_rect[2], self.base_font_size, self.font_path.clone() ) ) ); // Save the index for later self.input_selector_index = self.ui_elements.len() as i32 - 1; } else if self.renderer_selector_index > -1 &&!self.ui_elements.is_empty() { self.ui_elements.remove(self.renderer_selector_index as usize); self.renderer_selector_index = -1; } } fn on_keypress (&mut self, _key: Key)
}
{ // ... }
identifier_body
mod.rs
// Import the rendering contract use crate::traits::RendererBase; use crate::traits::UIElement; use crate::traits::UIEvent; // We make use of the arguments of the event loop use piston::input::{UpdateArgs, RenderArgs, Key}; // Used to send events to the application use std::sync::mpsc; // Use the GlGraphics backend use opengl_graphics::GlGraphics; use graphics::character::CharacterCache; // Import drawing helper functions use graphics::{Context, rectangle, text, line, Transformed}; // Font imports use opengl_graphics::GlyphCache; use opengl_graphics::TextureSettings; // Needed to satisfy the trait use crate::audio::AnalyzedAudio; // Import UI elements mod dropdown; use dropdown::UIDropdown; mod util; use util::{cursor_in_rect, format_number, find_font}; // Needed for the timeout use std::time; // Needed to resolve the asset path use std::env::current_dir; use std::path::Path; // Necessary to retrieve a list of available input devices. use crate::audio::util::{fetch_devices, AudioDevice}; static AUDIO_IO_ID: usize = 1; static RENDERER_ID: usize = 2; pub struct UI<'a> { width: u32, height: u32, last_cursor_x: f64, last_cursor_y: f64, cursor_over_window: bool, should_display_ui: bool, menu_display_time: u64, // in seconds mouse_last_moved: time::Instant, ui_opacity: f64, target_opacity: f64, ui_font: graphics::glyph_cache::rusttype::GlyphCache<'a, (), opengl_graphics::Texture>, // Displayable settings available_devices: Vec<AudioDevice>, available_renderers: Vec<String>, ui_elements: Vec<Box<dyn UIElement>>, selected_device: usize, selected_renderer: usize, event_sender: Option<mpsc::Sender<UIEvent>>, device_info: String, base_font_size: f64, font_path: String, input_selector_button_rect: [f64; 4], renderer_selector_button_rect: [f64; 4], input_selector_index: i32, renderer_selector_index: i32, min_amp: f32, max_amp: f32 } impl UI<'static> { pub fn create () -> Self { let font_path = find_font(); if let Err(e) = font_path { use std::io::Write; let mut file = std::fs::File::create("/Users/hendrik/Desktop/log.txt").unwrap(); file.write_all(b"Could not find the font path!").unwrap(); } let glyph_cache = GlyphCache::new(find_font().unwrap(), (), TextureSettings::new()).unwrap(); Self { // General window parameters width: 0, height: 0, last_cursor_x: 0.0, last_cursor_y: 0.0, cursor_over_window: false, mouse_last_moved: time::Instant::now(), // General UI parameters should_display_ui: false, // If true, will increase the ui_opacity to the target ui_opacity: 0.0, // Will increase as long as display var is true, else decrease target_opacity: 0.7, // The final opacity of the UI when fully shown menu_display_time: 2, ui_font: glyph_cache, // Information available_devices: fetch_devices(), available_renderers: Vec::new(), selected_device: 0, selected_renderer: 0, event_sender: None, device_info: String::from("No device selected"), font_path: find_font().unwrap(), ui_elements: Vec::new(), base_font_size: 12.0, input_selector_button_rect: [0.0, 0.0, 0.0, 0.0], renderer_selector_button_rect: [0.0, 0.0, 0.0, 0.0], input_selector_index: -1, renderer_selector_index: -1, min_amp: 0.0, max_amp: 0.0 } } // Helper and utility functions pub fn selected_audio_device_changed (&mut self, idx: usize) { self.selected_device = idx; } pub fn selected_renderer_changed (&mut self, idx: usize) { self.selected_renderer = idx; } pub fn register_action_callback (&mut self, tx: mpsc::Sender<UIEvent>) { self.event_sender = Some(tx); } pub fn set_available_renderers (&mut self, rend: Vec<String>) { self.available_renderers = rend; } /// Draw a text button and return the actual rectangle where it has been drawn fn draw_text_button (&mut self, begin_point: [f64; 2], text: String, gl: &mut GlGraphics, context: Context) -> [f64; 4] { // Draws a text button with the UIs style let padding = 5.0; let real_width = self.ui_font.width(self.base_font_size as u32, text.as_str()).unwrap() + 2.0 * padding; let real_height = self.base_font_size + 2.0 * padding; let rect = [ begin_point[0], begin_point[1], begin_point[0] + real_width, begin_point[1] + real_height ]; // Hover effect // if cursor_in_rect([self.last_cursor_x, self.last_cursor_y], self.input_selector_button_rect) { let line_color = [0.9, 0.9, 0.9, self.ui_opacity as f32]; // Four lines surrounding the button line(line_color, 0.5, [rect[0], rect[1], rect[2], rect[1]], context.transform, gl); line(line_color, 0.5, [rect[2], rect[1], rect[2], rect[3]], context.transform, gl); line(line_color, 0.5, [rect[2], rect[3], rect[0], rect[3]], context.transform, gl); line(line_color, 0.5, [rect[0], rect[3], rect[0], rect[1]], context.transform, gl); // } // Now the text within it let fg_color = [1.0, 1.0, 1.0, self.ui_opacity as f32]; text::Text::new_color(fg_color, self.base_font_size as u32).draw( text.as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(begin_point[0] + padding, begin_point[1] + padding + self.base_font_size), gl ).unwrap(); // Finally return the actual rectangle [ begin_point[0], begin_point[1], real_width, real_height ] } } impl RendererBase for UI<'static> { fn render (&mut self, gl: &mut GlGraphics, context: Context, args: &RenderArgs, audio: &AnalyzedAudio) { if self.ui_opacity == 0.0 { return // If the opacity is zero, we don't need to waste resources } // Window size self.width = args.draw_size[0]; self.height = args.draw_size[1]; // Overlay size (width is always full)
// Font size relative to UI overlay (always three lines high) self.base_font_size = (overlay_height / 3.0 * 0.95).floor(); if self.base_font_size > 14.0 { self.base_font_size = 14.0; // Don't overdo it } // Colors let bg_color = [0.0, 0.0, 0.0, self.ui_opacity as f32]; // Overlay area let overlay_rect = [ 0.0, overlay_top, self.width as f64, overlay_height ]; // Draw the overlay rectangle(bg_color, overlay_rect, context.transform, gl); let mut selected_device = String::from("No device selected"); // Check if we have a device selected if!self.available_devices.is_empty() && self.selected_device < self.available_devices.len() { selected_device = self.available_devices[self.selected_device].name.clone(); } self.device_info = format!("IN: {}", selected_device); // Draw the input selection button self.input_selector_button_rect = self.draw_text_button([10.0, overlay_rect[1] + 10.0], self.device_info.clone(), gl, context); //... and the renderer self.renderer_selector_button_rect = self.draw_text_button( [10.0 + self.input_selector_button_rect[2] + 20.0, overlay_rect[1] + 10.0], format!("Renderer: {}", self.available_renderers[self.selected_renderer].clone()), gl, context); let fg_color = [1.0, 1.0, 1.0, self.ui_opacity as f32]; // Draw a small spectrogram to indicate whether audio is actually being received let amp_bar_height = self.renderer_selector_button_rect[3] as f32; let start_x = self.renderer_selector_button_rect[0] + self.renderer_selector_button_rect[2] + 10.0; let start_y = self.renderer_selector_button_rect[1] + self.renderer_selector_button_rect[3]; let w = 50.0 / audio.amplitude[0].len() as f64; for (i, sample) in audio.amplitude[0].iter().enumerate() { let h = (sample.abs() * amp_bar_height) as f64; rectangle(fg_color, [start_x + i as f64 * w, start_y - h, w, h], context.transform, gl); } // Now provide audio information in the next lines let padding = 5.0; // Sample rate text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!("Sample rate: {} Hz", format_number(audio.sample_rate as f64)).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 2.0 + 3.0 * padding), gl ).unwrap(); // Buffer size text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!("Buffer size: {} samples", format_number(audio.buffer_size as f64)).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 3.0 + 4.0 * padding), gl ).unwrap(); let mut max_frequency = 0.0; for sample in audio.frequency[0].clone() { if sample > max_frequency { max_frequency = sample; } if sample < self.min_amp { self.min_amp = sample } if sample > self.max_amp { self.max_amp = sample } } // Min/max frequency // Buffer size text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!( "Analyzed frequencies: {} Hz to {} Hz (channels: {})", format_number(audio.bin_frequency.round() as f64), format_number((audio.bin_frequency * audio.frequency[0].len() as f32).round() as f64), audio.channels ).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 4.0 + 5.0 * padding), gl ).unwrap(); let mut items = Vec::new(); for device in self.available_devices.iter() { items.push(device.name.clone()); } // Now display all UI elements for elem in self.ui_elements.iter_mut() { elem.render(gl, context, args); } } fn update (&mut self, _args: &UpdateArgs) { let now = time::Instant::now(); if now.duration_since(self.mouse_last_moved) > time::Duration::new(self.menu_display_time, 0) { self.should_display_ui = false; } // Adapt the animation if!self.should_display_ui && self.ui_opacity > 0.0 { self.ui_opacity -= 0.1; } else if self.should_display_ui && self.ui_opacity < self.target_opacity { self.ui_opacity += 0.1; } } fn on_cursor_movement (&mut self, x: f64, y: f64) { self.last_cursor_x = x; self.last_cursor_y = y; self.mouse_last_moved = time::Instant::now(); self.should_display_ui = true; // Now propagate to all UI elements for elem in self.ui_elements.iter_mut() { elem.on_cursor_movement(x, y); } } fn on_cursor_state (&mut self, is_over_window: bool) { self.cursor_over_window = is_over_window; if!is_over_window { self.should_display_ui = false; } } fn on_click (&mut self) { // Check for generated events on the UI Elements // Now propagate to all UI elements for elem in self.ui_elements.iter_mut() { if let Some(event) = elem.on_click() { if let UIEvent::Selection(idx, id) = event { // Send event to application if self.event_sender.is_some() && id == AUDIO_IO_ID { self.event_sender.as_ref().unwrap().send(UIEvent::RequestChangeAudioDevice(idx)).unwrap(); } else if self.event_sender.is_some() && id == RENDERER_ID { // let event = match idx { // 1 => { // RendererType::Circle // }, // 2 => { // RendererType::Tree // }, // _ => { RendererType::Square } // Everything 0 and non-covered // }; self.event_sender.as_ref().unwrap().send(UIEvent::RequestChangeRenderer(idx)).unwrap(); } } } } // Display the dropdown if the cursor is currently in the input device selector button rect if cursor_in_rect( [self.last_cursor_x, self.last_cursor_y], self.input_selector_button_rect ) && self.input_selector_index < 0 { let mut items = Vec::new(); for device in self.available_devices.iter() { items.push((device.index, device.name.clone())); } self.ui_elements.push( Box::new( UIDropdown::create( AUDIO_IO_ID, items, true, [self.input_selector_button_rect[0], self.input_selector_button_rect[1]], self.input_selector_button_rect[2], self.base_font_size, self.font_path.clone() ) ) ); // Save the index for later self.input_selector_index = self.ui_elements.len() as i32 - 1; } else if self.input_selector_index > -1 &&!self.ui_elements.is_empty() { // Remove that thing again self.ui_elements.remove(self.input_selector_index as usize); self.input_selector_index = -1; } if cursor_in_rect([self.last_cursor_x, self.last_cursor_y], self.renderer_selector_button_rect) && self.renderer_selector_index < 0 { let mut items = Vec::new(); for (i, renderer) in self.available_renderers.iter().enumerate() { items.push((i, renderer.clone())); } self.ui_elements.push( Box::new( UIDropdown::create( RENDERER_ID, items, true, [self.renderer_selector_button_rect[0], self.renderer_selector_button_rect[1]], self.renderer_selector_button_rect[2], self.base_font_size, self.font_path.clone() ) ) ); // Save the index for later self.input_selector_index = self.ui_elements.len() as i32 - 1; } else if self.renderer_selector_index > -1 &&!self.ui_elements.is_empty() { self.ui_elements.remove(self.renderer_selector_index as usize); self.renderer_selector_index = -1; } } fn on_keypress (&mut self, _key: Key) { //... } }
let overlay_top = self.height as f64 * 0.8; let overlay_height = self.height as f64 * 0.2;
random_line_split
mod.rs
// Import the rendering contract use crate::traits::RendererBase; use crate::traits::UIElement; use crate::traits::UIEvent; // We make use of the arguments of the event loop use piston::input::{UpdateArgs, RenderArgs, Key}; // Used to send events to the application use std::sync::mpsc; // Use the GlGraphics backend use opengl_graphics::GlGraphics; use graphics::character::CharacterCache; // Import drawing helper functions use graphics::{Context, rectangle, text, line, Transformed}; // Font imports use opengl_graphics::GlyphCache; use opengl_graphics::TextureSettings; // Needed to satisfy the trait use crate::audio::AnalyzedAudio; // Import UI elements mod dropdown; use dropdown::UIDropdown; mod util; use util::{cursor_in_rect, format_number, find_font}; // Needed for the timeout use std::time; // Needed to resolve the asset path use std::env::current_dir; use std::path::Path; // Necessary to retrieve a list of available input devices. use crate::audio::util::{fetch_devices, AudioDevice}; static AUDIO_IO_ID: usize = 1; static RENDERER_ID: usize = 2; pub struct UI<'a> { width: u32, height: u32, last_cursor_x: f64, last_cursor_y: f64, cursor_over_window: bool, should_display_ui: bool, menu_display_time: u64, // in seconds mouse_last_moved: time::Instant, ui_opacity: f64, target_opacity: f64, ui_font: graphics::glyph_cache::rusttype::GlyphCache<'a, (), opengl_graphics::Texture>, // Displayable settings available_devices: Vec<AudioDevice>, available_renderers: Vec<String>, ui_elements: Vec<Box<dyn UIElement>>, selected_device: usize, selected_renderer: usize, event_sender: Option<mpsc::Sender<UIEvent>>, device_info: String, base_font_size: f64, font_path: String, input_selector_button_rect: [f64; 4], renderer_selector_button_rect: [f64; 4], input_selector_index: i32, renderer_selector_index: i32, min_amp: f32, max_amp: f32 } impl UI<'static> { pub fn create () -> Self { let font_path = find_font(); if let Err(e) = font_path { use std::io::Write; let mut file = std::fs::File::create("/Users/hendrik/Desktop/log.txt").unwrap(); file.write_all(b"Could not find the font path!").unwrap(); } let glyph_cache = GlyphCache::new(find_font().unwrap(), (), TextureSettings::new()).unwrap(); Self { // General window parameters width: 0, height: 0, last_cursor_x: 0.0, last_cursor_y: 0.0, cursor_over_window: false, mouse_last_moved: time::Instant::now(), // General UI parameters should_display_ui: false, // If true, will increase the ui_opacity to the target ui_opacity: 0.0, // Will increase as long as display var is true, else decrease target_opacity: 0.7, // The final opacity of the UI when fully shown menu_display_time: 2, ui_font: glyph_cache, // Information available_devices: fetch_devices(), available_renderers: Vec::new(), selected_device: 0, selected_renderer: 0, event_sender: None, device_info: String::from("No device selected"), font_path: find_font().unwrap(), ui_elements: Vec::new(), base_font_size: 12.0, input_selector_button_rect: [0.0, 0.0, 0.0, 0.0], renderer_selector_button_rect: [0.0, 0.0, 0.0, 0.0], input_selector_index: -1, renderer_selector_index: -1, min_amp: 0.0, max_amp: 0.0 } } // Helper and utility functions pub fn selected_audio_device_changed (&mut self, idx: usize) { self.selected_device = idx; } pub fn selected_renderer_changed (&mut self, idx: usize) { self.selected_renderer = idx; } pub fn register_action_callback (&mut self, tx: mpsc::Sender<UIEvent>) { self.event_sender = Some(tx); } pub fn set_available_renderers (&mut self, rend: Vec<String>) { self.available_renderers = rend; } /// Draw a text button and return the actual rectangle where it has been drawn fn
(&mut self, begin_point: [f64; 2], text: String, gl: &mut GlGraphics, context: Context) -> [f64; 4] { // Draws a text button with the UIs style let padding = 5.0; let real_width = self.ui_font.width(self.base_font_size as u32, text.as_str()).unwrap() + 2.0 * padding; let real_height = self.base_font_size + 2.0 * padding; let rect = [ begin_point[0], begin_point[1], begin_point[0] + real_width, begin_point[1] + real_height ]; // Hover effect // if cursor_in_rect([self.last_cursor_x, self.last_cursor_y], self.input_selector_button_rect) { let line_color = [0.9, 0.9, 0.9, self.ui_opacity as f32]; // Four lines surrounding the button line(line_color, 0.5, [rect[0], rect[1], rect[2], rect[1]], context.transform, gl); line(line_color, 0.5, [rect[2], rect[1], rect[2], rect[3]], context.transform, gl); line(line_color, 0.5, [rect[2], rect[3], rect[0], rect[3]], context.transform, gl); line(line_color, 0.5, [rect[0], rect[3], rect[0], rect[1]], context.transform, gl); // } // Now the text within it let fg_color = [1.0, 1.0, 1.0, self.ui_opacity as f32]; text::Text::new_color(fg_color, self.base_font_size as u32).draw( text.as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(begin_point[0] + padding, begin_point[1] + padding + self.base_font_size), gl ).unwrap(); // Finally return the actual rectangle [ begin_point[0], begin_point[1], real_width, real_height ] } } impl RendererBase for UI<'static> { fn render (&mut self, gl: &mut GlGraphics, context: Context, args: &RenderArgs, audio: &AnalyzedAudio) { if self.ui_opacity == 0.0 { return // If the opacity is zero, we don't need to waste resources } // Window size self.width = args.draw_size[0]; self.height = args.draw_size[1]; // Overlay size (width is always full) let overlay_top = self.height as f64 * 0.8; let overlay_height = self.height as f64 * 0.2; // Font size relative to UI overlay (always three lines high) self.base_font_size = (overlay_height / 3.0 * 0.95).floor(); if self.base_font_size > 14.0 { self.base_font_size = 14.0; // Don't overdo it } // Colors let bg_color = [0.0, 0.0, 0.0, self.ui_opacity as f32]; // Overlay area let overlay_rect = [ 0.0, overlay_top, self.width as f64, overlay_height ]; // Draw the overlay rectangle(bg_color, overlay_rect, context.transform, gl); let mut selected_device = String::from("No device selected"); // Check if we have a device selected if!self.available_devices.is_empty() && self.selected_device < self.available_devices.len() { selected_device = self.available_devices[self.selected_device].name.clone(); } self.device_info = format!("IN: {}", selected_device); // Draw the input selection button self.input_selector_button_rect = self.draw_text_button([10.0, overlay_rect[1] + 10.0], self.device_info.clone(), gl, context); //... and the renderer self.renderer_selector_button_rect = self.draw_text_button( [10.0 + self.input_selector_button_rect[2] + 20.0, overlay_rect[1] + 10.0], format!("Renderer: {}", self.available_renderers[self.selected_renderer].clone()), gl, context); let fg_color = [1.0, 1.0, 1.0, self.ui_opacity as f32]; // Draw a small spectrogram to indicate whether audio is actually being received let amp_bar_height = self.renderer_selector_button_rect[3] as f32; let start_x = self.renderer_selector_button_rect[0] + self.renderer_selector_button_rect[2] + 10.0; let start_y = self.renderer_selector_button_rect[1] + self.renderer_selector_button_rect[3]; let w = 50.0 / audio.amplitude[0].len() as f64; for (i, sample) in audio.amplitude[0].iter().enumerate() { let h = (sample.abs() * amp_bar_height) as f64; rectangle(fg_color, [start_x + i as f64 * w, start_y - h, w, h], context.transform, gl); } // Now provide audio information in the next lines let padding = 5.0; // Sample rate text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!("Sample rate: {} Hz", format_number(audio.sample_rate as f64)).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 2.0 + 3.0 * padding), gl ).unwrap(); // Buffer size text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!("Buffer size: {} samples", format_number(audio.buffer_size as f64)).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 3.0 + 4.0 * padding), gl ).unwrap(); let mut max_frequency = 0.0; for sample in audio.frequency[0].clone() { if sample > max_frequency { max_frequency = sample; } if sample < self.min_amp { self.min_amp = sample } if sample > self.max_amp { self.max_amp = sample } } // Min/max frequency // Buffer size text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!( "Analyzed frequencies: {} Hz to {} Hz (channels: {})", format_number(audio.bin_frequency.round() as f64), format_number((audio.bin_frequency * audio.frequency[0].len() as f32).round() as f64), audio.channels ).as_str(), &mut self.ui_font, &context.draw_state, context.transform.trans(10.0 + padding, overlay_rect[1] + 10.0 + self.base_font_size * 4.0 + 5.0 * padding), gl ).unwrap(); let mut items = Vec::new(); for device in self.available_devices.iter() { items.push(device.name.clone()); } // Now display all UI elements for elem in self.ui_elements.iter_mut() { elem.render(gl, context, args); } } fn update (&mut self, _args: &UpdateArgs) { let now = time::Instant::now(); if now.duration_since(self.mouse_last_moved) > time::Duration::new(self.menu_display_time, 0) { self.should_display_ui = false; } // Adapt the animation if!self.should_display_ui && self.ui_opacity > 0.0 { self.ui_opacity -= 0.1; } else if self.should_display_ui && self.ui_opacity < self.target_opacity { self.ui_opacity += 0.1; } } fn on_cursor_movement (&mut self, x: f64, y: f64) { self.last_cursor_x = x; self.last_cursor_y = y; self.mouse_last_moved = time::Instant::now(); self.should_display_ui = true; // Now propagate to all UI elements for elem in self.ui_elements.iter_mut() { elem.on_cursor_movement(x, y); } } fn on_cursor_state (&mut self, is_over_window: bool) { self.cursor_over_window = is_over_window; if!is_over_window { self.should_display_ui = false; } } fn on_click (&mut self) { // Check for generated events on the UI Elements // Now propagate to all UI elements for elem in self.ui_elements.iter_mut() { if let Some(event) = elem.on_click() { if let UIEvent::Selection(idx, id) = event { // Send event to application if self.event_sender.is_some() && id == AUDIO_IO_ID { self.event_sender.as_ref().unwrap().send(UIEvent::RequestChangeAudioDevice(idx)).unwrap(); } else if self.event_sender.is_some() && id == RENDERER_ID { // let event = match idx { // 1 => { // RendererType::Circle // }, // 2 => { // RendererType::Tree // }, // _ => { RendererType::Square } // Everything 0 and non-covered // }; self.event_sender.as_ref().unwrap().send(UIEvent::RequestChangeRenderer(idx)).unwrap(); } } } } // Display the dropdown if the cursor is currently in the input device selector button rect if cursor_in_rect( [self.last_cursor_x, self.last_cursor_y], self.input_selector_button_rect ) && self.input_selector_index < 0 { let mut items = Vec::new(); for device in self.available_devices.iter() { items.push((device.index, device.name.clone())); } self.ui_elements.push( Box::new( UIDropdown::create( AUDIO_IO_ID, items, true, [self.input_selector_button_rect[0], self.input_selector_button_rect[1]], self.input_selector_button_rect[2], self.base_font_size, self.font_path.clone() ) ) ); // Save the index for later self.input_selector_index = self.ui_elements.len() as i32 - 1; } else if self.input_selector_index > -1 &&!self.ui_elements.is_empty() { // Remove that thing again self.ui_elements.remove(self.input_selector_index as usize); self.input_selector_index = -1; } if cursor_in_rect([self.last_cursor_x, self.last_cursor_y], self.renderer_selector_button_rect) && self.renderer_selector_index < 0 { let mut items = Vec::new(); for (i, renderer) in self.available_renderers.iter().enumerate() { items.push((i, renderer.clone())); } self.ui_elements.push( Box::new( UIDropdown::create( RENDERER_ID, items, true, [self.renderer_selector_button_rect[0], self.renderer_selector_button_rect[1]], self.renderer_selector_button_rect[2], self.base_font_size, self.font_path.clone() ) ) ); // Save the index for later self.input_selector_index = self.ui_elements.len() as i32 - 1; } else if self.renderer_selector_index > -1 &&!self.ui_elements.is_empty() { self.ui_elements.remove(self.renderer_selector_index as usize); self.renderer_selector_index = -1; } } fn on_keypress (&mut self, _key: Key) { //... } }
draw_text_button
identifier_name
mod.rs
#![allow(dead_code)] pub mod hypotheses; use std::collections::HashMap; use std::hash::Hash; use std::cmp::{Eq, Ordering}; use std::iter::FromIterator; use ansi_term::Style; use triangles::Study; use inference::triangle::hypotheses::BasicHypothesis; use inference::triangle::hypotheses::JoinedHypothesis; pub use inference::triangle::hypotheses::standard_basics::standard_basic_hypotheses; pub trait Hypothesis { fn predicts_the_property(&self, study: &Study) -> bool; fn description(&self) -> String; } #[derive(Debug)] pub struct Distribution<H: Hypothesis + Hash + Eq>(HashMap<H, f64>); impl<H: Hypothesis + Hash + Eq + Copy> Distribution<H> { pub fn new() -> Self { let backing = HashMap::<H, f64>::new(); Distribution(backing) } pub fn ignorance_prior(hypotheses: Vec<H>) -> Self { let mut backing = HashMap::<H, f64>::new(); let probability_each: f64 = 1.0/(hypotheses.len() as f64); for hypothesis in hypotheses.into_iter() { backing.insert(hypothesis, probability_each); } Distribution(backing) } fn backing(&self) -> &HashMap<H, f64> { &self.0 } fn mut_backing(&mut self) -> &mut HashMap<H, f64> { &mut self.0 } pub fn len(&self) -> usize { self.backing().len() } pub fn hypotheses(&self) -> Vec<&H> { self.backing().keys().collect::<Vec<_>>() } pub fn belief(&self, hypothesis: H) -> f64 { *self.backing().get(&hypothesis).unwrap_or(&0.0f64) } pub fn entropy(&self) -> f64 { self.backing().values().map(|p| -p * p.log2()).sum() } pub fn completely_certain(&self) -> Option<H> { if self.backing().len()!= 1 { None } else { Some(*self.backing().keys().nth(0).expect("should have one entry")) } } pub fn predict(&self, study: &Study, verdict: bool) -> f64 { self.backing().iter() .filter(|hp| { let h = hp.0; h.predicts_the_property(study) == verdict }) .map(|hp| { let p = hp.1; p }).sum() } pub fn updated(&self, study: &Study, verdict: bool) -> Self { let normalization_factor = 1.0/self.predict(study, verdict); let rebacking_pairs = self.backing() .into_iter().filter(|hp| { let h = hp.0; h.predicts_the_property(study) == verdict }).map(|hp| { let (h, p) = hp; (*h, normalization_factor * p) }); let rebacking = HashMap::from_iter(rebacking_pairs); Distribution(rebacking) } pub fn value_of_information(&self, study: &Study) -> f64 { let mut entropy = 0.; let mut probability_of_the_property = 0.; let mut probability_of_the_negation = 0.; for (&hypothesis, &probability) in self.backing().iter() { if hypothesis.predicts_the_property(study) { probability_of_the_property += probability; } else { probability_of_the_negation += probability; } entropy += -probability * probability.log2(); } let property_normalization_factor = 1./probability_of_the_property; let negation_normalization_factor = 1./probability_of_the_negation; let mut entropy_given_the_property = 0.; let mut entropy_given_the_negation = 0.; for (&hypothesis, &probability) in self.backing().iter() { if hypothesis.predicts_the_property(study) { let p = property_normalization_factor * probability; entropy_given_the_property += -p * p.log2(); } else { let p = negation_normalization_factor * probability; entropy_given_the_negation += -p * p.log2(); } } let expected_entropy = probability_of_the_property * entropy_given_the_property + probability_of_the_negation * entropy_given_the_negation; entropy - expected_entropy } pub fn burning_question(&self, desired_bits: f64, sample_cap: usize) -> Study { let mut study = Study::sample(); let mut value = self.value_of_information(&study); let mut top_study = study.clone(); let mut top_value = value; let mut samples = 1; loop { if value > top_value { top_value = value; top_study = study; } if (top_value > desired_bits) || (samples >= sample_cap) { break; } study = Study::sample(); value = self.value_of_information(&study); samples += 1; } top_study } pub fn inspect(&self, n: usize) { let mut backing = self.backing().iter().collect::<Vec<_>>(); backing.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_or(Ordering::Equal)); let total_probability_mass: f64 = backing.iter() .map(|hp| { hp.1 }).sum(); println!("Total probability mass: {:.6}", total_probability_mass); println!("Top {} hypotheses:", n); for &(&hypothesis, &probability) in backing.iter().take(n) { wrapln!(" * {}: {}", hypothesis.description(), Style::new().bold().paint(&format!("{:.4}", probability))); } } } pub fn complexity_prior(basic_hypotheses: Vec<BasicHypothesis>) -> Distribution<JoinedHypothesis> { let mut prebacking = HashMap::<JoinedHypothesis, f64>::new(); // just a guess; we'll have to normalize later to get a real probability let weight_each_basic = (2./3.)/(basic_hypotheses.len() as f64); let weight_each_joined = (1./3.)/(basic_hypotheses.len().pow(2) as f64); for &basic in &basic_hypotheses { prebacking.insert(JoinedHypothesis::full_stop(basic), weight_each_basic); } for (i, &one_basic) in basic_hypotheses.iter().enumerate() { for (j, &another_basic) in basic_hypotheses.iter().enumerate() { if j <= i { continue; } if one_basic.obviates(&another_basic) || another_basic.obviates(&one_basic) { continue; } let conjunction = JoinedHypothesis::and(one_basic, another_basic); let disjunction = JoinedHypothesis::or(one_basic, another_basic); for &junction in &vec![conjunction, disjunction] { if junction.check_substantiality(100) { prebacking.insert(junction, weight_each_joined); } } } } let total_mass: f64 = prebacking.iter().map(|hp| { hp.1 }).sum(); let normalization_factor = 1.0/total_mass; let backing_pairs = prebacking.into_iter() .map(|hp| { let (h, p) = hp; (h, normalization_factor * p) }); let backing = HashMap::from_iter(backing_pairs); Distribution(backing) } #[cfg(test)] mod tests { use test::Bencher; use super::*; use triangles::{Color, Size, Stack, Study, Triangle}; use inference::triangle::hypotheses::{BasicHypothesis, JoinedHypothesis}; use inference::triangle::hypotheses::color_count_boundedness::ColorCountBoundednessHypothesis; #[test] fn concerning_updating_your_bayesian_distribution() { // Suppose we think the hypotheses "A study has the property if it has // at least 1 triangle of color C" for C in {Red, Green, Blue, Yellow} // are all equally likely, and that we aren't considering any other // alternatives. let hypotheses = vec![Color::Red, Color::Green, Color::Blue, Color::Yellow].iter() .map(|&c| ColorCountBoundednessHypothesis::new_lower(c, 1)) .collect::<Vec<_>>(); let prior = Distribution::ignorance_prior(hypotheses); // If we learn that a study consisting of Red and Yellow triangles does // not have the property, then we think that C = Green or Blue are // equally likely. let beliefs = prior.updated( &study!(stack!(Triangle::new(Color::Red, Size::One), Triangle::new(Color::Yellow, Size::One))), false); let probability_c_is_blue = beliefs.belief( ColorCountBoundednessHypothesis::new_lower(Color::Blue, 1)); let probability_c_is_green = beliefs.belief( ColorCountBoundednessHypothesis::new_lower(Color::Green, 1)); assert_eq!(probability_c_is_blue, 0.5); assert_eq!(probability_c_is_green, 0.5); } #[ignore] // TODO investigate and repair test #[test] fn concerning_soundness_of_our_complexity_penalty() { // ⎲ ∞ // ⎳ i=1 1/2^i = 1 // // So... I want to give conjunctions and disjunctions a lower prior // probability, but I'm running into the same philosophical difficulty // that I ran into when I was first sketching out the number game, as // accounted in the README: if the true meaning of the complexity // penalty is that the hypothesis "A" gets to sum over the unspecified // details borne by the more complicated hypotheses "A ∧ B" and "A ∧ // C", then it's not clear how this insight translates to this setting, // where we want to represent our knowledge as a collection of mutually // exclusive hypotheses: we don't care about being able to refine a // true-but-vague theory to a true-but-more-precise theory; we want to // say that the precise theory is true and that all others are false. // // Probably the real answer is that this game just isn't very // philosophically interesting: we should have a complexity penalty to // exactly the extent that we think the human property-specifiers the // engine will face are going to choose disjunctions or disjunctions // less often than a uniform sample over distinct hypotheses would. let basics = vec![ BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower(Color::Blue, 1)), BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower(Color::Red, 1)) ]; let distribution = complexity_prior(basics); assert_eq!(1./3., distribution.belief(JoinedHypothesis::full_stop( BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Blue, 1))))); assert_eq!(1./12., distribution.belief(JoinedHypothesis::and( BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Blue, 1)), BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Red, 1))))); } #[bench] fn concerning_the_expense_of_updating(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.updated(&Study::sample(), true); }); } #[bench] fn concerning_the_expense_of_computing_entropy(bencher: &mut Bencher) {
nch] fn concerning_the_expense_of_prediction(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.predict(&Study::sample(), true); }); } #[bench] fn concerning_the_expense_of_the_value(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.value_of_information(&Study::sample()); }); } }
let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.entropy() }); } #[be
identifier_body
mod.rs
#![allow(dead_code)] pub mod hypotheses; use std::collections::HashMap; use std::hash::Hash; use std::cmp::{Eq, Ordering}; use std::iter::FromIterator; use ansi_term::Style; use triangles::Study; use inference::triangle::hypotheses::BasicHypothesis; use inference::triangle::hypotheses::JoinedHypothesis; pub use inference::triangle::hypotheses::standard_basics::standard_basic_hypotheses; pub trait Hypothesis { fn predicts_the_property(&self, study: &Study) -> bool; fn description(&self) -> String; } #[derive(Debug)] pub struct Distribution<H: Hypothesis + Hash + Eq>(HashMap<H, f64>); impl<H: Hypothesis + Hash + Eq + Copy> Distribution<H> { pub fn new() -> Self { let backing = HashMap::<H, f64>::new(); Distribution(backing) } pub fn ignorance_prior(hypotheses: Vec<H>) -> Self { let mut backing = HashMap::<H, f64>::new(); let probability_each: f64 = 1.0/(hypotheses.len() as f64); for hypothesis in hypotheses.into_iter() { backing.insert(hypothesis, probability_each); } Distribution(backing) } fn backing(&self) -> &HashMap<H, f64> { &self.0 } fn mut_backing(&mut self) -> &mut HashMap<H, f64> { &mut self.0 } pub fn len(&self) -> usize { self.backing().len() } pub fn hypotheses(&self) -> Vec<&H> { self.backing().keys().collect::<Vec<_>>() } pub fn belief(&self, hypothesis: H) -> f64 { *self.backing().get(&hypothesis).unwrap_or(&0.0f64) } pub fn entropy(&self) -> f64 { self.backing().values().map(|p| -p * p.log2()).sum() } pub fn completely_certain(&self) -> Option<H> { if self.backing().len()!= 1 { None } else { Some(*self.backing().keys().nth(0).expect("should have one entry")) } } pub fn predict(&self, study: &Study, verdict: bool) -> f64 { self.backing().iter() .filter(|hp| { let h = hp.0; h.predicts_the_property(study) == verdict }) .map(|hp| { let p = hp.1; p }).sum() } pub fn updated(&self, study: &Study, verdict: bool) -> Self { let normalization_factor = 1.0/self.predict(study, verdict); let rebacking_pairs = self.backing() .into_iter().filter(|hp| { let h = hp.0; h.predicts_the_property(study) == verdict }).map(|hp| { let (h, p) = hp; (*h, normalization_factor * p) }); let rebacking = HashMap::from_iter(rebacking_pairs); Distribution(rebacking) } pub fn value_of_information(&self, study: &Study) -> f64 { let mut entropy = 0.; let mut probability_of_the_property = 0.; let mut probability_of_the_negation = 0.; for (&hypothesis, &probability) in self.backing().iter() { if hypothesis.predicts_the_property(study) { probability_of_the_property += probability; } else { probability_of_the_negation += probability; } entropy += -probability * probability.log2(); } let property_normalization_factor = 1./probability_of_the_property; let negation_normalization_factor = 1./probability_of_the_negation; let mut entropy_given_the_property = 0.; let mut entropy_given_the_negation = 0.; for (&hypothesis, &probability) in self.backing().iter() { if hypothesis.predicts_the_property(study) { let p = property_normalization_factor * probability; entropy_given_the_property += -p * p.log2(); } else { let p = negation_normalization_factor * probability; entropy_given_the_negation += -p * p.log2(); } } let expected_entropy = probability_of_the_property * entropy_given_the_property + probability_of_the_negation * entropy_given_the_negation; entropy - expected_entropy } pub fn burning_question(&self, desired_bits: f64, sample_cap: usize) -> Study { let mut study = Study::sample(); let mut value = self.value_of_information(&study); let mut top_study = study.clone(); let mut top_value = value; let mut samples = 1; loop { if value > top_value { top_value = value; top_study = study; } if (top_value > desired_bits) || (samples >= sample_cap) { break; } study = Study::sample(); value = self.value_of_information(&study); samples += 1; } top_study } pub fn inspect(&self, n: usize) { let mut backing = self.backing().iter().collect::<Vec<_>>(); backing.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_or(Ordering::Equal)); let total_probability_mass: f64 = backing.iter() .map(|hp| { hp.1 }).sum(); println!("Total probability mass: {:.6}", total_probability_mass); println!("Top {} hypotheses:", n); for &(&hypothesis, &probability) in backing.iter().take(n) { wrapln!(" * {}: {}", hypothesis.description(), Style::new().bold().paint(&format!("{:.4}", probability))); } } } pub fn complexity_prior(basic_hypotheses: Vec<BasicHypothesis>) -> Distribution<JoinedHypothesis> { let mut prebacking = HashMap::<JoinedHypothesis, f64>::new(); // just a guess; we'll have to normalize later to get a real probability let weight_each_basic = (2./3.)/(basic_hypotheses.len() as f64); let weight_each_joined = (1./3.)/(basic_hypotheses.len().pow(2) as f64); for &basic in &basic_hypotheses { prebacking.insert(JoinedHypothesis::full_stop(basic), weight_each_basic); } for (i, &one_basic) in basic_hypotheses.iter().enumerate() { for (j, &another_basic) in basic_hypotheses.iter().enumerate() { if j <= i { continue; } if one_basic.obviates(&another_basic) || another_basic.obviates(&one_basic) { continue; } let conjunction = JoinedHypothesis::and(one_basic, another_basic); let disjunction = JoinedHypothesis::or(one_basic, another_basic); for &junction in &vec![conjunction, disjunction] { if junction.check_substantiality(100) { prebacking.insert(junction, weight_each_joined); } } } } let total_mass: f64 = prebacking.iter().map(|hp| { hp.1 }).sum(); let normalization_factor = 1.0/total_mass; let backing_pairs = prebacking.into_iter() .map(|hp| { let (h, p) = hp; (h, normalization_factor * p) }); let backing = HashMap::from_iter(backing_pairs); Distribution(backing) } #[cfg(test)] mod tests { use test::Bencher; use super::*; use triangles::{Color, Size, Stack, Study, Triangle}; use inference::triangle::hypotheses::{BasicHypothesis, JoinedHypothesis}; use inference::triangle::hypotheses::color_count_boundedness::ColorCountBoundednessHypothesis; #[test] fn concerning_updating_your_bayesian_distribution() { // Suppose we think the hypotheses "A study has the property if it has // at least 1 triangle of color C" for C in {Red, Green, Blue, Yellow} // are all equally likely, and that we aren't considering any other // alternatives. let hypotheses = vec![Color::Red, Color::Green, Color::Blue, Color::Yellow].iter() .map(|&c| ColorCountBoundednessHypothesis::new_lower(c, 1)) .collect::<Vec<_>>(); let prior = Distribution::ignorance_prior(hypotheses); // If we learn that a study consisting of Red and Yellow triangles does // not have the property, then we think that C = Green or Blue are // equally likely. let beliefs = prior.updated( &study!(stack!(Triangle::new(Color::Red, Size::One), Triangle::new(Color::Yellow, Size::One))), false); let probability_c_is_blue = beliefs.belief( ColorCountBoundednessHypothesis::new_lower(Color::Blue, 1)); let probability_c_is_green = beliefs.belief( ColorCountBoundednessHypothesis::new_lower(Color::Green, 1)); assert_eq!(probability_c_is_blue, 0.5); assert_eq!(probability_c_is_green, 0.5); } #[ignore] // TODO investigate and repair test #[test] fn concerning_soundness_of_our_complexity_penalty() { // ⎲ ∞
// that I ran into when I was first sketching out the number game, as // accounted in the README: if the true meaning of the complexity // penalty is that the hypothesis "A" gets to sum over the unspecified // details borne by the more complicated hypotheses "A ∧ B" and "A ∧ // C", then it's not clear how this insight translates to this setting, // where we want to represent our knowledge as a collection of mutually // exclusive hypotheses: we don't care about being able to refine a // true-but-vague theory to a true-but-more-precise theory; we want to // say that the precise theory is true and that all others are false. // // Probably the real answer is that this game just isn't very // philosophically interesting: we should have a complexity penalty to // exactly the extent that we think the human property-specifiers the // engine will face are going to choose disjunctions or disjunctions // less often than a uniform sample over distinct hypotheses would. let basics = vec![ BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower(Color::Blue, 1)), BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower(Color::Red, 1)) ]; let distribution = complexity_prior(basics); assert_eq!(1./3., distribution.belief(JoinedHypothesis::full_stop( BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Blue, 1))))); assert_eq!(1./12., distribution.belief(JoinedHypothesis::and( BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Blue, 1)), BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Red, 1))))); } #[bench] fn concerning_the_expense_of_updating(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.updated(&Study::sample(), true); }); } #[bench] fn concerning_the_expense_of_computing_entropy(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.entropy() }); } #[bench] fn concerning_the_expense_of_prediction(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.predict(&Study::sample(), true); }); } #[bench] fn concerning_the_expense_of_the_value(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.value_of_information(&Study::sample()); }); } }
// ⎳ i=1 1/2^i = 1 // // So ... I want to give conjunctions and disjunctions a lower prior // probability, but I'm running into the same philosophical difficulty
random_line_split
mod.rs
#![allow(dead_code)] pub mod hypotheses; use std::collections::HashMap; use std::hash::Hash; use std::cmp::{Eq, Ordering}; use std::iter::FromIterator; use ansi_term::Style; use triangles::Study; use inference::triangle::hypotheses::BasicHypothesis; use inference::triangle::hypotheses::JoinedHypothesis; pub use inference::triangle::hypotheses::standard_basics::standard_basic_hypotheses; pub trait Hypothesis { fn predicts_the_property(&self, study: &Study) -> bool; fn description(&self) -> String; } #[derive(Debug)] pub struct Distribution<H: Hypothesis + Hash + Eq>(HashMap<H, f64>); impl<H: Hypothesis + Hash + Eq + Copy> Distribution<H> { pub fn new() -> Self { let backing = HashMap::<H, f64>::new(); Distribution(backing) } pub fn ignorance_prior(hypotheses: Vec<H>) -> Self { let mut backing = HashMap::<H, f64>::new(); let probability_each: f64 = 1.0/(hypotheses.len() as f64); for hypothesis in hypotheses.into_iter() { backing.insert(hypothesis, probability_each); } Distribution(backing) } fn backing(&self) -> &HashMap<H, f64> { &self.0 } fn mut_backing(&mut self) -> &mut HashMap<H, f64> { &mut self.0 } pub fn len(&self) -> usize { self.backing().len() } pub fn hypotheses(&self) -> Vec<&H> { self.backing().keys().collect::<Vec<_>>() } pub fn belief(&self, hypothesis: H) -> f64 { *self.backing().get(&hypothesis).unwrap_or(&0.0f64) } pub fn entropy(&self) -> f64 { self.backing().values().map(|p| -p * p.log2()).sum() } pub fn completely_certain(&self) -> Option<H> { if self.backing().len()!= 1 { None } else { Some(*self.backing().keys().nth(0).expect("should have one entry")) } } pub fn predict(&self, study: &Study, verdict: bool) -> f64 { self.backing().iter() .filter(|hp| { let h = hp.0; h.predicts_the_property(study) == verdict }) .map(|hp| { let p = hp.1; p }).sum() } pub fn updated(&self, study: &Study, verdict: bool) -> Self { let normalization_factor = 1.0/self.predict(study, verdict); let rebacking_pairs = self.backing() .into_iter().filter(|hp| { let h = hp.0; h.predicts_the_property(study) == verdict }).map(|hp| { let (h, p) = hp; (*h, normalization_factor * p) }); let rebacking = HashMap::from_iter(rebacking_pairs); Distribution(rebacking) } pub fn value_of_information(&self, study: &Study) -> f64 { let mut entropy = 0.; let mut probability_of_the_property = 0.; let mut probability_of_the_negation = 0.; for (&hypothesis, &probability) in self.backing().iter() { if hypothesis.predicts_the_property(study) { probability_of_the_property += probability; } else { probability_of_the_negation += probability; } entropy += -probability * probability.log2(); } let property_normalization_factor = 1./probability_of_the_property; let negation_normalization_factor = 1./probability_of_the_negation; let mut entropy_given_the_property = 0.; let mut entropy_given_the_negation = 0.; for (&hypothesis, &probability) in self.backing().iter() { if hypothesis.predicts_the_property(study) { let p = property_normalization_factor * probability; entropy_given_the_property += -p * p.log2(); } else { let p = negation_normalization_factor * probability; entropy_given_the_negation += -p * p.log2(); } } let expected_entropy = probability_of_the_property * entropy_given_the_property + probability_of_the_negation * entropy_given_the_negation; entropy - expected_entropy } pub fn
(&self, desired_bits: f64, sample_cap: usize) -> Study { let mut study = Study::sample(); let mut value = self.value_of_information(&study); let mut top_study = study.clone(); let mut top_value = value; let mut samples = 1; loop { if value > top_value { top_value = value; top_study = study; } if (top_value > desired_bits) || (samples >= sample_cap) { break; } study = Study::sample(); value = self.value_of_information(&study); samples += 1; } top_study } pub fn inspect(&self, n: usize) { let mut backing = self.backing().iter().collect::<Vec<_>>(); backing.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_or(Ordering::Equal)); let total_probability_mass: f64 = backing.iter() .map(|hp| { hp.1 }).sum(); println!("Total probability mass: {:.6}", total_probability_mass); println!("Top {} hypotheses:", n); for &(&hypothesis, &probability) in backing.iter().take(n) { wrapln!(" * {}: {}", hypothesis.description(), Style::new().bold().paint(&format!("{:.4}", probability))); } } } pub fn complexity_prior(basic_hypotheses: Vec<BasicHypothesis>) -> Distribution<JoinedHypothesis> { let mut prebacking = HashMap::<JoinedHypothesis, f64>::new(); // just a guess; we'll have to normalize later to get a real probability let weight_each_basic = (2./3.)/(basic_hypotheses.len() as f64); let weight_each_joined = (1./3.)/(basic_hypotheses.len().pow(2) as f64); for &basic in &basic_hypotheses { prebacking.insert(JoinedHypothesis::full_stop(basic), weight_each_basic); } for (i, &one_basic) in basic_hypotheses.iter().enumerate() { for (j, &another_basic) in basic_hypotheses.iter().enumerate() { if j <= i { continue; } if one_basic.obviates(&another_basic) || another_basic.obviates(&one_basic) { continue; } let conjunction = JoinedHypothesis::and(one_basic, another_basic); let disjunction = JoinedHypothesis::or(one_basic, another_basic); for &junction in &vec![conjunction, disjunction] { if junction.check_substantiality(100) { prebacking.insert(junction, weight_each_joined); } } } } let total_mass: f64 = prebacking.iter().map(|hp| { hp.1 }).sum(); let normalization_factor = 1.0/total_mass; let backing_pairs = prebacking.into_iter() .map(|hp| { let (h, p) = hp; (h, normalization_factor * p) }); let backing = HashMap::from_iter(backing_pairs); Distribution(backing) } #[cfg(test)] mod tests { use test::Bencher; use super::*; use triangles::{Color, Size, Stack, Study, Triangle}; use inference::triangle::hypotheses::{BasicHypothesis, JoinedHypothesis}; use inference::triangle::hypotheses::color_count_boundedness::ColorCountBoundednessHypothesis; #[test] fn concerning_updating_your_bayesian_distribution() { // Suppose we think the hypotheses "A study has the property if it has // at least 1 triangle of color C" for C in {Red, Green, Blue, Yellow} // are all equally likely, and that we aren't considering any other // alternatives. let hypotheses = vec![Color::Red, Color::Green, Color::Blue, Color::Yellow].iter() .map(|&c| ColorCountBoundednessHypothesis::new_lower(c, 1)) .collect::<Vec<_>>(); let prior = Distribution::ignorance_prior(hypotheses); // If we learn that a study consisting of Red and Yellow triangles does // not have the property, then we think that C = Green or Blue are // equally likely. let beliefs = prior.updated( &study!(stack!(Triangle::new(Color::Red, Size::One), Triangle::new(Color::Yellow, Size::One))), false); let probability_c_is_blue = beliefs.belief( ColorCountBoundednessHypothesis::new_lower(Color::Blue, 1)); let probability_c_is_green = beliefs.belief( ColorCountBoundednessHypothesis::new_lower(Color::Green, 1)); assert_eq!(probability_c_is_blue, 0.5); assert_eq!(probability_c_is_green, 0.5); } #[ignore] // TODO investigate and repair test #[test] fn concerning_soundness_of_our_complexity_penalty() { // ⎲ ∞ // ⎳ i=1 1/2^i = 1 // // So... I want to give conjunctions and disjunctions a lower prior // probability, but I'm running into the same philosophical difficulty // that I ran into when I was first sketching out the number game, as // accounted in the README: if the true meaning of the complexity // penalty is that the hypothesis "A" gets to sum over the unspecified // details borne by the more complicated hypotheses "A ∧ B" and "A ∧ // C", then it's not clear how this insight translates to this setting, // where we want to represent our knowledge as a collection of mutually // exclusive hypotheses: we don't care about being able to refine a // true-but-vague theory to a true-but-more-precise theory; we want to // say that the precise theory is true and that all others are false. // // Probably the real answer is that this game just isn't very // philosophically interesting: we should have a complexity penalty to // exactly the extent that we think the human property-specifiers the // engine will face are going to choose disjunctions or disjunctions // less often than a uniform sample over distinct hypotheses would. let basics = vec![ BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower(Color::Blue, 1)), BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower(Color::Red, 1)) ]; let distribution = complexity_prior(basics); assert_eq!(1./3., distribution.belief(JoinedHypothesis::full_stop( BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Blue, 1))))); assert_eq!(1./12., distribution.belief(JoinedHypothesis::and( BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Blue, 1)), BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Red, 1))))); } #[bench] fn concerning_the_expense_of_updating(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.updated(&Study::sample(), true); }); } #[bench] fn concerning_the_expense_of_computing_entropy(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.entropy() }); } #[bench] fn concerning_the_expense_of_prediction(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.predict(&Study::sample(), true); }); } #[bench] fn concerning_the_expense_of_the_value(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.value_of_information(&Study::sample()); }); } }
burning_question
identifier_name
mod.rs
#![allow(dead_code)] pub mod hypotheses; use std::collections::HashMap; use std::hash::Hash; use std::cmp::{Eq, Ordering}; use std::iter::FromIterator; use ansi_term::Style; use triangles::Study; use inference::triangle::hypotheses::BasicHypothesis; use inference::triangle::hypotheses::JoinedHypothesis; pub use inference::triangle::hypotheses::standard_basics::standard_basic_hypotheses; pub trait Hypothesis { fn predicts_the_property(&self, study: &Study) -> bool; fn description(&self) -> String; } #[derive(Debug)] pub struct Distribution<H: Hypothesis + Hash + Eq>(HashMap<H, f64>); impl<H: Hypothesis + Hash + Eq + Copy> Distribution<H> { pub fn new() -> Self { let backing = HashMap::<H, f64>::new(); Distribution(backing) } pub fn ignorance_prior(hypotheses: Vec<H>) -> Self { let mut backing = HashMap::<H, f64>::new(); let probability_each: f64 = 1.0/(hypotheses.len() as f64); for hypothesis in hypotheses.into_iter() { backing.insert(hypothesis, probability_each); } Distribution(backing) } fn backing(&self) -> &HashMap<H, f64> { &self.0 } fn mut_backing(&mut self) -> &mut HashMap<H, f64> { &mut self.0 } pub fn len(&self) -> usize { self.backing().len() } pub fn hypotheses(&self) -> Vec<&H> { self.backing().keys().collect::<Vec<_>>() } pub fn belief(&self, hypothesis: H) -> f64 { *self.backing().get(&hypothesis).unwrap_or(&0.0f64) } pub fn entropy(&self) -> f64 { self.backing().values().map(|p| -p * p.log2()).sum() } pub fn completely_certain(&self) -> Option<H> { if self.backing().len()!= 1 { None } else { Some(*self.backing().keys().nth(0).expect("should have one entry")) } } pub fn predict(&self, study: &Study, verdict: bool) -> f64 { self.backing().iter() .filter(|hp| { let h = hp.0; h.predicts_the_property(study) == verdict }) .map(|hp| { let p = hp.1; p }).sum() } pub fn updated(&self, study: &Study, verdict: bool) -> Self { let normalization_factor = 1.0/self.predict(study, verdict); let rebacking_pairs = self.backing() .into_iter().filter(|hp| { let h = hp.0; h.predicts_the_property(study) == verdict }).map(|hp| { let (h, p) = hp; (*h, normalization_factor * p) }); let rebacking = HashMap::from_iter(rebacking_pairs); Distribution(rebacking) } pub fn value_of_information(&self, study: &Study) -> f64 { let mut entropy = 0.; let mut probability_of_the_property = 0.; let mut probability_of_the_negation = 0.; for (&hypothesis, &probability) in self.backing().iter() { if hypothesis.predicts_the_property(study) { probability_of_the_property += probability; } else { probability_of_the_negation += probability; } entropy += -probability * probability.log2(); } let property_normalization_factor = 1./probability_of_the_property; let negation_normalization_factor = 1./probability_of_the_negation; let mut entropy_given_the_property = 0.; let mut entropy_given_the_negation = 0.; for (&hypothesis, &probability) in self.backing().iter() { if hypothesis.predicts_the_property(study) { let p = property_normalization_factor * probability; entropy_given_the_property += -p * p.log2(); } else { let p = negation_normalization_factor * probability; entropy_given_the_negation += -p * p.log2(); } } let expected_entropy = probability_of_the_property * entropy_given_the_property + probability_of_the_negation * entropy_given_the_negation; entropy - expected_entropy } pub fn burning_question(&self, desired_bits: f64, sample_cap: usize) -> Study { let mut study = Study::sample(); let mut value = self.value_of_information(&study); let mut top_study = study.clone(); let mut top_value = value; let mut samples = 1; loop { if value > top_value { top_value = value; top_study = study; } if (top_value > desired_bits) || (samples >= sample_cap)
study = Study::sample(); value = self.value_of_information(&study); samples += 1; } top_study } pub fn inspect(&self, n: usize) { let mut backing = self.backing().iter().collect::<Vec<_>>(); backing.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_or(Ordering::Equal)); let total_probability_mass: f64 = backing.iter() .map(|hp| { hp.1 }).sum(); println!("Total probability mass: {:.6}", total_probability_mass); println!("Top {} hypotheses:", n); for &(&hypothesis, &probability) in backing.iter().take(n) { wrapln!(" * {}: {}", hypothesis.description(), Style::new().bold().paint(&format!("{:.4}", probability))); } } } pub fn complexity_prior(basic_hypotheses: Vec<BasicHypothesis>) -> Distribution<JoinedHypothesis> { let mut prebacking = HashMap::<JoinedHypothesis, f64>::new(); // just a guess; we'll have to normalize later to get a real probability let weight_each_basic = (2./3.)/(basic_hypotheses.len() as f64); let weight_each_joined = (1./3.)/(basic_hypotheses.len().pow(2) as f64); for &basic in &basic_hypotheses { prebacking.insert(JoinedHypothesis::full_stop(basic), weight_each_basic); } for (i, &one_basic) in basic_hypotheses.iter().enumerate() { for (j, &another_basic) in basic_hypotheses.iter().enumerate() { if j <= i { continue; } if one_basic.obviates(&another_basic) || another_basic.obviates(&one_basic) { continue; } let conjunction = JoinedHypothesis::and(one_basic, another_basic); let disjunction = JoinedHypothesis::or(one_basic, another_basic); for &junction in &vec![conjunction, disjunction] { if junction.check_substantiality(100) { prebacking.insert(junction, weight_each_joined); } } } } let total_mass: f64 = prebacking.iter().map(|hp| { hp.1 }).sum(); let normalization_factor = 1.0/total_mass; let backing_pairs = prebacking.into_iter() .map(|hp| { let (h, p) = hp; (h, normalization_factor * p) }); let backing = HashMap::from_iter(backing_pairs); Distribution(backing) } #[cfg(test)] mod tests { use test::Bencher; use super::*; use triangles::{Color, Size, Stack, Study, Triangle}; use inference::triangle::hypotheses::{BasicHypothesis, JoinedHypothesis}; use inference::triangle::hypotheses::color_count_boundedness::ColorCountBoundednessHypothesis; #[test] fn concerning_updating_your_bayesian_distribution() { // Suppose we think the hypotheses "A study has the property if it has // at least 1 triangle of color C" for C in {Red, Green, Blue, Yellow} // are all equally likely, and that we aren't considering any other // alternatives. let hypotheses = vec![Color::Red, Color::Green, Color::Blue, Color::Yellow].iter() .map(|&c| ColorCountBoundednessHypothesis::new_lower(c, 1)) .collect::<Vec<_>>(); let prior = Distribution::ignorance_prior(hypotheses); // If we learn that a study consisting of Red and Yellow triangles does // not have the property, then we think that C = Green or Blue are // equally likely. let beliefs = prior.updated( &study!(stack!(Triangle::new(Color::Red, Size::One), Triangle::new(Color::Yellow, Size::One))), false); let probability_c_is_blue = beliefs.belief( ColorCountBoundednessHypothesis::new_lower(Color::Blue, 1)); let probability_c_is_green = beliefs.belief( ColorCountBoundednessHypothesis::new_lower(Color::Green, 1)); assert_eq!(probability_c_is_blue, 0.5); assert_eq!(probability_c_is_green, 0.5); } #[ignore] // TODO investigate and repair test #[test] fn concerning_soundness_of_our_complexity_penalty() { // ⎲ ∞ // ⎳ i=1 1/2^i = 1 // // So... I want to give conjunctions and disjunctions a lower prior // probability, but I'm running into the same philosophical difficulty // that I ran into when I was first sketching out the number game, as // accounted in the README: if the true meaning of the complexity // penalty is that the hypothesis "A" gets to sum over the unspecified // details borne by the more complicated hypotheses "A ∧ B" and "A ∧ // C", then it's not clear how this insight translates to this setting, // where we want to represent our knowledge as a collection of mutually // exclusive hypotheses: we don't care about being able to refine a // true-but-vague theory to a true-but-more-precise theory; we want to // say that the precise theory is true and that all others are false. // // Probably the real answer is that this game just isn't very // philosophically interesting: we should have a complexity penalty to // exactly the extent that we think the human property-specifiers the // engine will face are going to choose disjunctions or disjunctions // less often than a uniform sample over distinct hypotheses would. let basics = vec![ BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower(Color::Blue, 1)), BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower(Color::Red, 1)) ]; let distribution = complexity_prior(basics); assert_eq!(1./3., distribution.belief(JoinedHypothesis::full_stop( BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Blue, 1))))); assert_eq!(1./12., distribution.belief(JoinedHypothesis::and( BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Blue, 1)), BasicHypothesis::from( ColorCountBoundednessHypothesis::new_lower( Color::Red, 1))))); } #[bench] fn concerning_the_expense_of_updating(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.updated(&Study::sample(), true); }); } #[bench] fn concerning_the_expense_of_computing_entropy(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.entropy() }); } #[bench] fn concerning_the_expense_of_prediction(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.predict(&Study::sample(), true); }); } #[bench] fn concerning_the_expense_of_the_value(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.value_of_information(&Study::sample()); }); } }
{ break; }
conditional_block
lib.rs
#![allow(clippy::many_single_char_names, non_snake_case)] pub mod chase; pub mod mvd; mod parser; mod sorted_uvec; use itertools::Itertools; use mvd::MVD; use rand::prelude::Distribution; use sorted_uvec::SortedUVec; use std::{borrow::Borrow, mem, ops::Not}; use std::{ collections::HashMap, fmt::{self, Display, Formatter}, }; pub type Attrs = SortedUVec<u32>; impl Attrs { pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> AttrWithNames<'a> { AttrWithNames { attrs: self, register, } } pub fn keys(&self, FDs: &[FD]) -> Vec<Attrs> { all_subsets_of(self) .filter(|sub| categorize(sub, self, FDs) == Category::Key) .collect() } } pub fn attrs<I, J>(iter: I) -> Attrs where I: IntoIterator<Item = J>, J: Borrow<u32>, { Attrs::new(iter.into_iter().map(|v| *v.borrow())) } #[derive(PartialEq, Eq, Clone, Debug, Default)] pub struct FD { pub source: Attrs, pub target: Attrs, } impl FD { pub fn new(source: Attrs, target: Attrs) -> Self { let target = &target - &source; Self { source, target } } pub fn is_deformed(&self) -> bool { self.source.is_empty() || self.target.is_empty() } pub fn split(&self) -> impl Iterator<Item = FD> + '_ { self.target .iter() .map(move |&v| FD::new(self.source.clone(), attrs(&[v]))) } pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> DepWithNames<'a> { DepWithNames { arrow: "->", source: &self.source, target: &self.target, register, } } } pub struct DepWithNames<'a> { arrow: &'a str, source: &'a Attrs, target: &'a Attrs, register: &'a NameRegister, } impl Display for DepWithNames<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let sep_by_comma = |list: &[u32], f: &mut Formatter| -> fmt::Result { let mut first = true; for &v in list { if!first { write!(f, ", ")?; } first = false; write!(f, "{}", self.register.name(v).unwrap_or("{Unnamed}"))?; } Ok(()) }; sep_by_comma(&*self.source, f)?; write!(f, " {} ", self.arrow)?; sep_by_comma(&*self.target, f)?; Ok(()) } } pub fn closure_of(attrs: &Attrs, dependencies: &[FD]) -> Attrs { let mut closure = attrs.clone(); let mut size = closure.len(); loop { for fd in dependencies { if fd.source.is_subset(&closure) { closure.extend(fd.target.iter().copied()); } } if closure.len() > size { size = closure.len(); } else { break; } } closure } #[derive(Debug, PartialEq)] pub enum Category { Nonkey, Key, Superkey, } impl Display for Category { fn fmt(&self, f: &mut Formatter) -> fmt::Result { <Self as fmt::Debug>::fmt(self, f) } } pub fn categorize(sub: &Attrs, rel: &Attrs, FDs: &[FD]) -> Category { let closure = closure_of(sub, FDs); if!closure.is_superset(&rel) { return Category::Nonkey; } let has_subkey = sub .iter() .map(|v| { let mut shirnked = sub.clone(); shirnked.remove(v); shirnked }) .any(|attrs| closure_of(&attrs, FDs).is_superset(&rel)); if has_subkey { Category::Superkey } else { Category::Key } } #[derive(Default)] pub struct NameRegister { cnt: u32, name_idx: HashMap<String, u32>, idx_name: HashMap<u32, String>, } impl NameRegister { pub fn new() -> Self { Self::default() } pub fn resolve(&self, name: &str) -> Option<u32> { self.name_idx.get(name).copied() } pub fn name(&self, idx: u32) -> Option<&str> { self.idx_name.get(&idx).map(|s| s.as_str()) } pub fn attrs(&self) -> Attrs { (0..self.cnt).collect() } pub fn categorize(&self, attrs: &Attrs, dependencies: &[FD]) -> Category { categorize(attrs, &self.attrs(), dependencies) } pub fn register(&mut self, name: &str) -> u32 { self.resolve(name).unwrap_or_else(|| { let key = self.cnt; self.cnt += 1; self.name_idx.insert(name.to_string(), key); self.idx_name.insert(key, name.to_string()); key }) } pub fn parse_fd(&self, input: &str) -> Option<FD> { let (_, (source, target)) = parser::fd(input).ok()?; let source: Attrs = source .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; let target: Attrs = target .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; Some(FD::new(source, target)) } pub fn parse_mvd(&self, input: &str) -> Option<MVD> { let (_, (source, target)) = parser::mvd(input).ok()?; let source: Attrs = source .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; let target: Attrs = target .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; Some(MVD::new(source, target)) } pub fn cnt(&self) -> u32 { self.cnt } } pub struct AttrWithNames<'a> { attrs: &'a [u32], register: &'a NameRegister, } impl<'a> Display for AttrWithNames<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut is_first = true; write!(f, "{{ ")?; for &attr in self.attrs { if!is_first { write!(f, ", ")?; } is_first = false; f.write_str(self.register.name(attr).unwrap_or("{Unnamed}"))?; } write!(f, " }}")?; Ok(()) } } pub fn parse_FDs(register: &NameRegister, FDs: &[&str]) -> Vec<FD> { FDs.iter() .map(|fd| register.parse_fd(fd).unwrap()) .collect() } pub fn parse_MVDs(register: &NameRegister, MVDs: &[&str]) -> Vec<MVD> { MVDs.iter() .map(|mvd| register.parse_mvd(mvd).unwrap()) .collect() } pub fn implies(FDs: &[FD], fd: &FD) -> bool { closure_of(&fd.source, FDs).is_superset(&fd.target) } pub fn all_subsets_of(attrs: &[u32]) -> impl Iterator<Item = Attrs> + '_ { (0..=attrs.len()) .flat_map(move |k| attrs.iter().copied().combinations(k)) .map(From::from) } pub fn project_to(attrs: &Attrs, FDs: &[FD]) -> Vec<FD> { let FDs: Vec<FD> = all_subsets_of(&*attrs) .map(|selected| { let closure = closure_of(&selected, FDs); FD::new(selected, &closure & attrs) }) .filter(|fd|!fd.is_deformed()) .collect(); minify(&FDs) } pub fn is_minimal_basis(FDs: &[FD]) -> bool { let mut FDs: Vec<_> = FDs.iter().flat_map(|fd| fd.split()).collect(); !remove_implied(&mut FDs) } pub fn minify(FDs: &[FD]) -> Vec<FD> { let mut FDs: Vec<_> = FDs.iter().flat_map(|fd| fd.split()).collect(); loop { let refined = remove_implied(&mut FDs); let shrinked = remove_redundant(&mut FDs); if!(refined || shrinked) { break; } } FDs.sort_by(|a, b| a.source.cmp(&b.source)); FDs } fn remove_implied(FDs: &mut Vec<FD>) -> bool { for i in 0..FDs.len() { let FD = mem::take(&mut FDs[i]); if implies(FDs, &FD) { FDs.swap_remove(i); return true; } FDs[i] = FD; } false } fn remove_redundant(FDs: &mut [FD]) -> bool { for i in 0..FDs.len() { let FD = &FDs[i]; for v in &FD.source { let mut shrinked = FD.clone(); shrinked.source.remove(v); if implies(FDs, &shrinked) { FDs[i] = shrinked; return true; } } } false } pub fn all_violations<'a>(rel: &'a Attrs, FDs: &'a [FD]) -> impl Iterator<Item = &'a FD> + 'a { FDs.iter() .filter(move |fd| closure_of(&fd.source, FDs).is_superset(rel).not()) } fn violation<'a>(rel: &'a Attrs, FDs: &'a [FD]) -> Option<&'a FD> { all_violations(rel, FDs).next() } pub fn is_bcnf_violation(rel: &Attrs, FDs: &[FD]) -> bool { violation(rel, FDs).is_some() } pub fn bcnf_decomposition(rel: &Attrs, FDs: &[FD]) -> Vec<Attrs> { let rel: Attrs = rel.clone(); let mut candidates: Vec<(Attrs, Vec<FD>)> = vec![(rel, FDs.to_vec())]; let mut bcnf: Vec<Attrs> = vec![]; while let Some((rel, FDs)) = candidates.pop() { // every 2-attribute relation is in BCNF if rel.len() <= 2 { bcnf.push(rel); continue; } if let Some(fd) = violation(&rel, &FDs) { let rel_0 = closure_of(&fd.source, &FDs); let FDs_0 = project_to(&rel_0, &FDs); let rel_1 = &fd.source | &(&rel - &rel_0); let FDs_1 = project_to(&rel_1, &FDs); candidates.push((rel_0, FDs_0)); candidates.push((rel_1, FDs_1)); } else
} bcnf } pub struct NumberOfAttrs(u32); impl NumberOfAttrs { pub fn new(n: u32) -> Self { Self(n) } } impl Distribution<FD> for NumberOfAttrs { fn sample<R: rand::Rng +?Sized>(&self, rng: &mut R) -> FD { let n = self.0; let mut source = vec![]; let mut target = vec![]; for i in 0..n { if rng.gen_bool(0.5) { source.push(i); } if rng.gen_bool(0.5) { target.push(i); } } if source.is_empty() { source.push(rng.gen_range(0..n)); } if target.is_empty() { target.push(rng.gen_range(0..n)); } FD::new(source.into(), target.into()) } } #[cfg(test)] mod test { use super::*; #[test] fn closure_test() { let mut reg = NameRegister::new(); let A = reg.register("A"); let B = reg.register("B"); let C = reg.register("C"); let D = reg.register("D"); let E = reg.register("E"); let _F = reg.register("F"); let dependencies = parse_FDs(&reg, &["A, B -> C", "B, C -> A, D", "D -> E", "C, F -> B"]); assert_eq!( &*closure_of(&attrs(&[A, B]), &dependencies), &[A, B, C, D, E] ); assert_eq!(&*closure_of(&attrs(&[D]), &dependencies), &[D, E]); } #[test] fn format_test() { let mut reg = NameRegister::new(); reg.register("A"); reg.register("B"); reg.register("C"); reg.register("D"); let fd = reg.parse_fd("B, A -> D, C").unwrap(); assert_eq!(format!("{}", fd.with_names(&reg)), "A, B -> C, D"); } #[test] fn project_test() { let mut reg = NameRegister::new(); let A = reg.register("A"); let _B = reg.register("B"); let C = reg.register("C"); let D = reg.register("D"); let FDs = parse_FDs(&reg, &["A -> B", "B -> C", "C -> D"]); let projection = project_to(&[A, C, D].iter().copied().collect(), &FDs); assert_eq!(projection.len(), 2); assert!(projection.iter().all(|fd| fd.target.len() == 1)); assert!(implies(&projection, &reg.parse_fd("A -> C, D").unwrap())); assert!(implies(&projection, &reg.parse_fd("C -> D").unwrap())); } #[test] fn violation_test() { let mut reg = NameRegister::new(); let _title = reg.register("title"); let _year = reg.register("year"); let _studio_name = reg.register("studio_name"); let _president = reg.register("president"); let FDs = parse_FDs( &reg, &["title, year -> studio_name", "studio_name -> president"], ); assert_eq!(violation(&reg.attrs(), &FDs), Some(&FDs[1])); } #[test] fn bcnf_test() { let mut reg = NameRegister::new(); let title = reg.register("title"); let year = reg.register("year"); let studio_name = reg.register("studio_name"); let president = reg.register("president"); let pres_addr = reg.register("pres_addr"); let FDs = parse_FDs( &reg, &[ "title, year -> studio_name", "studio_name -> president", "president -> pres_addr", ], ); let decomposition = bcnf_decomposition(&reg.attrs(), &FDs); assert_eq!(decomposition.len(), 3); assert!(decomposition.contains(&attrs(&[title, year, studio_name]))); assert!(decomposition.contains(&attrs(&[studio_name, president]))); assert!(decomposition.contains(&attrs(&[president, pres_addr]))); } }
{ bcnf.push(rel); }
conditional_block
lib.rs
#![allow(clippy::many_single_char_names, non_snake_case)] pub mod chase; pub mod mvd; mod parser; mod sorted_uvec; use itertools::Itertools; use mvd::MVD; use rand::prelude::Distribution; use sorted_uvec::SortedUVec; use std::{borrow::Borrow, mem, ops::Not}; use std::{ collections::HashMap, fmt::{self, Display, Formatter}, }; pub type Attrs = SortedUVec<u32>; impl Attrs { pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> AttrWithNames<'a> { AttrWithNames { attrs: self, register, } } pub fn keys(&self, FDs: &[FD]) -> Vec<Attrs> { all_subsets_of(self) .filter(|sub| categorize(sub, self, FDs) == Category::Key) .collect() } } pub fn attrs<I, J>(iter: I) -> Attrs where I: IntoIterator<Item = J>, J: Borrow<u32>, { Attrs::new(iter.into_iter().map(|v| *v.borrow())) } #[derive(PartialEq, Eq, Clone, Debug, Default)] pub struct FD { pub source: Attrs, pub target: Attrs, } impl FD { pub fn new(source: Attrs, target: Attrs) -> Self { let target = &target - &source; Self { source, target } } pub fn is_deformed(&self) -> bool { self.source.is_empty() || self.target.is_empty() } pub fn split(&self) -> impl Iterator<Item = FD> + '_ { self.target .iter() .map(move |&v| FD::new(self.source.clone(), attrs(&[v]))) } pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> DepWithNames<'a> { DepWithNames { arrow: "->", source: &self.source, target: &self.target, register, } } } pub struct DepWithNames<'a> { arrow: &'a str, source: &'a Attrs, target: &'a Attrs, register: &'a NameRegister, } impl Display for DepWithNames<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let sep_by_comma = |list: &[u32], f: &mut Formatter| -> fmt::Result { let mut first = true; for &v in list { if!first { write!(f, ", ")?; } first = false; write!(f, "{}", self.register.name(v).unwrap_or("{Unnamed}"))?; } Ok(()) }; sep_by_comma(&*self.source, f)?; write!(f, " {} ", self.arrow)?; sep_by_comma(&*self.target, f)?; Ok(()) } } pub fn closure_of(attrs: &Attrs, dependencies: &[FD]) -> Attrs { let mut closure = attrs.clone(); let mut size = closure.len(); loop { for fd in dependencies { if fd.source.is_subset(&closure) { closure.extend(fd.target.iter().copied()); } } if closure.len() > size { size = closure.len(); } else { break; } } closure } #[derive(Debug, PartialEq)] pub enum Category { Nonkey, Key, Superkey, } impl Display for Category { fn
(&self, f: &mut Formatter) -> fmt::Result { <Self as fmt::Debug>::fmt(self, f) } } pub fn categorize(sub: &Attrs, rel: &Attrs, FDs: &[FD]) -> Category { let closure = closure_of(sub, FDs); if!closure.is_superset(&rel) { return Category::Nonkey; } let has_subkey = sub .iter() .map(|v| { let mut shirnked = sub.clone(); shirnked.remove(v); shirnked }) .any(|attrs| closure_of(&attrs, FDs).is_superset(&rel)); if has_subkey { Category::Superkey } else { Category::Key } } #[derive(Default)] pub struct NameRegister { cnt: u32, name_idx: HashMap<String, u32>, idx_name: HashMap<u32, String>, } impl NameRegister { pub fn new() -> Self { Self::default() } pub fn resolve(&self, name: &str) -> Option<u32> { self.name_idx.get(name).copied() } pub fn name(&self, idx: u32) -> Option<&str> { self.idx_name.get(&idx).map(|s| s.as_str()) } pub fn attrs(&self) -> Attrs { (0..self.cnt).collect() } pub fn categorize(&self, attrs: &Attrs, dependencies: &[FD]) -> Category { categorize(attrs, &self.attrs(), dependencies) } pub fn register(&mut self, name: &str) -> u32 { self.resolve(name).unwrap_or_else(|| { let key = self.cnt; self.cnt += 1; self.name_idx.insert(name.to_string(), key); self.idx_name.insert(key, name.to_string()); key }) } pub fn parse_fd(&self, input: &str) -> Option<FD> { let (_, (source, target)) = parser::fd(input).ok()?; let source: Attrs = source .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; let target: Attrs = target .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; Some(FD::new(source, target)) } pub fn parse_mvd(&self, input: &str) -> Option<MVD> { let (_, (source, target)) = parser::mvd(input).ok()?; let source: Attrs = source .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; let target: Attrs = target .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; Some(MVD::new(source, target)) } pub fn cnt(&self) -> u32 { self.cnt } } pub struct AttrWithNames<'a> { attrs: &'a [u32], register: &'a NameRegister, } impl<'a> Display for AttrWithNames<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut is_first = true; write!(f, "{{ ")?; for &attr in self.attrs { if!is_first { write!(f, ", ")?; } is_first = false; f.write_str(self.register.name(attr).unwrap_or("{Unnamed}"))?; } write!(f, " }}")?; Ok(()) } } pub fn parse_FDs(register: &NameRegister, FDs: &[&str]) -> Vec<FD> { FDs.iter() .map(|fd| register.parse_fd(fd).unwrap()) .collect() } pub fn parse_MVDs(register: &NameRegister, MVDs: &[&str]) -> Vec<MVD> { MVDs.iter() .map(|mvd| register.parse_mvd(mvd).unwrap()) .collect() } pub fn implies(FDs: &[FD], fd: &FD) -> bool { closure_of(&fd.source, FDs).is_superset(&fd.target) } pub fn all_subsets_of(attrs: &[u32]) -> impl Iterator<Item = Attrs> + '_ { (0..=attrs.len()) .flat_map(move |k| attrs.iter().copied().combinations(k)) .map(From::from) } pub fn project_to(attrs: &Attrs, FDs: &[FD]) -> Vec<FD> { let FDs: Vec<FD> = all_subsets_of(&*attrs) .map(|selected| { let closure = closure_of(&selected, FDs); FD::new(selected, &closure & attrs) }) .filter(|fd|!fd.is_deformed()) .collect(); minify(&FDs) } pub fn is_minimal_basis(FDs: &[FD]) -> bool { let mut FDs: Vec<_> = FDs.iter().flat_map(|fd| fd.split()).collect(); !remove_implied(&mut FDs) } pub fn minify(FDs: &[FD]) -> Vec<FD> { let mut FDs: Vec<_> = FDs.iter().flat_map(|fd| fd.split()).collect(); loop { let refined = remove_implied(&mut FDs); let shrinked = remove_redundant(&mut FDs); if!(refined || shrinked) { break; } } FDs.sort_by(|a, b| a.source.cmp(&b.source)); FDs } fn remove_implied(FDs: &mut Vec<FD>) -> bool { for i in 0..FDs.len() { let FD = mem::take(&mut FDs[i]); if implies(FDs, &FD) { FDs.swap_remove(i); return true; } FDs[i] = FD; } false } fn remove_redundant(FDs: &mut [FD]) -> bool { for i in 0..FDs.len() { let FD = &FDs[i]; for v in &FD.source { let mut shrinked = FD.clone(); shrinked.source.remove(v); if implies(FDs, &shrinked) { FDs[i] = shrinked; return true; } } } false } pub fn all_violations<'a>(rel: &'a Attrs, FDs: &'a [FD]) -> impl Iterator<Item = &'a FD> + 'a { FDs.iter() .filter(move |fd| closure_of(&fd.source, FDs).is_superset(rel).not()) } fn violation<'a>(rel: &'a Attrs, FDs: &'a [FD]) -> Option<&'a FD> { all_violations(rel, FDs).next() } pub fn is_bcnf_violation(rel: &Attrs, FDs: &[FD]) -> bool { violation(rel, FDs).is_some() } pub fn bcnf_decomposition(rel: &Attrs, FDs: &[FD]) -> Vec<Attrs> { let rel: Attrs = rel.clone(); let mut candidates: Vec<(Attrs, Vec<FD>)> = vec![(rel, FDs.to_vec())]; let mut bcnf: Vec<Attrs> = vec![]; while let Some((rel, FDs)) = candidates.pop() { // every 2-attribute relation is in BCNF if rel.len() <= 2 { bcnf.push(rel); continue; } if let Some(fd) = violation(&rel, &FDs) { let rel_0 = closure_of(&fd.source, &FDs); let FDs_0 = project_to(&rel_0, &FDs); let rel_1 = &fd.source | &(&rel - &rel_0); let FDs_1 = project_to(&rel_1, &FDs); candidates.push((rel_0, FDs_0)); candidates.push((rel_1, FDs_1)); } else { bcnf.push(rel); } } bcnf } pub struct NumberOfAttrs(u32); impl NumberOfAttrs { pub fn new(n: u32) -> Self { Self(n) } } impl Distribution<FD> for NumberOfAttrs { fn sample<R: rand::Rng +?Sized>(&self, rng: &mut R) -> FD { let n = self.0; let mut source = vec![]; let mut target = vec![]; for i in 0..n { if rng.gen_bool(0.5) { source.push(i); } if rng.gen_bool(0.5) { target.push(i); } } if source.is_empty() { source.push(rng.gen_range(0..n)); } if target.is_empty() { target.push(rng.gen_range(0..n)); } FD::new(source.into(), target.into()) } } #[cfg(test)] mod test { use super::*; #[test] fn closure_test() { let mut reg = NameRegister::new(); let A = reg.register("A"); let B = reg.register("B"); let C = reg.register("C"); let D = reg.register("D"); let E = reg.register("E"); let _F = reg.register("F"); let dependencies = parse_FDs(&reg, &["A, B -> C", "B, C -> A, D", "D -> E", "C, F -> B"]); assert_eq!( &*closure_of(&attrs(&[A, B]), &dependencies), &[A, B, C, D, E] ); assert_eq!(&*closure_of(&attrs(&[D]), &dependencies), &[D, E]); } #[test] fn format_test() { let mut reg = NameRegister::new(); reg.register("A"); reg.register("B"); reg.register("C"); reg.register("D"); let fd = reg.parse_fd("B, A -> D, C").unwrap(); assert_eq!(format!("{}", fd.with_names(&reg)), "A, B -> C, D"); } #[test] fn project_test() { let mut reg = NameRegister::new(); let A = reg.register("A"); let _B = reg.register("B"); let C = reg.register("C"); let D = reg.register("D"); let FDs = parse_FDs(&reg, &["A -> B", "B -> C", "C -> D"]); let projection = project_to(&[A, C, D].iter().copied().collect(), &FDs); assert_eq!(projection.len(), 2); assert!(projection.iter().all(|fd| fd.target.len() == 1)); assert!(implies(&projection, &reg.parse_fd("A -> C, D").unwrap())); assert!(implies(&projection, &reg.parse_fd("C -> D").unwrap())); } #[test] fn violation_test() { let mut reg = NameRegister::new(); let _title = reg.register("title"); let _year = reg.register("year"); let _studio_name = reg.register("studio_name"); let _president = reg.register("president"); let FDs = parse_FDs( &reg, &["title, year -> studio_name", "studio_name -> president"], ); assert_eq!(violation(&reg.attrs(), &FDs), Some(&FDs[1])); } #[test] fn bcnf_test() { let mut reg = NameRegister::new(); let title = reg.register("title"); let year = reg.register("year"); let studio_name = reg.register("studio_name"); let president = reg.register("president"); let pres_addr = reg.register("pres_addr"); let FDs = parse_FDs( &reg, &[ "title, year -> studio_name", "studio_name -> president", "president -> pres_addr", ], ); let decomposition = bcnf_decomposition(&reg.attrs(), &FDs); assert_eq!(decomposition.len(), 3); assert!(decomposition.contains(&attrs(&[title, year, studio_name]))); assert!(decomposition.contains(&attrs(&[studio_name, president]))); assert!(decomposition.contains(&attrs(&[president, pres_addr]))); } }
fmt
identifier_name
lib.rs
#![allow(clippy::many_single_char_names, non_snake_case)] pub mod chase; pub mod mvd; mod parser; mod sorted_uvec; use itertools::Itertools; use mvd::MVD; use rand::prelude::Distribution; use sorted_uvec::SortedUVec; use std::{borrow::Borrow, mem, ops::Not}; use std::{ collections::HashMap, fmt::{self, Display, Formatter}, }; pub type Attrs = SortedUVec<u32>; impl Attrs { pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> AttrWithNames<'a> { AttrWithNames { attrs: self, register, } } pub fn keys(&self, FDs: &[FD]) -> Vec<Attrs> { all_subsets_of(self) .filter(|sub| categorize(sub, self, FDs) == Category::Key) .collect() } } pub fn attrs<I, J>(iter: I) -> Attrs where I: IntoIterator<Item = J>, J: Borrow<u32>, { Attrs::new(iter.into_iter().map(|v| *v.borrow())) } #[derive(PartialEq, Eq, Clone, Debug, Default)] pub struct FD { pub source: Attrs, pub target: Attrs, } impl FD { pub fn new(source: Attrs, target: Attrs) -> Self { let target = &target - &source; Self { source, target } } pub fn is_deformed(&self) -> bool { self.source.is_empty() || self.target.is_empty() } pub fn split(&self) -> impl Iterator<Item = FD> + '_ { self.target .iter() .map(move |&v| FD::new(self.source.clone(), attrs(&[v]))) } pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> DepWithNames<'a> { DepWithNames { arrow: "->", source: &self.source, target: &self.target, register, } } } pub struct DepWithNames<'a> { arrow: &'a str, source: &'a Attrs, target: &'a Attrs, register: &'a NameRegister, } impl Display for DepWithNames<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let sep_by_comma = |list: &[u32], f: &mut Formatter| -> fmt::Result { let mut first = true; for &v in list { if!first { write!(f, ", ")?; } first = false; write!(f, "{}", self.register.name(v).unwrap_or("{Unnamed}"))?; } Ok(()) }; sep_by_comma(&*self.source, f)?; write!(f, " {} ", self.arrow)?; sep_by_comma(&*self.target, f)?; Ok(()) } } pub fn closure_of(attrs: &Attrs, dependencies: &[FD]) -> Attrs { let mut closure = attrs.clone(); let mut size = closure.len(); loop { for fd in dependencies { if fd.source.is_subset(&closure) { closure.extend(fd.target.iter().copied()); } } if closure.len() > size { size = closure.len(); } else { break; } } closure } #[derive(Debug, PartialEq)] pub enum Category { Nonkey, Key, Superkey, } impl Display for Category { fn fmt(&self, f: &mut Formatter) -> fmt::Result { <Self as fmt::Debug>::fmt(self, f) } } pub fn categorize(sub: &Attrs, rel: &Attrs, FDs: &[FD]) -> Category { let closure = closure_of(sub, FDs); if!closure.is_superset(&rel) { return Category::Nonkey; } let has_subkey = sub .iter() .map(|v| { let mut shirnked = sub.clone(); shirnked.remove(v); shirnked }) .any(|attrs| closure_of(&attrs, FDs).is_superset(&rel)); if has_subkey { Category::Superkey } else { Category::Key } } #[derive(Default)] pub struct NameRegister { cnt: u32, name_idx: HashMap<String, u32>, idx_name: HashMap<u32, String>, } impl NameRegister { pub fn new() -> Self { Self::default() } pub fn resolve(&self, name: &str) -> Option<u32> { self.name_idx.get(name).copied() } pub fn name(&self, idx: u32) -> Option<&str> { self.idx_name.get(&idx).map(|s| s.as_str()) } pub fn attrs(&self) -> Attrs { (0..self.cnt).collect() } pub fn categorize(&self, attrs: &Attrs, dependencies: &[FD]) -> Category { categorize(attrs, &self.attrs(), dependencies) } pub fn register(&mut self, name: &str) -> u32 { self.resolve(name).unwrap_or_else(|| { let key = self.cnt; self.cnt += 1; self.name_idx.insert(name.to_string(), key); self.idx_name.insert(key, name.to_string()); key }) } pub fn parse_fd(&self, input: &str) -> Option<FD> { let (_, (source, target)) = parser::fd(input).ok()?; let source: Attrs = source .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; let target: Attrs = target .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; Some(FD::new(source, target)) } pub fn parse_mvd(&self, input: &str) -> Option<MVD> { let (_, (source, target)) = parser::mvd(input).ok()?; let source: Attrs = source .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; let target: Attrs = target .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; Some(MVD::new(source, target)) } pub fn cnt(&self) -> u32 { self.cnt } } pub struct AttrWithNames<'a> { attrs: &'a [u32], register: &'a NameRegister, } impl<'a> Display for AttrWithNames<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut is_first = true; write!(f, "{{ ")?; for &attr in self.attrs { if!is_first { write!(f, ", ")?; } is_first = false; f.write_str(self.register.name(attr).unwrap_or("{Unnamed}"))?; } write!(f, " }}")?; Ok(()) } } pub fn parse_FDs(register: &NameRegister, FDs: &[&str]) -> Vec<FD> { FDs.iter() .map(|fd| register.parse_fd(fd).unwrap()) .collect() } pub fn parse_MVDs(register: &NameRegister, MVDs: &[&str]) -> Vec<MVD> { MVDs.iter() .map(|mvd| register.parse_mvd(mvd).unwrap()) .collect() } pub fn implies(FDs: &[FD], fd: &FD) -> bool { closure_of(&fd.source, FDs).is_superset(&fd.target) } pub fn all_subsets_of(attrs: &[u32]) -> impl Iterator<Item = Attrs> + '_ { (0..=attrs.len()) .flat_map(move |k| attrs.iter().copied().combinations(k)) .map(From::from) } pub fn project_to(attrs: &Attrs, FDs: &[FD]) -> Vec<FD> { let FDs: Vec<FD> = all_subsets_of(&*attrs) .map(|selected| { let closure = closure_of(&selected, FDs); FD::new(selected, &closure & attrs) }) .filter(|fd|!fd.is_deformed()) .collect(); minify(&FDs) } pub fn is_minimal_basis(FDs: &[FD]) -> bool { let mut FDs: Vec<_> = FDs.iter().flat_map(|fd| fd.split()).collect(); !remove_implied(&mut FDs) } pub fn minify(FDs: &[FD]) -> Vec<FD> { let mut FDs: Vec<_> = FDs.iter().flat_map(|fd| fd.split()).collect(); loop { let refined = remove_implied(&mut FDs); let shrinked = remove_redundant(&mut FDs); if!(refined || shrinked) { break; } } FDs.sort_by(|a, b| a.source.cmp(&b.source)); FDs } fn remove_implied(FDs: &mut Vec<FD>) -> bool { for i in 0..FDs.len() { let FD = mem::take(&mut FDs[i]); if implies(FDs, &FD) { FDs.swap_remove(i); return true; } FDs[i] = FD; } false } fn remove_redundant(FDs: &mut [FD]) -> bool { for i in 0..FDs.len() { let FD = &FDs[i]; for v in &FD.source { let mut shrinked = FD.clone(); shrinked.source.remove(v); if implies(FDs, &shrinked) { FDs[i] = shrinked; return true; } } } false } pub fn all_violations<'a>(rel: &'a Attrs, FDs: &'a [FD]) -> impl Iterator<Item = &'a FD> + 'a { FDs.iter() .filter(move |fd| closure_of(&fd.source, FDs).is_superset(rel).not()) } fn violation<'a>(rel: &'a Attrs, FDs: &'a [FD]) -> Option<&'a FD> { all_violations(rel, FDs).next() } pub fn is_bcnf_violation(rel: &Attrs, FDs: &[FD]) -> bool { violation(rel, FDs).is_some() }
while let Some((rel, FDs)) = candidates.pop() { // every 2-attribute relation is in BCNF if rel.len() <= 2 { bcnf.push(rel); continue; } if let Some(fd) = violation(&rel, &FDs) { let rel_0 = closure_of(&fd.source, &FDs); let FDs_0 = project_to(&rel_0, &FDs); let rel_1 = &fd.source | &(&rel - &rel_0); let FDs_1 = project_to(&rel_1, &FDs); candidates.push((rel_0, FDs_0)); candidates.push((rel_1, FDs_1)); } else { bcnf.push(rel); } } bcnf } pub struct NumberOfAttrs(u32); impl NumberOfAttrs { pub fn new(n: u32) -> Self { Self(n) } } impl Distribution<FD> for NumberOfAttrs { fn sample<R: rand::Rng +?Sized>(&self, rng: &mut R) -> FD { let n = self.0; let mut source = vec![]; let mut target = vec![]; for i in 0..n { if rng.gen_bool(0.5) { source.push(i); } if rng.gen_bool(0.5) { target.push(i); } } if source.is_empty() { source.push(rng.gen_range(0..n)); } if target.is_empty() { target.push(rng.gen_range(0..n)); } FD::new(source.into(), target.into()) } } #[cfg(test)] mod test { use super::*; #[test] fn closure_test() { let mut reg = NameRegister::new(); let A = reg.register("A"); let B = reg.register("B"); let C = reg.register("C"); let D = reg.register("D"); let E = reg.register("E"); let _F = reg.register("F"); let dependencies = parse_FDs(&reg, &["A, B -> C", "B, C -> A, D", "D -> E", "C, F -> B"]); assert_eq!( &*closure_of(&attrs(&[A, B]), &dependencies), &[A, B, C, D, E] ); assert_eq!(&*closure_of(&attrs(&[D]), &dependencies), &[D, E]); } #[test] fn format_test() { let mut reg = NameRegister::new(); reg.register("A"); reg.register("B"); reg.register("C"); reg.register("D"); let fd = reg.parse_fd("B, A -> D, C").unwrap(); assert_eq!(format!("{}", fd.with_names(&reg)), "A, B -> C, D"); } #[test] fn project_test() { let mut reg = NameRegister::new(); let A = reg.register("A"); let _B = reg.register("B"); let C = reg.register("C"); let D = reg.register("D"); let FDs = parse_FDs(&reg, &["A -> B", "B -> C", "C -> D"]); let projection = project_to(&[A, C, D].iter().copied().collect(), &FDs); assert_eq!(projection.len(), 2); assert!(projection.iter().all(|fd| fd.target.len() == 1)); assert!(implies(&projection, &reg.parse_fd("A -> C, D").unwrap())); assert!(implies(&projection, &reg.parse_fd("C -> D").unwrap())); } #[test] fn violation_test() { let mut reg = NameRegister::new(); let _title = reg.register("title"); let _year = reg.register("year"); let _studio_name = reg.register("studio_name"); let _president = reg.register("president"); let FDs = parse_FDs( &reg, &["title, year -> studio_name", "studio_name -> president"], ); assert_eq!(violation(&reg.attrs(), &FDs), Some(&FDs[1])); } #[test] fn bcnf_test() { let mut reg = NameRegister::new(); let title = reg.register("title"); let year = reg.register("year"); let studio_name = reg.register("studio_name"); let president = reg.register("president"); let pres_addr = reg.register("pres_addr"); let FDs = parse_FDs( &reg, &[ "title, year -> studio_name", "studio_name -> president", "president -> pres_addr", ], ); let decomposition = bcnf_decomposition(&reg.attrs(), &FDs); assert_eq!(decomposition.len(), 3); assert!(decomposition.contains(&attrs(&[title, year, studio_name]))); assert!(decomposition.contains(&attrs(&[studio_name, president]))); assert!(decomposition.contains(&attrs(&[president, pres_addr]))); } }
pub fn bcnf_decomposition(rel: &Attrs, FDs: &[FD]) -> Vec<Attrs> { let rel: Attrs = rel.clone(); let mut candidates: Vec<(Attrs, Vec<FD>)> = vec![(rel, FDs.to_vec())]; let mut bcnf: Vec<Attrs> = vec![];
random_line_split
lib.rs
#![allow(clippy::many_single_char_names, non_snake_case)] pub mod chase; pub mod mvd; mod parser; mod sorted_uvec; use itertools::Itertools; use mvd::MVD; use rand::prelude::Distribution; use sorted_uvec::SortedUVec; use std::{borrow::Borrow, mem, ops::Not}; use std::{ collections::HashMap, fmt::{self, Display, Formatter}, }; pub type Attrs = SortedUVec<u32>; impl Attrs { pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> AttrWithNames<'a> { AttrWithNames { attrs: self, register, } } pub fn keys(&self, FDs: &[FD]) -> Vec<Attrs> { all_subsets_of(self) .filter(|sub| categorize(sub, self, FDs) == Category::Key) .collect() } } pub fn attrs<I, J>(iter: I) -> Attrs where I: IntoIterator<Item = J>, J: Borrow<u32>, { Attrs::new(iter.into_iter().map(|v| *v.borrow())) } #[derive(PartialEq, Eq, Clone, Debug, Default)] pub struct FD { pub source: Attrs, pub target: Attrs, } impl FD { pub fn new(source: Attrs, target: Attrs) -> Self { let target = &target - &source; Self { source, target } } pub fn is_deformed(&self) -> bool { self.source.is_empty() || self.target.is_empty() } pub fn split(&self) -> impl Iterator<Item = FD> + '_
pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> DepWithNames<'a> { DepWithNames { arrow: "->", source: &self.source, target: &self.target, register, } } } pub struct DepWithNames<'a> { arrow: &'a str, source: &'a Attrs, target: &'a Attrs, register: &'a NameRegister, } impl Display for DepWithNames<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let sep_by_comma = |list: &[u32], f: &mut Formatter| -> fmt::Result { let mut first = true; for &v in list { if!first { write!(f, ", ")?; } first = false; write!(f, "{}", self.register.name(v).unwrap_or("{Unnamed}"))?; } Ok(()) }; sep_by_comma(&*self.source, f)?; write!(f, " {} ", self.arrow)?; sep_by_comma(&*self.target, f)?; Ok(()) } } pub fn closure_of(attrs: &Attrs, dependencies: &[FD]) -> Attrs { let mut closure = attrs.clone(); let mut size = closure.len(); loop { for fd in dependencies { if fd.source.is_subset(&closure) { closure.extend(fd.target.iter().copied()); } } if closure.len() > size { size = closure.len(); } else { break; } } closure } #[derive(Debug, PartialEq)] pub enum Category { Nonkey, Key, Superkey, } impl Display for Category { fn fmt(&self, f: &mut Formatter) -> fmt::Result { <Self as fmt::Debug>::fmt(self, f) } } pub fn categorize(sub: &Attrs, rel: &Attrs, FDs: &[FD]) -> Category { let closure = closure_of(sub, FDs); if!closure.is_superset(&rel) { return Category::Nonkey; } let has_subkey = sub .iter() .map(|v| { let mut shirnked = sub.clone(); shirnked.remove(v); shirnked }) .any(|attrs| closure_of(&attrs, FDs).is_superset(&rel)); if has_subkey { Category::Superkey } else { Category::Key } } #[derive(Default)] pub struct NameRegister { cnt: u32, name_idx: HashMap<String, u32>, idx_name: HashMap<u32, String>, } impl NameRegister { pub fn new() -> Self { Self::default() } pub fn resolve(&self, name: &str) -> Option<u32> { self.name_idx.get(name).copied() } pub fn name(&self, idx: u32) -> Option<&str> { self.idx_name.get(&idx).map(|s| s.as_str()) } pub fn attrs(&self) -> Attrs { (0..self.cnt).collect() } pub fn categorize(&self, attrs: &Attrs, dependencies: &[FD]) -> Category { categorize(attrs, &self.attrs(), dependencies) } pub fn register(&mut self, name: &str) -> u32 { self.resolve(name).unwrap_or_else(|| { let key = self.cnt; self.cnt += 1; self.name_idx.insert(name.to_string(), key); self.idx_name.insert(key, name.to_string()); key }) } pub fn parse_fd(&self, input: &str) -> Option<FD> { let (_, (source, target)) = parser::fd(input).ok()?; let source: Attrs = source .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; let target: Attrs = target .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; Some(FD::new(source, target)) } pub fn parse_mvd(&self, input: &str) -> Option<MVD> { let (_, (source, target)) = parser::mvd(input).ok()?; let source: Attrs = source .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; let target: Attrs = target .iter() .map(|v| self.resolve(v)) .collect::<Option<_>>()?; Some(MVD::new(source, target)) } pub fn cnt(&self) -> u32 { self.cnt } } pub struct AttrWithNames<'a> { attrs: &'a [u32], register: &'a NameRegister, } impl<'a> Display for AttrWithNames<'a> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut is_first = true; write!(f, "{{ ")?; for &attr in self.attrs { if!is_first { write!(f, ", ")?; } is_first = false; f.write_str(self.register.name(attr).unwrap_or("{Unnamed}"))?; } write!(f, " }}")?; Ok(()) } } pub fn parse_FDs(register: &NameRegister, FDs: &[&str]) -> Vec<FD> { FDs.iter() .map(|fd| register.parse_fd(fd).unwrap()) .collect() } pub fn parse_MVDs(register: &NameRegister, MVDs: &[&str]) -> Vec<MVD> { MVDs.iter() .map(|mvd| register.parse_mvd(mvd).unwrap()) .collect() } pub fn implies(FDs: &[FD], fd: &FD) -> bool { closure_of(&fd.source, FDs).is_superset(&fd.target) } pub fn all_subsets_of(attrs: &[u32]) -> impl Iterator<Item = Attrs> + '_ { (0..=attrs.len()) .flat_map(move |k| attrs.iter().copied().combinations(k)) .map(From::from) } pub fn project_to(attrs: &Attrs, FDs: &[FD]) -> Vec<FD> { let FDs: Vec<FD> = all_subsets_of(&*attrs) .map(|selected| { let closure = closure_of(&selected, FDs); FD::new(selected, &closure & attrs) }) .filter(|fd|!fd.is_deformed()) .collect(); minify(&FDs) } pub fn is_minimal_basis(FDs: &[FD]) -> bool { let mut FDs: Vec<_> = FDs.iter().flat_map(|fd| fd.split()).collect(); !remove_implied(&mut FDs) } pub fn minify(FDs: &[FD]) -> Vec<FD> { let mut FDs: Vec<_> = FDs.iter().flat_map(|fd| fd.split()).collect(); loop { let refined = remove_implied(&mut FDs); let shrinked = remove_redundant(&mut FDs); if!(refined || shrinked) { break; } } FDs.sort_by(|a, b| a.source.cmp(&b.source)); FDs } fn remove_implied(FDs: &mut Vec<FD>) -> bool { for i in 0..FDs.len() { let FD = mem::take(&mut FDs[i]); if implies(FDs, &FD) { FDs.swap_remove(i); return true; } FDs[i] = FD; } false } fn remove_redundant(FDs: &mut [FD]) -> bool { for i in 0..FDs.len() { let FD = &FDs[i]; for v in &FD.source { let mut shrinked = FD.clone(); shrinked.source.remove(v); if implies(FDs, &shrinked) { FDs[i] = shrinked; return true; } } } false } pub fn all_violations<'a>(rel: &'a Attrs, FDs: &'a [FD]) -> impl Iterator<Item = &'a FD> + 'a { FDs.iter() .filter(move |fd| closure_of(&fd.source, FDs).is_superset(rel).not()) } fn violation<'a>(rel: &'a Attrs, FDs: &'a [FD]) -> Option<&'a FD> { all_violations(rel, FDs).next() } pub fn is_bcnf_violation(rel: &Attrs, FDs: &[FD]) -> bool { violation(rel, FDs).is_some() } pub fn bcnf_decomposition(rel: &Attrs, FDs: &[FD]) -> Vec<Attrs> { let rel: Attrs = rel.clone(); let mut candidates: Vec<(Attrs, Vec<FD>)> = vec![(rel, FDs.to_vec())]; let mut bcnf: Vec<Attrs> = vec![]; while let Some((rel, FDs)) = candidates.pop() { // every 2-attribute relation is in BCNF if rel.len() <= 2 { bcnf.push(rel); continue; } if let Some(fd) = violation(&rel, &FDs) { let rel_0 = closure_of(&fd.source, &FDs); let FDs_0 = project_to(&rel_0, &FDs); let rel_1 = &fd.source | &(&rel - &rel_0); let FDs_1 = project_to(&rel_1, &FDs); candidates.push((rel_0, FDs_0)); candidates.push((rel_1, FDs_1)); } else { bcnf.push(rel); } } bcnf } pub struct NumberOfAttrs(u32); impl NumberOfAttrs { pub fn new(n: u32) -> Self { Self(n) } } impl Distribution<FD> for NumberOfAttrs { fn sample<R: rand::Rng +?Sized>(&self, rng: &mut R) -> FD { let n = self.0; let mut source = vec![]; let mut target = vec![]; for i in 0..n { if rng.gen_bool(0.5) { source.push(i); } if rng.gen_bool(0.5) { target.push(i); } } if source.is_empty() { source.push(rng.gen_range(0..n)); } if target.is_empty() { target.push(rng.gen_range(0..n)); } FD::new(source.into(), target.into()) } } #[cfg(test)] mod test { use super::*; #[test] fn closure_test() { let mut reg = NameRegister::new(); let A = reg.register("A"); let B = reg.register("B"); let C = reg.register("C"); let D = reg.register("D"); let E = reg.register("E"); let _F = reg.register("F"); let dependencies = parse_FDs(&reg, &["A, B -> C", "B, C -> A, D", "D -> E", "C, F -> B"]); assert_eq!( &*closure_of(&attrs(&[A, B]), &dependencies), &[A, B, C, D, E] ); assert_eq!(&*closure_of(&attrs(&[D]), &dependencies), &[D, E]); } #[test] fn format_test() { let mut reg = NameRegister::new(); reg.register("A"); reg.register("B"); reg.register("C"); reg.register("D"); let fd = reg.parse_fd("B, A -> D, C").unwrap(); assert_eq!(format!("{}", fd.with_names(&reg)), "A, B -> C, D"); } #[test] fn project_test() { let mut reg = NameRegister::new(); let A = reg.register("A"); let _B = reg.register("B"); let C = reg.register("C"); let D = reg.register("D"); let FDs = parse_FDs(&reg, &["A -> B", "B -> C", "C -> D"]); let projection = project_to(&[A, C, D].iter().copied().collect(), &FDs); assert_eq!(projection.len(), 2); assert!(projection.iter().all(|fd| fd.target.len() == 1)); assert!(implies(&projection, &reg.parse_fd("A -> C, D").unwrap())); assert!(implies(&projection, &reg.parse_fd("C -> D").unwrap())); } #[test] fn violation_test() { let mut reg = NameRegister::new(); let _title = reg.register("title"); let _year = reg.register("year"); let _studio_name = reg.register("studio_name"); let _president = reg.register("president"); let FDs = parse_FDs( &reg, &["title, year -> studio_name", "studio_name -> president"], ); assert_eq!(violation(&reg.attrs(), &FDs), Some(&FDs[1])); } #[test] fn bcnf_test() { let mut reg = NameRegister::new(); let title = reg.register("title"); let year = reg.register("year"); let studio_name = reg.register("studio_name"); let president = reg.register("president"); let pres_addr = reg.register("pres_addr"); let FDs = parse_FDs( &reg, &[ "title, year -> studio_name", "studio_name -> president", "president -> pres_addr", ], ); let decomposition = bcnf_decomposition(&reg.attrs(), &FDs); assert_eq!(decomposition.len(), 3); assert!(decomposition.contains(&attrs(&[title, year, studio_name]))); assert!(decomposition.contains(&attrs(&[studio_name, president]))); assert!(decomposition.contains(&attrs(&[president, pres_addr]))); } }
{ self.target .iter() .map(move |&v| FD::new(self.source.clone(), attrs(&[v]))) }
identifier_body
response.rs
// rust imports use std::io::Read; use std::ffi::OsStr; use std::path::{PathBuf, Path}; use std::fs::{self, File}; use std::collections::HashMap; // 3rd-party imports use rusqlite::Connection; use rusqlite::types::ToSql; use hyper::http::h1::HttpReader; use hyper::buffer::BufReader; use hyper::net::NetworkStream; use hyper::header::{Headers, ContentType}; use hyper::mime::{Mime, TopLevel, SubLevel}; use multipart::server::{Multipart, Entries, SaveResult}; use url::percent_encoding::percent_decode; use mime_types; use csv; use chrono::naive::date::NaiveDate; use chrono::Datelike; use serde::ser::Serialize; use serde_json; // local imports use route::{Route, HumanError, APIError}; use database::Database; // statics lazy_static! { static ref MIME_TYPES: mime_types::Types = mime_types::Types::new().unwrap(); } // enums pub enum Component { Home, NotFound, } #[derive(Serialize, Debug)] pub struct JSONResponse { pub error: Option<String>, pub payload: Option<serde_json::Value>, } impl JSONResponse { fn error(reason: Option<String>) -> Self { JSONResponse { error: reason, payload: None, } } fn payload<T: Serialize>(value: T) -> Self { use serde_json::to_value; JSONResponse { error: None, payload: Some(to_value(value).unwrap()), } } } pub enum AppResponse { Component(Component), Asset(ContentType, Vec<u8> /* content */), MethodNotAllowed, NotFound, BadRequest, InternalServerError, JSONResponse(JSONResponse), } impl AppResponse { pub fn process(db_conn: Database, route: Route, headers: Headers, http_reader: HttpReader<&mut BufReader<&mut NetworkStream>>) -> Self { match route { Route::Home => AppResponse::Component(Component::Home), Route::FileUpload => handle_file_upload(db_conn, headers, http_reader), Route::Asset(path_to_asset) => handle_asset(path_to_asset), Route::HumanError(human_error) => { match human_error { HumanError::NotFound => AppResponse::Component(Component::NotFound), } } Route::APIError(api_error) => { match api_error { APIError::MethodNotAllowed => AppResponse::MethodNotAllowed, APIError::NotFound => AppResponse::NotFound, } } } } } fn handle_asset(path_to_asset: String) -> AppResponse { #[inline] fn decode_percents(string: &OsStr) -> String { let string = format!("{}", string.to_string_lossy()); format!("{}", percent_decode(string.as_bytes()).decode_utf8_lossy()) } // TODO: inlined resources here // URL decode let decoded_req_path = Path::new(&path_to_asset).iter().map(decode_percents); let starts_with = match Path::new("./assets/").to_path_buf().canonicalize() { Err(_) => { return AppResponse::Component(Component::NotFound); } Ok(x) => x, }; let mut req_path = starts_with.clone(); req_path.extend(decoded_req_path); let req_path: PathBuf = req_path; // TODO: this is a security bottle-neck let req_path = match req_path.canonicalize() { Err(_) => { return AppResponse::Component(Component::NotFound); } Ok(req_path) => { if!req_path.starts_with(starts_with.as_path()) { return AppResponse::Component(Component::NotFound); } req_path } }; match fs::metadata(&req_path) { Ok(metadata) => { if!metadata.is_file() { return AppResponse::Component(Component::NotFound); } // TODO: better way? let path_str = format!("{}", &req_path.to_string_lossy()); // Set the content type based on the file extension let mime_str = MIME_TYPES.mime_for_path(req_path.as_path()); let mut content_type = ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![])); let _ = mime_str.parse().map(|mime: Mime| { content_type = ContentType(mime); }); let mut file = File::open(req_path) .ok() .expect(&format!("No such file: {:?}", path_str)); let mut content = Vec::new(); file.read_to_end(&mut content).unwrap(); return AppResponse::Asset(content_type, content); } Err(_err) => { return AppResponse::Component(Component::NotFound); } } } fn handle_file_upload(db_conn: Database, headers: Headers, http_reader: HttpReader<&mut BufReader<&mut NetworkStream>>) -> AppResponse { match process_multipart(headers, http_reader) { None => AppResponse::BadRequest, Some(mut multipart) => { match multipart.save().temp() { SaveResult::Full(entries) => process_entries(db_conn, entries), SaveResult::Partial(_entries, error) => { println!("Errors saving multipart:\n{:?}", error); // TODO: fix // process_entries(entries.into()) AppResponse::BadRequest } SaveResult::Error(error) => { println!("Errors saving multipart:\n{:?}", error); // Err(error) AppResponse::BadRequest } } } } } fn process_entries(db_conn: Database, entries: Entries) -> AppResponse { let files = match entries.files.get("uploads[]") { Some(files) => { if files.len() <= 0 { return AppResponse::BadRequest; } files } None => { return AppResponse::BadRequest; } }; let mut expense_tracker = ExpenseTracker::new(); let mut records = vec![]; for file in files { let mut reader = match csv::Reader::from_file(file.path.clone()) { Ok(reader) => reader.has_headers(true), Err(error) => { // TODO: error println!("error: {}", error); return AppResponse::InternalServerError; } }; for record in reader.decode() { let (date, category, employee_name, employee_address, expense_description, pre_tax_amount, tax_name, tax_amount): (String, String, String, String, String, String, String, String) = match record { Ok(x) => x, Err(_) => { return AppResponse::BadRequest; } }; let pre_tax_amount: f64 = { let pre_tax_amount = pre_tax_amount.trim().replace(",", ""); match pre_tax_amount.parse::<f64>() { Ok(x) => x, Err(_) => { return AppResponse::BadRequest; } } }; let tax_amount: f64 = { let tax_amount = tax_amount.trim().replace(",", ""); match tax_amount.parse::<f64>() { Ok(x) => x, Err(_) => { return AppResponse::BadRequest; } } }; let new_date = match NaiveDate::parse_from_str(&date, "%_m/%e/%Y") { Ok(x) => x, Err(_) => { return AppResponse::BadRequest; } }; let record = Record(date, category, employee_name, employee_address, expense_description, pre_tax_amount, tax_name, tax_amount); records.push(record); expense_tracker.add(new_date, pre_tax_amount + tax_amount); } } add_to_database(db_conn, records); return AppResponse::JSONResponse(JSONResponse::payload(expense_tracker)); } fn add_to_database(db_connnection: Database, records: Vec<Record>) { for record in records { let Record(date, category, employee_name, employee_address, expense_description, pre_tax_amount, tax_name, tax_amount) = record; let query = format!(" INSERT INTO ExpenseHistory(date, category, \ employee_name, employee_address, expense_description, \ pre_tax_amount, tax_name, tax_amount) VALUES (:date, \ :category, :employee_name, :employee_address, :expense_description, \ :pre_tax_amount, :tax_name, :tax_amount); "); let params: &[(&str, &ToSql)] = &[(":date", &date), (":category", &category), (":employee_name", &employee_name), (":employee_address", &employee_address), (":expense_description", &expense_description), (":pre_tax_amount", &pre_tax_amount), (":tax_name", &tax_name), (":tax_amount", &tax_amount)]; db_write_lock!(db_conn; db_connnection.clone()); let db_conn: &Connection = db_conn; match db_conn.execute_named(&query, params) { Err(sqlite_error) => { panic!("{:?}", sqlite_error); } _ => { /* query sucessfully executed */ } } } } fn process_multipart<R: Read>(headers: Headers, http_reader: R) -> Option<Multipart<R>> { let boundary = headers.get::<ContentType>().and_then(|ct| { use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; let ContentType(ref mime) = *ct; let params = match *mime { Mime(TopLevel::Multipart, SubLevel::FormData, ref params) => params, _ => return None, }; params.iter() .find(|&&(ref name, _)| match *name { Attr::Boundary => true, _ => false, }) .and_then(|&(_, ref val)| match *val { Value::Ext(ref val) => Some(&**val), _ => None, }) }); match boundary.map(String::from) { Some(boundary) => Some(Multipart::with_body(http_reader, boundary)), None => None, } } #[derive(Eq, PartialEq, Hash, Serialize)] enum Month { January, February, March, April, May, June, July, August, September, October, November, December, } #[derive(Serialize)] struct ExpenseTracker(HashMap<Month, f64>); impl ExpenseTracker { fn
() -> Self { ExpenseTracker(HashMap::new()) } fn add(&mut self, date: NaiveDate, expenses: f64) { let month = match date.month() { 1 => Month::January, 2 => Month::February, 3 => Month::March, 4 => Month::April, 5 => Month::May, 6 => Month::June, 7 => Month::July, 8 => Month::August, 9 => Month::September, 10 => Month::October, 11 => Month::November, 12 => Month::December, _ => unreachable!(), }; if self.0.contains_key(&month) { let entry = self.0.get_mut(&month).unwrap(); *entry = *entry + expenses; return; } self.0.insert(month, expenses); } } struct Record(String, String, String, String, String, f64, String, f64);
new
identifier_name
response.rs
// rust imports use std::io::Read; use std::ffi::OsStr; use std::path::{PathBuf, Path}; use std::fs::{self, File}; use std::collections::HashMap; // 3rd-party imports use rusqlite::Connection; use rusqlite::types::ToSql; use hyper::http::h1::HttpReader; use hyper::buffer::BufReader; use hyper::net::NetworkStream; use hyper::header::{Headers, ContentType}; use hyper::mime::{Mime, TopLevel, SubLevel}; use multipart::server::{Multipart, Entries, SaveResult}; use url::percent_encoding::percent_decode; use mime_types; use csv; use chrono::naive::date::NaiveDate; use chrono::Datelike; use serde::ser::Serialize; use serde_json; // local imports use route::{Route, HumanError, APIError}; use database::Database; // statics lazy_static! { static ref MIME_TYPES: mime_types::Types = mime_types::Types::new().unwrap(); } // enums pub enum Component { Home, NotFound, } #[derive(Serialize, Debug)] pub struct JSONResponse { pub error: Option<String>, pub payload: Option<serde_json::Value>, } impl JSONResponse { fn error(reason: Option<String>) -> Self { JSONResponse { error: reason, payload: None, } } fn payload<T: Serialize>(value: T) -> Self { use serde_json::to_value; JSONResponse { error: None, payload: Some(to_value(value).unwrap()), } } } pub enum AppResponse { Component(Component), Asset(ContentType, Vec<u8> /* content */), MethodNotAllowed, NotFound, BadRequest, InternalServerError, JSONResponse(JSONResponse), } impl AppResponse { pub fn process(db_conn: Database, route: Route, headers: Headers, http_reader: HttpReader<&mut BufReader<&mut NetworkStream>>) -> Self { match route { Route::Home => AppResponse::Component(Component::Home), Route::FileUpload => handle_file_upload(db_conn, headers, http_reader), Route::Asset(path_to_asset) => handle_asset(path_to_asset), Route::HumanError(human_error) => { match human_error { HumanError::NotFound => AppResponse::Component(Component::NotFound), } } Route::APIError(api_error) => { match api_error { APIError::MethodNotAllowed => AppResponse::MethodNotAllowed, APIError::NotFound => AppResponse::NotFound, } } } } } fn handle_asset(path_to_asset: String) -> AppResponse { #[inline] fn decode_percents(string: &OsStr) -> String { let string = format!("{}", string.to_string_lossy()); format!("{}", percent_decode(string.as_bytes()).decode_utf8_lossy()) } // TODO: inlined resources here // URL decode let decoded_req_path = Path::new(&path_to_asset).iter().map(decode_percents); let starts_with = match Path::new("./assets/").to_path_buf().canonicalize() { Err(_) => { return AppResponse::Component(Component::NotFound); } Ok(x) => x, }; let mut req_path = starts_with.clone(); req_path.extend(decoded_req_path); let req_path: PathBuf = req_path; // TODO: this is a security bottle-neck let req_path = match req_path.canonicalize() { Err(_) => { return AppResponse::Component(Component::NotFound); } Ok(req_path) => { if!req_path.starts_with(starts_with.as_path()) { return AppResponse::Component(Component::NotFound); } req_path } }; match fs::metadata(&req_path) { Ok(metadata) => { if!metadata.is_file() { return AppResponse::Component(Component::NotFound); } // TODO: better way? let path_str = format!("{}", &req_path.to_string_lossy()); // Set the content type based on the file extension let mime_str = MIME_TYPES.mime_for_path(req_path.as_path()); let mut content_type = ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![])); let _ = mime_str.parse().map(|mime: Mime| { content_type = ContentType(mime); }); let mut file = File::open(req_path) .ok() .expect(&format!("No such file: {:?}", path_str)); let mut content = Vec::new(); file.read_to_end(&mut content).unwrap(); return AppResponse::Asset(content_type, content); } Err(_err) => { return AppResponse::Component(Component::NotFound); } } } fn handle_file_upload(db_conn: Database, headers: Headers, http_reader: HttpReader<&mut BufReader<&mut NetworkStream>>) -> AppResponse { match process_multipart(headers, http_reader) { None => AppResponse::BadRequest, Some(mut multipart) => { match multipart.save().temp() { SaveResult::Full(entries) => process_entries(db_conn, entries), SaveResult::Partial(_entries, error) => { println!("Errors saving multipart:\n{:?}", error); // TODO: fix // process_entries(entries.into()) AppResponse::BadRequest } SaveResult::Error(error) => { println!("Errors saving multipart:\n{:?}", error); // Err(error) AppResponse::BadRequest } } } } } fn process_entries(db_conn: Database, entries: Entries) -> AppResponse { let files = match entries.files.get("uploads[]") { Some(files) => { if files.len() <= 0 { return AppResponse::BadRequest; } files } None => { return AppResponse::BadRequest; } }; let mut expense_tracker = ExpenseTracker::new(); let mut records = vec![]; for file in files { let mut reader = match csv::Reader::from_file(file.path.clone()) { Ok(reader) => reader.has_headers(true), Err(error) => { // TODO: error println!("error: {}", error); return AppResponse::InternalServerError; } }; for record in reader.decode() { let (date, category, employee_name, employee_address, expense_description, pre_tax_amount, tax_name, tax_amount): (String, String, String, String, String, String, String, String) = match record { Ok(x) => x, Err(_) => { return AppResponse::BadRequest; } }; let pre_tax_amount: f64 = { let pre_tax_amount = pre_tax_amount.trim().replace(",", ""); match pre_tax_amount.parse::<f64>() { Ok(x) => x, Err(_) => { return AppResponse::BadRequest; } } }; let tax_amount: f64 = { let tax_amount = tax_amount.trim().replace(",", ""); match tax_amount.parse::<f64>() { Ok(x) => x, Err(_) => { return AppResponse::BadRequest; } } }; let new_date = match NaiveDate::parse_from_str(&date, "%_m/%e/%Y") { Ok(x) => x, Err(_) => { return AppResponse::BadRequest; } }; let record = Record(date, category, employee_name, employee_address, expense_description, pre_tax_amount, tax_name, tax_amount); records.push(record); expense_tracker.add(new_date, pre_tax_amount + tax_amount); } } add_to_database(db_conn, records); return AppResponse::JSONResponse(JSONResponse::payload(expense_tracker)); } fn add_to_database(db_connnection: Database, records: Vec<Record>) { for record in records { let Record(date, category, employee_name, employee_address, expense_description, pre_tax_amount, tax_name, tax_amount) = record; let query = format!(" INSERT INTO ExpenseHistory(date, category, \ employee_name, employee_address, expense_description, \ pre_tax_amount, tax_name, tax_amount) VALUES (:date, \ :category, :employee_name, :employee_address, :expense_description, \ :pre_tax_amount, :tax_name, :tax_amount); "); let params: &[(&str, &ToSql)] = &[(":date", &date), (":category", &category), (":employee_name", &employee_name), (":employee_address", &employee_address), (":expense_description", &expense_description), (":pre_tax_amount", &pre_tax_amount), (":tax_name", &tax_name), (":tax_amount", &tax_amount)]; db_write_lock!(db_conn; db_connnection.clone()); let db_conn: &Connection = db_conn; match db_conn.execute_named(&query, params) { Err(sqlite_error) => { panic!("{:?}", sqlite_error); } _ => { /* query sucessfully executed */
} } fn process_multipart<R: Read>(headers: Headers, http_reader: R) -> Option<Multipart<R>> { let boundary = headers.get::<ContentType>().and_then(|ct| { use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; let ContentType(ref mime) = *ct; let params = match *mime { Mime(TopLevel::Multipart, SubLevel::FormData, ref params) => params, _ => return None, }; params.iter() .find(|&&(ref name, _)| match *name { Attr::Boundary => true, _ => false, }) .and_then(|&(_, ref val)| match *val { Value::Ext(ref val) => Some(&**val), _ => None, }) }); match boundary.map(String::from) { Some(boundary) => Some(Multipart::with_body(http_reader, boundary)), None => None, } } #[derive(Eq, PartialEq, Hash, Serialize)] enum Month { January, February, March, April, May, June, July, August, September, October, November, December, } #[derive(Serialize)] struct ExpenseTracker(HashMap<Month, f64>); impl ExpenseTracker { fn new() -> Self { ExpenseTracker(HashMap::new()) } fn add(&mut self, date: NaiveDate, expenses: f64) { let month = match date.month() { 1 => Month::January, 2 => Month::February, 3 => Month::March, 4 => Month::April, 5 => Month::May, 6 => Month::June, 7 => Month::July, 8 => Month::August, 9 => Month::September, 10 => Month::October, 11 => Month::November, 12 => Month::December, _ => unreachable!(), }; if self.0.contains_key(&month) { let entry = self.0.get_mut(&month).unwrap(); *entry = *entry + expenses; return; } self.0.insert(month, expenses); } } struct Record(String, String, String, String, String, f64, String, f64);
} }
random_line_split
read_archive.rs
//! read-archive use backup_cli::storage::{FileHandle, FileHandleRef}; use libra_types::access_path::AccessPath; use libra_types::account_config::AccountResource; use libra_types::account_state::AccountState; use libra_types::write_set::{WriteOp, WriteSetMut}; use move_core_types::move_resource::MoveResource; use ol_fixtures::get_persona_mnem; use ol_keys::wallet::get_account_from_mnem; use serde::de::DeserializeOwned; use std::convert::TryFrom; use std::path::PathBuf; use std::fs::File; use std::io::Read; use libra_config::utils::get_available_port; use libra_crypto::HashValue; use libra_types::{ account_state_blob::AccountStateBlob, ledger_info::LedgerInfoWithSignatures, proof::TransactionInfoWithProof, account_config::BalanceResource, validator_config::ValidatorConfigResource, }; use libra_types::{ transaction::{Transaction, WriteSetPayload}, trusted_state::TrustedState, waypoint::Waypoint, }; use ol_types::miner_state::MinerStateResource; use std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, sync::Arc, }; use backup_cli::backup_types::state_snapshot::manifest::StateSnapshotBackup; use anyhow::{bail, ensure, Error, Result}; use tokio::{fs::OpenOptions, io::AsyncRead}; use libra_temppath::TempPath; use libradb::LibraDB; use backup_cli::utils::read_record_bytes::ReadRecordBytes; use backup_service::start_backup_service; use tokio::runtime::Runtime; use executor::db_bootstrapper::{generate_waypoint, maybe_bootstrap}; use libra_vm::LibraVM; use storage_interface::DbReaderWriter; use crate::generate_genesis; use crate::recover::{accounts_into_recovery, LegacyRecovery}; fn get_runtime() -> (Runtime, u16) { let port = get_available_port(); let path = TempPath::new(); let rt = start_backup_service( SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port), Arc::new(LibraDB::new_for_test(&path)), ); (rt, port) } async fn open_for_read(file_handle: &FileHandleRef) -> Result<Box<dyn AsyncRead + Send + Unpin>> { let file = OpenOptions::new().read(true).open(file_handle).await?; Ok(Box::new(file)) } fn read_from_file(path: &str) -> Result<Vec<u8>> { let mut data = Vec::<u8>::new(); let mut f = File::open(path).expect("Unable to open file"); f.read_to_end(&mut data).expect("Unable to read data"); Ok(data) } fn read_from_json(path: &PathBuf) -> Result<StateSnapshotBackup> { let config = std::fs::read_to_string(path)?; let map: StateSnapshotBackup = serde_json::from_str(&config)?; Ok(map) } fn load_lcs_file<T: DeserializeOwned>(file_handle: &str) -> Result<T> { let x = read_from_file(&file_handle)?; Ok(lcs::from_bytes(&x)?) } async fn read_account_state_chunk( file_handle: FileHandle, archive_path: &PathBuf, ) -> Result<Vec<(HashValue, AccountStateBlob)>> { let full_handle = archive_path.parent().unwrap().join(file_handle); let handle_str = full_handle.to_str().unwrap(); let mut file = open_for_read(handle_str).await?; let mut chunk = vec![]; while let Some(record_bytes) = file.read_record_bytes().await? { chunk.push(lcs::from_bytes(&record_bytes)?); } Ok(chunk) } /// take an archive file path and parse into a writeset pub async fn archive_into_swarm_writeset( archive_path: PathBuf, ) -> Result<WriteSetMut, Error> { let backup = read_from_json(&archive_path)?; let account_blobs = accounts_from_snapshot_backup(backup, &archive_path).await?; accounts_into_writeset_swarm(&account_blobs) } /// take an archive file path and parse into a writeset pub async fn archive_into_recovery(archive_path: &PathBuf) -> Result<Vec<LegacyRecovery>, Error> { let manifest_json = archive_path.join("state.manifest"); let backup = read_from_json(&manifest_json)?; let account_blobs = accounts_from_snapshot_backup(backup, archive_path).await?; let r = accounts_into_recovery(&account_blobs)?; Ok(r) } /// Tokio async parsing of state snapshot into blob async fn accounts_from_snapshot_backup( manifest: StateSnapshotBackup, archive_path: &PathBuf ) -> Result<Vec<AccountStateBlob>> { // parse AccountStateBlob from chunks of the archive let mut account_state_blobs: Vec<AccountStateBlob> = Vec::new(); for chunk in manifest.chunks { let blobs = read_account_state_chunk(chunk.blobs, archive_path).await?; // println!("{:?}", blobs); for (_key, blob) in blobs { account_state_blobs.push(blob) } } Ok(account_state_blobs) } fn get_alice_authkey_for_swarm() -> Vec<u8> { let mnemonic_string = get_persona_mnem("alice"); let account_details = get_account_from_mnem(mnemonic_string); account_details.0.to_vec() } /// cases that we need to create a genesis from backup. pub enum GenesisCase { /// a network upgrade or fork Fork, /// simulate state in a local swarm. Test, } /// make the writeset for the genesis case. Starts with an unmodified account state and make into a writeset. pub fn accounts_into_writeset_swarm( account_state_blobs: &Vec<AccountStateBlob>, ) -> Result<WriteSetMut, Error>
/// Without modifying the data convert an AccountState struct, into a WriteSet Item which can be included in a genesis transaction. This should take all of the resources in the account. fn get_unmodified_writeset(account_state: &AccountState) -> Result<WriteSetMut, Error> { let mut ws = WriteSetMut::new(vec![]); if let Some(address) = account_state.get_account_address()? { // iterate over all the account's resources\ for (k, v) in account_state.iter() { let item_tuple = ( AccessPath::new(address, k.clone()), WriteOp::Value(v.clone()), ); // push into the writeset ws.push(item_tuple); } println!("processed account: {:?}", address); return Ok(ws); } bail!("ERROR: No address for AccountState: {:?}", account_state); } /// Returns the writeset item for replaceing an authkey on an account. This is only to be used in testing and simulation. fn authkey_rotate_change_item( account_state: &AccountState, authentication_key: Vec<u8>, ) -> Result<WriteSetMut, Error> { let mut ws = WriteSetMut::new(vec![]); if let Some(address) = account_state.get_account_address()? { // iterate over all the account's resources for (k, _v) in account_state.iter() { // if we find an AccountResource struc, which is where authkeys are kept if k.clone() == AccountResource::resource_path() { // let account_resource_option = account_state.get_account_resource()?; if let Some(account_resource) = account_state.get_account_resource()? { let account_resource_new = account_resource .clone_with_authentication_key(authentication_key.clone(), address.clone()); ws.push(( AccessPath::new(address, k.clone()), WriteOp::Value(lcs::to_bytes(&account_resource_new).unwrap()), )); } } } println!("rotate authkey for account: {:?}", address); } bail!( "ERROR: No address found at AccountState: {:?}", account_state ); } /// helper to merge writesets pub fn merge_writeset(mut left: WriteSetMut, right: WriteSetMut) -> Result<WriteSetMut, Error> { left.write_set.extend(right.write_set); Ok(left) } /// Tokio async parsing of state snapshot into blob async fn run_impl(manifest: StateSnapshotBackup, path: &PathBuf) -> Result<()> { // parse AccountStateBlob from chunks of the archive let mut account_state_blobs: Vec<AccountStateBlob> = Vec::new(); for chunk in manifest.chunks { let blobs = read_account_state_chunk(chunk.blobs, path).await?; // let proof = load_lcs_file(&chunk.proof)?; println!("{:?}", blobs); // TODO(Venkat) -> Here's the blob // println!("{:?}", proof); for (_key, blob) in blobs { account_state_blobs.push(blob) } } let genesis = vm_genesis::test_genesis_change_set_and_validators(Some(1)); let genesis_txn = Transaction::GenesisTransaction(WriteSetPayload::Direct(genesis.0)); let tmp_dir = TempPath::new(); let db_rw = DbReaderWriter::new(LibraDB::new_for_test(&tmp_dir)); // Executor won't be able to boot on empty db due to lack of StartupInfo. assert!(db_rw.reader.get_startup_info().unwrap().is_none()); // Bootstrap empty DB. let waypoint = generate_waypoint::<LibraVM>(&db_rw, &genesis_txn).expect("Should not fail."); maybe_bootstrap::<LibraVM>(&db_rw, &genesis_txn, waypoint).unwrap(); let startup_info = db_rw .reader .get_startup_info() .expect("Should not fail.") .expect("Should not be None."); assert_eq!( Waypoint::new_epoch_boundary(startup_info.latest_ledger_info.ledger_info()).unwrap(), waypoint ); let (li, epoch_change_proof, _) = db_rw.reader.get_state_proof(waypoint.version()).unwrap(); let trusted_state = TrustedState::from(waypoint); trusted_state .verify_and_ratchet(&li, &epoch_change_proof) .unwrap(); // `maybe_bootstrap()` does nothing on non-empty DB. assert!(!maybe_bootstrap::<LibraVM>(&db_rw, &genesis_txn, waypoint).unwrap()); let genesis_txn = generate_genesis::generate_genesis_from_snapshot(&account_state_blobs, &db_rw).unwrap(); generate_genesis::write_genesis_blob(genesis_txn)?; generate_genesis::test_genesis_from_blob(&account_state_blobs, db_rw)?; Ok(()) } /// given a path to state archive, produce a genesis.blob pub fn genesis_from_path(path: PathBuf) -> Result<()> { let path_man = path.clone().join("state.manifest"); dbg!(&path_man); let path_proof = path.join("state.proof"); dbg!(&path_proof); let manifest = read_from_json(&path_man).unwrap(); // Tokio runtime let (mut rt, _port) = get_runtime(); let (txn_info_with_proof, li): (TransactionInfoWithProof, LedgerInfoWithSignatures) = load_lcs_file(&path_proof.into_os_string().into_string().unwrap()).unwrap(); txn_info_with_proof.verify(li.ledger_info(), manifest.version)?; ensure!( txn_info_with_proof.transaction_info().state_root_hash() == manifest.root_hash, "Root hash mismatch with that in proof. root hash: {}, expected: {}", manifest.root_hash, txn_info_with_proof.transaction_info().state_root_hash(), ); let future = run_impl(manifest, &path); // Nothing is printed rt.block_on(future)?; Ok(()) } #[cfg(test)] #[test] fn test_main() -> Result<()> { use std::path::Path; let path = env!("CARGO_MANIFEST_DIR"); let buf = Path::new(path) .parent() .unwrap() .join("fixtures/state-snapshot/194/state_ver_74694920.0889/"); genesis_from_path(buf) } #[test] pub fn test_accounts_into_recovery() { use std::path::Path; let path = env!("CARGO_MANIFEST_DIR"); let buf = Path::new(path) .parent() .unwrap() .join("fixtures/state-snapshot/194/state_ver_74694920.0889/"); let path_man = buf.clone().join("state.manifest"); println!("Running....."); let backup = read_from_json(&path_man).unwrap(); let (mut rt, _port) = get_runtime(); let account_blobs_futures = accounts_from_snapshot_backup(backup); let account_blobs = rt.block_on(account_blobs_futures).unwrap(); let genesis_recovery_list = accounts_into_recovery(&account_blobs).unwrap(); println!("Total GenesisRecovery objects: {}", &genesis_recovery_list.len()); for blob in account_blobs { let account_state = AccountState::try_from(&blob).unwrap(); if let Some(address) = account_state.get_account_address().unwrap() { let mut address_processed = false; for gr in &genesis_recovery_list { if gr.address!= address { continue; } // iterate over all the account's resources\ for (k, v) in account_state.iter() { // extract the validator config resource if k.clone() == BalanceResource::resource_path() { match &gr.balance { Some(balance) => { if lcs::to_bytes(&balance).unwrap()!= v.clone() { panic!("Balance resource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("Balance not found"); } } } if k.clone() == ValidatorConfigResource::resource_path() { match &gr.val_cfg { Some(val_cfg) => { if lcs::to_bytes(&val_cfg).unwrap()!= v.clone() { panic!("ValidatorConfigResource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("ValidatorConfigResource not found"); } } } if k.clone() == MinerStateResource::resource_path() { match &gr.miner_state { Some(miner_state) => { if lcs::to_bytes(&miner_state).unwrap()!= v.clone() { panic!("MinerStateResource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("MinerStateResource not found"); } } } } println!("processed account: {:?}", address); address_processed = true; break; }; if!address_processed { panic!("Address not found for {} in recovery list", &address); } }; }; }
{ let mut write_set_mut = WriteSetMut::new(vec![]); for blob in account_state_blobs { let account_state = AccountState::try_from(blob)?; // TODO: borrow let clean = get_unmodified_writeset(&account_state)?; let auth = authkey_rotate_change_item(&account_state, get_alice_authkey_for_swarm())?; let merge_clean = merge_writeset(write_set_mut, clean)?; write_set_mut = merge_writeset(merge_clean, auth)?; } println!("Total accounts read: {}", &account_state_blobs.len()); Ok(write_set_mut) }
identifier_body
read_archive.rs
//! read-archive use backup_cli::storage::{FileHandle, FileHandleRef}; use libra_types::access_path::AccessPath; use libra_types::account_config::AccountResource; use libra_types::account_state::AccountState; use libra_types::write_set::{WriteOp, WriteSetMut}; use move_core_types::move_resource::MoveResource; use ol_fixtures::get_persona_mnem; use ol_keys::wallet::get_account_from_mnem; use serde::de::DeserializeOwned; use std::convert::TryFrom; use std::path::PathBuf; use std::fs::File; use std::io::Read; use libra_config::utils::get_available_port; use libra_crypto::HashValue; use libra_types::{ account_state_blob::AccountStateBlob, ledger_info::LedgerInfoWithSignatures, proof::TransactionInfoWithProof, account_config::BalanceResource, validator_config::ValidatorConfigResource, }; use libra_types::{ transaction::{Transaction, WriteSetPayload}, trusted_state::TrustedState, waypoint::Waypoint, }; use ol_types::miner_state::MinerStateResource; use std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, sync::Arc, }; use backup_cli::backup_types::state_snapshot::manifest::StateSnapshotBackup; use anyhow::{bail, ensure, Error, Result}; use tokio::{fs::OpenOptions, io::AsyncRead}; use libra_temppath::TempPath; use libradb::LibraDB; use backup_cli::utils::read_record_bytes::ReadRecordBytes; use backup_service::start_backup_service; use tokio::runtime::Runtime; use executor::db_bootstrapper::{generate_waypoint, maybe_bootstrap}; use libra_vm::LibraVM; use storage_interface::DbReaderWriter; use crate::generate_genesis; use crate::recover::{accounts_into_recovery, LegacyRecovery}; fn get_runtime() -> (Runtime, u16) { let port = get_available_port(); let path = TempPath::new(); let rt = start_backup_service( SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port), Arc::new(LibraDB::new_for_test(&path)), ); (rt, port) } async fn open_for_read(file_handle: &FileHandleRef) -> Result<Box<dyn AsyncRead + Send + Unpin>> { let file = OpenOptions::new().read(true).open(file_handle).await?; Ok(Box::new(file))
fn read_from_file(path: &str) -> Result<Vec<u8>> { let mut data = Vec::<u8>::new(); let mut f = File::open(path).expect("Unable to open file"); f.read_to_end(&mut data).expect("Unable to read data"); Ok(data) } fn read_from_json(path: &PathBuf) -> Result<StateSnapshotBackup> { let config = std::fs::read_to_string(path)?; let map: StateSnapshotBackup = serde_json::from_str(&config)?; Ok(map) } fn load_lcs_file<T: DeserializeOwned>(file_handle: &str) -> Result<T> { let x = read_from_file(&file_handle)?; Ok(lcs::from_bytes(&x)?) } async fn read_account_state_chunk( file_handle: FileHandle, archive_path: &PathBuf, ) -> Result<Vec<(HashValue, AccountStateBlob)>> { let full_handle = archive_path.parent().unwrap().join(file_handle); let handle_str = full_handle.to_str().unwrap(); let mut file = open_for_read(handle_str).await?; let mut chunk = vec![]; while let Some(record_bytes) = file.read_record_bytes().await? { chunk.push(lcs::from_bytes(&record_bytes)?); } Ok(chunk) } /// take an archive file path and parse into a writeset pub async fn archive_into_swarm_writeset( archive_path: PathBuf, ) -> Result<WriteSetMut, Error> { let backup = read_from_json(&archive_path)?; let account_blobs = accounts_from_snapshot_backup(backup, &archive_path).await?; accounts_into_writeset_swarm(&account_blobs) } /// take an archive file path and parse into a writeset pub async fn archive_into_recovery(archive_path: &PathBuf) -> Result<Vec<LegacyRecovery>, Error> { let manifest_json = archive_path.join("state.manifest"); let backup = read_from_json(&manifest_json)?; let account_blobs = accounts_from_snapshot_backup(backup, archive_path).await?; let r = accounts_into_recovery(&account_blobs)?; Ok(r) } /// Tokio async parsing of state snapshot into blob async fn accounts_from_snapshot_backup( manifest: StateSnapshotBackup, archive_path: &PathBuf ) -> Result<Vec<AccountStateBlob>> { // parse AccountStateBlob from chunks of the archive let mut account_state_blobs: Vec<AccountStateBlob> = Vec::new(); for chunk in manifest.chunks { let blobs = read_account_state_chunk(chunk.blobs, archive_path).await?; // println!("{:?}", blobs); for (_key, blob) in blobs { account_state_blobs.push(blob) } } Ok(account_state_blobs) } fn get_alice_authkey_for_swarm() -> Vec<u8> { let mnemonic_string = get_persona_mnem("alice"); let account_details = get_account_from_mnem(mnemonic_string); account_details.0.to_vec() } /// cases that we need to create a genesis from backup. pub enum GenesisCase { /// a network upgrade or fork Fork, /// simulate state in a local swarm. Test, } /// make the writeset for the genesis case. Starts with an unmodified account state and make into a writeset. pub fn accounts_into_writeset_swarm( account_state_blobs: &Vec<AccountStateBlob>, ) -> Result<WriteSetMut, Error> { let mut write_set_mut = WriteSetMut::new(vec![]); for blob in account_state_blobs { let account_state = AccountState::try_from(blob)?; // TODO: borrow let clean = get_unmodified_writeset(&account_state)?; let auth = authkey_rotate_change_item(&account_state, get_alice_authkey_for_swarm())?; let merge_clean = merge_writeset(write_set_mut, clean)?; write_set_mut = merge_writeset(merge_clean, auth)?; } println!("Total accounts read: {}", &account_state_blobs.len()); Ok(write_set_mut) } /// Without modifying the data convert an AccountState struct, into a WriteSet Item which can be included in a genesis transaction. This should take all of the resources in the account. fn get_unmodified_writeset(account_state: &AccountState) -> Result<WriteSetMut, Error> { let mut ws = WriteSetMut::new(vec![]); if let Some(address) = account_state.get_account_address()? { // iterate over all the account's resources\ for (k, v) in account_state.iter() { let item_tuple = ( AccessPath::new(address, k.clone()), WriteOp::Value(v.clone()), ); // push into the writeset ws.push(item_tuple); } println!("processed account: {:?}", address); return Ok(ws); } bail!("ERROR: No address for AccountState: {:?}", account_state); } /// Returns the writeset item for replaceing an authkey on an account. This is only to be used in testing and simulation. fn authkey_rotate_change_item( account_state: &AccountState, authentication_key: Vec<u8>, ) -> Result<WriteSetMut, Error> { let mut ws = WriteSetMut::new(vec![]); if let Some(address) = account_state.get_account_address()? { // iterate over all the account's resources for (k, _v) in account_state.iter() { // if we find an AccountResource struc, which is where authkeys are kept if k.clone() == AccountResource::resource_path() { // let account_resource_option = account_state.get_account_resource()?; if let Some(account_resource) = account_state.get_account_resource()? { let account_resource_new = account_resource .clone_with_authentication_key(authentication_key.clone(), address.clone()); ws.push(( AccessPath::new(address, k.clone()), WriteOp::Value(lcs::to_bytes(&account_resource_new).unwrap()), )); } } } println!("rotate authkey for account: {:?}", address); } bail!( "ERROR: No address found at AccountState: {:?}", account_state ); } /// helper to merge writesets pub fn merge_writeset(mut left: WriteSetMut, right: WriteSetMut) -> Result<WriteSetMut, Error> { left.write_set.extend(right.write_set); Ok(left) } /// Tokio async parsing of state snapshot into blob async fn run_impl(manifest: StateSnapshotBackup, path: &PathBuf) -> Result<()> { // parse AccountStateBlob from chunks of the archive let mut account_state_blobs: Vec<AccountStateBlob> = Vec::new(); for chunk in manifest.chunks { let blobs = read_account_state_chunk(chunk.blobs, path).await?; // let proof = load_lcs_file(&chunk.proof)?; println!("{:?}", blobs); // TODO(Venkat) -> Here's the blob // println!("{:?}", proof); for (_key, blob) in blobs { account_state_blobs.push(blob) } } let genesis = vm_genesis::test_genesis_change_set_and_validators(Some(1)); let genesis_txn = Transaction::GenesisTransaction(WriteSetPayload::Direct(genesis.0)); let tmp_dir = TempPath::new(); let db_rw = DbReaderWriter::new(LibraDB::new_for_test(&tmp_dir)); // Executor won't be able to boot on empty db due to lack of StartupInfo. assert!(db_rw.reader.get_startup_info().unwrap().is_none()); // Bootstrap empty DB. let waypoint = generate_waypoint::<LibraVM>(&db_rw, &genesis_txn).expect("Should not fail."); maybe_bootstrap::<LibraVM>(&db_rw, &genesis_txn, waypoint).unwrap(); let startup_info = db_rw .reader .get_startup_info() .expect("Should not fail.") .expect("Should not be None."); assert_eq!( Waypoint::new_epoch_boundary(startup_info.latest_ledger_info.ledger_info()).unwrap(), waypoint ); let (li, epoch_change_proof, _) = db_rw.reader.get_state_proof(waypoint.version()).unwrap(); let trusted_state = TrustedState::from(waypoint); trusted_state .verify_and_ratchet(&li, &epoch_change_proof) .unwrap(); // `maybe_bootstrap()` does nothing on non-empty DB. assert!(!maybe_bootstrap::<LibraVM>(&db_rw, &genesis_txn, waypoint).unwrap()); let genesis_txn = generate_genesis::generate_genesis_from_snapshot(&account_state_blobs, &db_rw).unwrap(); generate_genesis::write_genesis_blob(genesis_txn)?; generate_genesis::test_genesis_from_blob(&account_state_blobs, db_rw)?; Ok(()) } /// given a path to state archive, produce a genesis.blob pub fn genesis_from_path(path: PathBuf) -> Result<()> { let path_man = path.clone().join("state.manifest"); dbg!(&path_man); let path_proof = path.join("state.proof"); dbg!(&path_proof); let manifest = read_from_json(&path_man).unwrap(); // Tokio runtime let (mut rt, _port) = get_runtime(); let (txn_info_with_proof, li): (TransactionInfoWithProof, LedgerInfoWithSignatures) = load_lcs_file(&path_proof.into_os_string().into_string().unwrap()).unwrap(); txn_info_with_proof.verify(li.ledger_info(), manifest.version)?; ensure!( txn_info_with_proof.transaction_info().state_root_hash() == manifest.root_hash, "Root hash mismatch with that in proof. root hash: {}, expected: {}", manifest.root_hash, txn_info_with_proof.transaction_info().state_root_hash(), ); let future = run_impl(manifest, &path); // Nothing is printed rt.block_on(future)?; Ok(()) } #[cfg(test)] #[test] fn test_main() -> Result<()> { use std::path::Path; let path = env!("CARGO_MANIFEST_DIR"); let buf = Path::new(path) .parent() .unwrap() .join("fixtures/state-snapshot/194/state_ver_74694920.0889/"); genesis_from_path(buf) } #[test] pub fn test_accounts_into_recovery() { use std::path::Path; let path = env!("CARGO_MANIFEST_DIR"); let buf = Path::new(path) .parent() .unwrap() .join("fixtures/state-snapshot/194/state_ver_74694920.0889/"); let path_man = buf.clone().join("state.manifest"); println!("Running....."); let backup = read_from_json(&path_man).unwrap(); let (mut rt, _port) = get_runtime(); let account_blobs_futures = accounts_from_snapshot_backup(backup); let account_blobs = rt.block_on(account_blobs_futures).unwrap(); let genesis_recovery_list = accounts_into_recovery(&account_blobs).unwrap(); println!("Total GenesisRecovery objects: {}", &genesis_recovery_list.len()); for blob in account_blobs { let account_state = AccountState::try_from(&blob).unwrap(); if let Some(address) = account_state.get_account_address().unwrap() { let mut address_processed = false; for gr in &genesis_recovery_list { if gr.address!= address { continue; } // iterate over all the account's resources\ for (k, v) in account_state.iter() { // extract the validator config resource if k.clone() == BalanceResource::resource_path() { match &gr.balance { Some(balance) => { if lcs::to_bytes(&balance).unwrap()!= v.clone() { panic!("Balance resource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("Balance not found"); } } } if k.clone() == ValidatorConfigResource::resource_path() { match &gr.val_cfg { Some(val_cfg) => { if lcs::to_bytes(&val_cfg).unwrap()!= v.clone() { panic!("ValidatorConfigResource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("ValidatorConfigResource not found"); } } } if k.clone() == MinerStateResource::resource_path() { match &gr.miner_state { Some(miner_state) => { if lcs::to_bytes(&miner_state).unwrap()!= v.clone() { panic!("MinerStateResource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("MinerStateResource not found"); } } } } println!("processed account: {:?}", address); address_processed = true; break; }; if!address_processed { panic!("Address not found for {} in recovery list", &address); } }; }; }
}
random_line_split
read_archive.rs
//! read-archive use backup_cli::storage::{FileHandle, FileHandleRef}; use libra_types::access_path::AccessPath; use libra_types::account_config::AccountResource; use libra_types::account_state::AccountState; use libra_types::write_set::{WriteOp, WriteSetMut}; use move_core_types::move_resource::MoveResource; use ol_fixtures::get_persona_mnem; use ol_keys::wallet::get_account_from_mnem; use serde::de::DeserializeOwned; use std::convert::TryFrom; use std::path::PathBuf; use std::fs::File; use std::io::Read; use libra_config::utils::get_available_port; use libra_crypto::HashValue; use libra_types::{ account_state_blob::AccountStateBlob, ledger_info::LedgerInfoWithSignatures, proof::TransactionInfoWithProof, account_config::BalanceResource, validator_config::ValidatorConfigResource, }; use libra_types::{ transaction::{Transaction, WriteSetPayload}, trusted_state::TrustedState, waypoint::Waypoint, }; use ol_types::miner_state::MinerStateResource; use std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, sync::Arc, }; use backup_cli::backup_types::state_snapshot::manifest::StateSnapshotBackup; use anyhow::{bail, ensure, Error, Result}; use tokio::{fs::OpenOptions, io::AsyncRead}; use libra_temppath::TempPath; use libradb::LibraDB; use backup_cli::utils::read_record_bytes::ReadRecordBytes; use backup_service::start_backup_service; use tokio::runtime::Runtime; use executor::db_bootstrapper::{generate_waypoint, maybe_bootstrap}; use libra_vm::LibraVM; use storage_interface::DbReaderWriter; use crate::generate_genesis; use crate::recover::{accounts_into_recovery, LegacyRecovery}; fn get_runtime() -> (Runtime, u16) { let port = get_available_port(); let path = TempPath::new(); let rt = start_backup_service( SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port), Arc::new(LibraDB::new_for_test(&path)), ); (rt, port) } async fn open_for_read(file_handle: &FileHandleRef) -> Result<Box<dyn AsyncRead + Send + Unpin>> { let file = OpenOptions::new().read(true).open(file_handle).await?; Ok(Box::new(file)) } fn read_from_file(path: &str) -> Result<Vec<u8>> { let mut data = Vec::<u8>::new(); let mut f = File::open(path).expect("Unable to open file"); f.read_to_end(&mut data).expect("Unable to read data"); Ok(data) } fn read_from_json(path: &PathBuf) -> Result<StateSnapshotBackup> { let config = std::fs::read_to_string(path)?; let map: StateSnapshotBackup = serde_json::from_str(&config)?; Ok(map) } fn load_lcs_file<T: DeserializeOwned>(file_handle: &str) -> Result<T> { let x = read_from_file(&file_handle)?; Ok(lcs::from_bytes(&x)?) } async fn read_account_state_chunk( file_handle: FileHandle, archive_path: &PathBuf, ) -> Result<Vec<(HashValue, AccountStateBlob)>> { let full_handle = archive_path.parent().unwrap().join(file_handle); let handle_str = full_handle.to_str().unwrap(); let mut file = open_for_read(handle_str).await?; let mut chunk = vec![]; while let Some(record_bytes) = file.read_record_bytes().await? { chunk.push(lcs::from_bytes(&record_bytes)?); } Ok(chunk) } /// take an archive file path and parse into a writeset pub async fn archive_into_swarm_writeset( archive_path: PathBuf, ) -> Result<WriteSetMut, Error> { let backup = read_from_json(&archive_path)?; let account_blobs = accounts_from_snapshot_backup(backup, &archive_path).await?; accounts_into_writeset_swarm(&account_blobs) } /// take an archive file path and parse into a writeset pub async fn archive_into_recovery(archive_path: &PathBuf) -> Result<Vec<LegacyRecovery>, Error> { let manifest_json = archive_path.join("state.manifest"); let backup = read_from_json(&manifest_json)?; let account_blobs = accounts_from_snapshot_backup(backup, archive_path).await?; let r = accounts_into_recovery(&account_blobs)?; Ok(r) } /// Tokio async parsing of state snapshot into blob async fn accounts_from_snapshot_backup( manifest: StateSnapshotBackup, archive_path: &PathBuf ) -> Result<Vec<AccountStateBlob>> { // parse AccountStateBlob from chunks of the archive let mut account_state_blobs: Vec<AccountStateBlob> = Vec::new(); for chunk in manifest.chunks { let blobs = read_account_state_chunk(chunk.blobs, archive_path).await?; // println!("{:?}", blobs); for (_key, blob) in blobs { account_state_blobs.push(blob) } } Ok(account_state_blobs) } fn get_alice_authkey_for_swarm() -> Vec<u8> { let mnemonic_string = get_persona_mnem("alice"); let account_details = get_account_from_mnem(mnemonic_string); account_details.0.to_vec() } /// cases that we need to create a genesis from backup. pub enum GenesisCase { /// a network upgrade or fork Fork, /// simulate state in a local swarm. Test, } /// make the writeset for the genesis case. Starts with an unmodified account state and make into a writeset. pub fn accounts_into_writeset_swarm( account_state_blobs: &Vec<AccountStateBlob>, ) -> Result<WriteSetMut, Error> { let mut write_set_mut = WriteSetMut::new(vec![]); for blob in account_state_blobs { let account_state = AccountState::try_from(blob)?; // TODO: borrow let clean = get_unmodified_writeset(&account_state)?; let auth = authkey_rotate_change_item(&account_state, get_alice_authkey_for_swarm())?; let merge_clean = merge_writeset(write_set_mut, clean)?; write_set_mut = merge_writeset(merge_clean, auth)?; } println!("Total accounts read: {}", &account_state_blobs.len()); Ok(write_set_mut) } /// Without modifying the data convert an AccountState struct, into a WriteSet Item which can be included in a genesis transaction. This should take all of the resources in the account. fn get_unmodified_writeset(account_state: &AccountState) -> Result<WriteSetMut, Error> { let mut ws = WriteSetMut::new(vec![]); if let Some(address) = account_state.get_account_address()? { // iterate over all the account's resources\ for (k, v) in account_state.iter() { let item_tuple = ( AccessPath::new(address, k.clone()), WriteOp::Value(v.clone()), ); // push into the writeset ws.push(item_tuple); } println!("processed account: {:?}", address); return Ok(ws); } bail!("ERROR: No address for AccountState: {:?}", account_state); } /// Returns the writeset item for replaceing an authkey on an account. This is only to be used in testing and simulation. fn authkey_rotate_change_item( account_state: &AccountState, authentication_key: Vec<u8>, ) -> Result<WriteSetMut, Error> { let mut ws = WriteSetMut::new(vec![]); if let Some(address) = account_state.get_account_address()? { // iterate over all the account's resources for (k, _v) in account_state.iter() { // if we find an AccountResource struc, which is where authkeys are kept if k.clone() == AccountResource::resource_path() { // let account_resource_option = account_state.get_account_resource()?; if let Some(account_resource) = account_state.get_account_resource()? { let account_resource_new = account_resource .clone_with_authentication_key(authentication_key.clone(), address.clone()); ws.push(( AccessPath::new(address, k.clone()), WriteOp::Value(lcs::to_bytes(&account_resource_new).unwrap()), )); } } } println!("rotate authkey for account: {:?}", address); } bail!( "ERROR: No address found at AccountState: {:?}", account_state ); } /// helper to merge writesets pub fn merge_writeset(mut left: WriteSetMut, right: WriteSetMut) -> Result<WriteSetMut, Error> { left.write_set.extend(right.write_set); Ok(left) } /// Tokio async parsing of state snapshot into blob async fn run_impl(manifest: StateSnapshotBackup, path: &PathBuf) -> Result<()> { // parse AccountStateBlob from chunks of the archive let mut account_state_blobs: Vec<AccountStateBlob> = Vec::new(); for chunk in manifest.chunks { let blobs = read_account_state_chunk(chunk.blobs, path).await?; // let proof = load_lcs_file(&chunk.proof)?; println!("{:?}", blobs); // TODO(Venkat) -> Here's the blob // println!("{:?}", proof); for (_key, blob) in blobs { account_state_blobs.push(blob) } } let genesis = vm_genesis::test_genesis_change_set_and_validators(Some(1)); let genesis_txn = Transaction::GenesisTransaction(WriteSetPayload::Direct(genesis.0)); let tmp_dir = TempPath::new(); let db_rw = DbReaderWriter::new(LibraDB::new_for_test(&tmp_dir)); // Executor won't be able to boot on empty db due to lack of StartupInfo. assert!(db_rw.reader.get_startup_info().unwrap().is_none()); // Bootstrap empty DB. let waypoint = generate_waypoint::<LibraVM>(&db_rw, &genesis_txn).expect("Should not fail."); maybe_bootstrap::<LibraVM>(&db_rw, &genesis_txn, waypoint).unwrap(); let startup_info = db_rw .reader .get_startup_info() .expect("Should not fail.") .expect("Should not be None."); assert_eq!( Waypoint::new_epoch_boundary(startup_info.latest_ledger_info.ledger_info()).unwrap(), waypoint ); let (li, epoch_change_proof, _) = db_rw.reader.get_state_proof(waypoint.version()).unwrap(); let trusted_state = TrustedState::from(waypoint); trusted_state .verify_and_ratchet(&li, &epoch_change_proof) .unwrap(); // `maybe_bootstrap()` does nothing on non-empty DB. assert!(!maybe_bootstrap::<LibraVM>(&db_rw, &genesis_txn, waypoint).unwrap()); let genesis_txn = generate_genesis::generate_genesis_from_snapshot(&account_state_blobs, &db_rw).unwrap(); generate_genesis::write_genesis_blob(genesis_txn)?; generate_genesis::test_genesis_from_blob(&account_state_blobs, db_rw)?; Ok(()) } /// given a path to state archive, produce a genesis.blob pub fn genesis_from_path(path: PathBuf) -> Result<()> { let path_man = path.clone().join("state.manifest"); dbg!(&path_man); let path_proof = path.join("state.proof"); dbg!(&path_proof); let manifest = read_from_json(&path_man).unwrap(); // Tokio runtime let (mut rt, _port) = get_runtime(); let (txn_info_with_proof, li): (TransactionInfoWithProof, LedgerInfoWithSignatures) = load_lcs_file(&path_proof.into_os_string().into_string().unwrap()).unwrap(); txn_info_with_proof.verify(li.ledger_info(), manifest.version)?; ensure!( txn_info_with_proof.transaction_info().state_root_hash() == manifest.root_hash, "Root hash mismatch with that in proof. root hash: {}, expected: {}", manifest.root_hash, txn_info_with_proof.transaction_info().state_root_hash(), ); let future = run_impl(manifest, &path); // Nothing is printed rt.block_on(future)?; Ok(()) } #[cfg(test)] #[test] fn test_main() -> Result<()> { use std::path::Path; let path = env!("CARGO_MANIFEST_DIR"); let buf = Path::new(path) .parent() .unwrap() .join("fixtures/state-snapshot/194/state_ver_74694920.0889/"); genesis_from_path(buf) } #[test] pub fn test_accounts_into_recovery() { use std::path::Path; let path = env!("CARGO_MANIFEST_DIR"); let buf = Path::new(path) .parent() .unwrap() .join("fixtures/state-snapshot/194/state_ver_74694920.0889/"); let path_man = buf.clone().join("state.manifest"); println!("Running....."); let backup = read_from_json(&path_man).unwrap(); let (mut rt, _port) = get_runtime(); let account_blobs_futures = accounts_from_snapshot_backup(backup); let account_blobs = rt.block_on(account_blobs_futures).unwrap(); let genesis_recovery_list = accounts_into_recovery(&account_blobs).unwrap(); println!("Total GenesisRecovery objects: {}", &genesis_recovery_list.len()); for blob in account_blobs { let account_state = AccountState::try_from(&blob).unwrap(); if let Some(address) = account_state.get_account_address().unwrap() { let mut address_processed = false; for gr in &genesis_recovery_list { if gr.address!= address { continue; } // iterate over all the account's resources\ for (k, v) in account_state.iter() { // extract the validator config resource if k.clone() == BalanceResource::resource_path() { match &gr.balance { Some(balance) => { if lcs::to_bytes(&balance).unwrap()!= v.clone() { panic!("Balance resource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("Balance not found"); } } } if k.clone() == ValidatorConfigResource::resource_path() { match &gr.val_cfg { Some(val_cfg) => { if lcs::to_bytes(&val_cfg).unwrap()!= v.clone() { panic!("ValidatorConfigResource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("ValidatorConfigResource not found"); } } } if k.clone() == MinerStateResource::resource_path() { match &gr.miner_state { Some(miner_state) => { if lcs::to_bytes(&miner_state).unwrap()!= v.clone() { panic!("MinerStateResource not found in GenesisRecovery object: {}", gr.address); } }, None =>
} } } println!("processed account: {:?}", address); address_processed = true; break; }; if!address_processed { panic!("Address not found for {} in recovery list", &address); } }; }; }
{ panic!("MinerStateResource not found"); }
conditional_block
read_archive.rs
//! read-archive use backup_cli::storage::{FileHandle, FileHandleRef}; use libra_types::access_path::AccessPath; use libra_types::account_config::AccountResource; use libra_types::account_state::AccountState; use libra_types::write_set::{WriteOp, WriteSetMut}; use move_core_types::move_resource::MoveResource; use ol_fixtures::get_persona_mnem; use ol_keys::wallet::get_account_from_mnem; use serde::de::DeserializeOwned; use std::convert::TryFrom; use std::path::PathBuf; use std::fs::File; use std::io::Read; use libra_config::utils::get_available_port; use libra_crypto::HashValue; use libra_types::{ account_state_blob::AccountStateBlob, ledger_info::LedgerInfoWithSignatures, proof::TransactionInfoWithProof, account_config::BalanceResource, validator_config::ValidatorConfigResource, }; use libra_types::{ transaction::{Transaction, WriteSetPayload}, trusted_state::TrustedState, waypoint::Waypoint, }; use ol_types::miner_state::MinerStateResource; use std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, sync::Arc, }; use backup_cli::backup_types::state_snapshot::manifest::StateSnapshotBackup; use anyhow::{bail, ensure, Error, Result}; use tokio::{fs::OpenOptions, io::AsyncRead}; use libra_temppath::TempPath; use libradb::LibraDB; use backup_cli::utils::read_record_bytes::ReadRecordBytes; use backup_service::start_backup_service; use tokio::runtime::Runtime; use executor::db_bootstrapper::{generate_waypoint, maybe_bootstrap}; use libra_vm::LibraVM; use storage_interface::DbReaderWriter; use crate::generate_genesis; use crate::recover::{accounts_into_recovery, LegacyRecovery}; fn get_runtime() -> (Runtime, u16) { let port = get_available_port(); let path = TempPath::new(); let rt = start_backup_service( SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port), Arc::new(LibraDB::new_for_test(&path)), ); (rt, port) } async fn open_for_read(file_handle: &FileHandleRef) -> Result<Box<dyn AsyncRead + Send + Unpin>> { let file = OpenOptions::new().read(true).open(file_handle).await?; Ok(Box::new(file)) } fn read_from_file(path: &str) -> Result<Vec<u8>> { let mut data = Vec::<u8>::new(); let mut f = File::open(path).expect("Unable to open file"); f.read_to_end(&mut data).expect("Unable to read data"); Ok(data) } fn read_from_json(path: &PathBuf) -> Result<StateSnapshotBackup> { let config = std::fs::read_to_string(path)?; let map: StateSnapshotBackup = serde_json::from_str(&config)?; Ok(map) } fn load_lcs_file<T: DeserializeOwned>(file_handle: &str) -> Result<T> { let x = read_from_file(&file_handle)?; Ok(lcs::from_bytes(&x)?) } async fn read_account_state_chunk( file_handle: FileHandle, archive_path: &PathBuf, ) -> Result<Vec<(HashValue, AccountStateBlob)>> { let full_handle = archive_path.parent().unwrap().join(file_handle); let handle_str = full_handle.to_str().unwrap(); let mut file = open_for_read(handle_str).await?; let mut chunk = vec![]; while let Some(record_bytes) = file.read_record_bytes().await? { chunk.push(lcs::from_bytes(&record_bytes)?); } Ok(chunk) } /// take an archive file path and parse into a writeset pub async fn
( archive_path: PathBuf, ) -> Result<WriteSetMut, Error> { let backup = read_from_json(&archive_path)?; let account_blobs = accounts_from_snapshot_backup(backup, &archive_path).await?; accounts_into_writeset_swarm(&account_blobs) } /// take an archive file path and parse into a writeset pub async fn archive_into_recovery(archive_path: &PathBuf) -> Result<Vec<LegacyRecovery>, Error> { let manifest_json = archive_path.join("state.manifest"); let backup = read_from_json(&manifest_json)?; let account_blobs = accounts_from_snapshot_backup(backup, archive_path).await?; let r = accounts_into_recovery(&account_blobs)?; Ok(r) } /// Tokio async parsing of state snapshot into blob async fn accounts_from_snapshot_backup( manifest: StateSnapshotBackup, archive_path: &PathBuf ) -> Result<Vec<AccountStateBlob>> { // parse AccountStateBlob from chunks of the archive let mut account_state_blobs: Vec<AccountStateBlob> = Vec::new(); for chunk in manifest.chunks { let blobs = read_account_state_chunk(chunk.blobs, archive_path).await?; // println!("{:?}", blobs); for (_key, blob) in blobs { account_state_blobs.push(blob) } } Ok(account_state_blobs) } fn get_alice_authkey_for_swarm() -> Vec<u8> { let mnemonic_string = get_persona_mnem("alice"); let account_details = get_account_from_mnem(mnemonic_string); account_details.0.to_vec() } /// cases that we need to create a genesis from backup. pub enum GenesisCase { /// a network upgrade or fork Fork, /// simulate state in a local swarm. Test, } /// make the writeset for the genesis case. Starts with an unmodified account state and make into a writeset. pub fn accounts_into_writeset_swarm( account_state_blobs: &Vec<AccountStateBlob>, ) -> Result<WriteSetMut, Error> { let mut write_set_mut = WriteSetMut::new(vec![]); for blob in account_state_blobs { let account_state = AccountState::try_from(blob)?; // TODO: borrow let clean = get_unmodified_writeset(&account_state)?; let auth = authkey_rotate_change_item(&account_state, get_alice_authkey_for_swarm())?; let merge_clean = merge_writeset(write_set_mut, clean)?; write_set_mut = merge_writeset(merge_clean, auth)?; } println!("Total accounts read: {}", &account_state_blobs.len()); Ok(write_set_mut) } /// Without modifying the data convert an AccountState struct, into a WriteSet Item which can be included in a genesis transaction. This should take all of the resources in the account. fn get_unmodified_writeset(account_state: &AccountState) -> Result<WriteSetMut, Error> { let mut ws = WriteSetMut::new(vec![]); if let Some(address) = account_state.get_account_address()? { // iterate over all the account's resources\ for (k, v) in account_state.iter() { let item_tuple = ( AccessPath::new(address, k.clone()), WriteOp::Value(v.clone()), ); // push into the writeset ws.push(item_tuple); } println!("processed account: {:?}", address); return Ok(ws); } bail!("ERROR: No address for AccountState: {:?}", account_state); } /// Returns the writeset item for replaceing an authkey on an account. This is only to be used in testing and simulation. fn authkey_rotate_change_item( account_state: &AccountState, authentication_key: Vec<u8>, ) -> Result<WriteSetMut, Error> { let mut ws = WriteSetMut::new(vec![]); if let Some(address) = account_state.get_account_address()? { // iterate over all the account's resources for (k, _v) in account_state.iter() { // if we find an AccountResource struc, which is where authkeys are kept if k.clone() == AccountResource::resource_path() { // let account_resource_option = account_state.get_account_resource()?; if let Some(account_resource) = account_state.get_account_resource()? { let account_resource_new = account_resource .clone_with_authentication_key(authentication_key.clone(), address.clone()); ws.push(( AccessPath::new(address, k.clone()), WriteOp::Value(lcs::to_bytes(&account_resource_new).unwrap()), )); } } } println!("rotate authkey for account: {:?}", address); } bail!( "ERROR: No address found at AccountState: {:?}", account_state ); } /// helper to merge writesets pub fn merge_writeset(mut left: WriteSetMut, right: WriteSetMut) -> Result<WriteSetMut, Error> { left.write_set.extend(right.write_set); Ok(left) } /// Tokio async parsing of state snapshot into blob async fn run_impl(manifest: StateSnapshotBackup, path: &PathBuf) -> Result<()> { // parse AccountStateBlob from chunks of the archive let mut account_state_blobs: Vec<AccountStateBlob> = Vec::new(); for chunk in manifest.chunks { let blobs = read_account_state_chunk(chunk.blobs, path).await?; // let proof = load_lcs_file(&chunk.proof)?; println!("{:?}", blobs); // TODO(Venkat) -> Here's the blob // println!("{:?}", proof); for (_key, blob) in blobs { account_state_blobs.push(blob) } } let genesis = vm_genesis::test_genesis_change_set_and_validators(Some(1)); let genesis_txn = Transaction::GenesisTransaction(WriteSetPayload::Direct(genesis.0)); let tmp_dir = TempPath::new(); let db_rw = DbReaderWriter::new(LibraDB::new_for_test(&tmp_dir)); // Executor won't be able to boot on empty db due to lack of StartupInfo. assert!(db_rw.reader.get_startup_info().unwrap().is_none()); // Bootstrap empty DB. let waypoint = generate_waypoint::<LibraVM>(&db_rw, &genesis_txn).expect("Should not fail."); maybe_bootstrap::<LibraVM>(&db_rw, &genesis_txn, waypoint).unwrap(); let startup_info = db_rw .reader .get_startup_info() .expect("Should not fail.") .expect("Should not be None."); assert_eq!( Waypoint::new_epoch_boundary(startup_info.latest_ledger_info.ledger_info()).unwrap(), waypoint ); let (li, epoch_change_proof, _) = db_rw.reader.get_state_proof(waypoint.version()).unwrap(); let trusted_state = TrustedState::from(waypoint); trusted_state .verify_and_ratchet(&li, &epoch_change_proof) .unwrap(); // `maybe_bootstrap()` does nothing on non-empty DB. assert!(!maybe_bootstrap::<LibraVM>(&db_rw, &genesis_txn, waypoint).unwrap()); let genesis_txn = generate_genesis::generate_genesis_from_snapshot(&account_state_blobs, &db_rw).unwrap(); generate_genesis::write_genesis_blob(genesis_txn)?; generate_genesis::test_genesis_from_blob(&account_state_blobs, db_rw)?; Ok(()) } /// given a path to state archive, produce a genesis.blob pub fn genesis_from_path(path: PathBuf) -> Result<()> { let path_man = path.clone().join("state.manifest"); dbg!(&path_man); let path_proof = path.join("state.proof"); dbg!(&path_proof); let manifest = read_from_json(&path_man).unwrap(); // Tokio runtime let (mut rt, _port) = get_runtime(); let (txn_info_with_proof, li): (TransactionInfoWithProof, LedgerInfoWithSignatures) = load_lcs_file(&path_proof.into_os_string().into_string().unwrap()).unwrap(); txn_info_with_proof.verify(li.ledger_info(), manifest.version)?; ensure!( txn_info_with_proof.transaction_info().state_root_hash() == manifest.root_hash, "Root hash mismatch with that in proof. root hash: {}, expected: {}", manifest.root_hash, txn_info_with_proof.transaction_info().state_root_hash(), ); let future = run_impl(manifest, &path); // Nothing is printed rt.block_on(future)?; Ok(()) } #[cfg(test)] #[test] fn test_main() -> Result<()> { use std::path::Path; let path = env!("CARGO_MANIFEST_DIR"); let buf = Path::new(path) .parent() .unwrap() .join("fixtures/state-snapshot/194/state_ver_74694920.0889/"); genesis_from_path(buf) } #[test] pub fn test_accounts_into_recovery() { use std::path::Path; let path = env!("CARGO_MANIFEST_DIR"); let buf = Path::new(path) .parent() .unwrap() .join("fixtures/state-snapshot/194/state_ver_74694920.0889/"); let path_man = buf.clone().join("state.manifest"); println!("Running....."); let backup = read_from_json(&path_man).unwrap(); let (mut rt, _port) = get_runtime(); let account_blobs_futures = accounts_from_snapshot_backup(backup); let account_blobs = rt.block_on(account_blobs_futures).unwrap(); let genesis_recovery_list = accounts_into_recovery(&account_blobs).unwrap(); println!("Total GenesisRecovery objects: {}", &genesis_recovery_list.len()); for blob in account_blobs { let account_state = AccountState::try_from(&blob).unwrap(); if let Some(address) = account_state.get_account_address().unwrap() { let mut address_processed = false; for gr in &genesis_recovery_list { if gr.address!= address { continue; } // iterate over all the account's resources\ for (k, v) in account_state.iter() { // extract the validator config resource if k.clone() == BalanceResource::resource_path() { match &gr.balance { Some(balance) => { if lcs::to_bytes(&balance).unwrap()!= v.clone() { panic!("Balance resource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("Balance not found"); } } } if k.clone() == ValidatorConfigResource::resource_path() { match &gr.val_cfg { Some(val_cfg) => { if lcs::to_bytes(&val_cfg).unwrap()!= v.clone() { panic!("ValidatorConfigResource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("ValidatorConfigResource not found"); } } } if k.clone() == MinerStateResource::resource_path() { match &gr.miner_state { Some(miner_state) => { if lcs::to_bytes(&miner_state).unwrap()!= v.clone() { panic!("MinerStateResource not found in GenesisRecovery object: {}", gr.address); } }, None => { panic!("MinerStateResource not found"); } } } } println!("processed account: {:?}", address); address_processed = true; break; }; if!address_processed { panic!("Address not found for {} in recovery list", &address); } }; }; }
archive_into_swarm_writeset
identifier_name
main.rs
// This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from // scratch based on a careful reading of the TLS 1.3 specification. use std::net::SocketAddr; use std::path::PathBuf; use std::time::Duration; use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind}; use tokio::net; use tokio::signal::unix::{signal, SignalKind}; use tokio::task; use tokio::time::{timeout, Elapsed}; // Unless otherwise specified, all quotes are from RFC 8446 (TLS 1.3). // legacy_record_version: "MUST be set to 0x0303 for all records generated by a TLS // 1.3 implementation" const TLS_LEGACY_RECORD_VERSION: [u8; 2] = [0x03, 0x03]; const TLS_HANDSHAKE_CONTENT_TYPE: u8 = 0x16; const TLS_HANDSHAKE_TYPE_CLIENT_HELLO: u8 = 0x01; const TLS_EXTENSION_SNI: usize = 0x0000; const TLS_SNI_HOST_NAME_TYPE: u8 = 0; const TLS_ALERT_CONTENT_TYPE: u8 = 21; const TLS_ALERT_LENGTH: [u8; 2] = [0x00, 0x02]; const TLS_ALERT_LEVEL_FATAL: u8 = 2; enum TlsError { UnexpectedMessage = 10, RecordOverflow = 22, DecodeError = 50, InternalError = 80, UserCanceled = 90, UnrecognizedName = 112, } impl From<Error> for TlsError { fn from(_error: Error) -> Self { TlsError::InternalError } } impl From<Elapsed> for TlsError { fn from(_error: Elapsed) -> Self { TlsError::UserCanceled } } type TlsResult<O> = Result<O, TlsError>; struct TlsHandshakeReader<R> { source: R, buffer: Vec<u8>, offset: usize, limit: usize, } fn check_length(length: usize, limit: &mut usize) -> TlsResult<()> { *limit = limit.checked_sub(length).ok_or(TlsError::DecodeError)?; Ok(()) } impl<R: AsyncReadExt> TlsHandshakeReader<R> { fn new(source: R) -> Self { TlsHandshakeReader { source: source, buffer: Vec::with_capacity(4096), offset: 0, limit: 0, } } fn seek(&mut self, offset: usize, limit: &mut usize) -> TlsResult<()> { self.offset += offset; check_length(offset, limit) } async fn fill_to(&mut self, target: usize) -> TlsResult<()> { while self.buffer.len() < target { if self.source.read_buf(&mut self.buffer).await? == 0 { return Err(TlsError::DecodeError); } } Ok(()) } async fn read(&mut self) -> TlsResult<u8>
// section 5.1: "The record layer fragments information blocks into TLSPlaintext // records carrying data in chunks of 2^14 bytes or less." if length > (1 << 14) { return Err(TlsError::RecordOverflow); } self.offset += 5; self.limit += 5 + length; } self.fill_to(self.offset + 1).await?; let v = self.buffer[self.offset]; self.offset += 1; Ok(v) } async fn read_length(&mut self, length: u8) -> TlsResult<usize> { debug_assert!(length > 0 && length <= 4); let mut result = 0; for _ in 0..length { result <<= 8; result |= self.read().await? as usize; } Ok(result) } async fn into_source<W: AsyncWriteExt + Unpin>(self, dest: &mut W) -> io::Result<R> { dest.write_all(&self.buffer[..]).await?; Ok(self.source) } } async fn get_server_name<R: AsyncReadExt>(source: &mut TlsHandshakeReader<R>) -> TlsResult<String> { // section 4.1.2: "When a client first connects to a server, it is REQUIRED to send the // ClientHello as its first TLS message." if source.read().await?!= TLS_HANDSHAKE_TYPE_CLIENT_HELLO { return Err(TlsError::UnexpectedMessage); } let mut hello_length = source.read_length(3).await?; // skip legacy_version (2) and random (32) source.seek(34, &mut hello_length)?; // skip legacy_session_id check_length(1, &mut hello_length)?; let length = source.read_length(1).await?; source.seek(length, &mut hello_length)?; // skip cipher_suites check_length(2, &mut hello_length)?; let length = source.read_length(2).await?; source.seek(length, &mut hello_length)?; // skip legacy_compression_methods check_length(1, &mut hello_length)?; let length = source.read_length(1).await?; source.seek(length, &mut hello_length)?; // section 4.1.2: "TLS 1.3 servers might receive ClientHello messages without an extensions // field from prior versions of TLS. The presence of extensions can be detected by determining // whether there are bytes following the compression_methods field at the end of the // ClientHello. Note that this method of detecting optional data differs from the normal TLS // method of having a variable-length field, but it is used for compatibility with TLS before // extensions were defined.... If negotiating a version of TLS prior to 1.3, a server MUST // check that the message either contains no data after legacy_compression_methods or that it // contains a valid extensions block with no data following. If not, then it MUST abort the // handshake with a "decode_error" alert." // // If there is no extensions block, treat it like a server name extension was present but with // an unrecognized name. I don't think the spec allows this, but it doesn't NOT allow it? if hello_length == 0 { return Err(TlsError::UnrecognizedName); } // ClientHello ends immediately after the extensions check_length(2, &mut hello_length)?; if hello_length!= source.read_length(2).await? { return Err(TlsError::DecodeError); } while hello_length > 0 { check_length(4, &mut hello_length)?; let extension = source.read_length(2).await?; let mut length = source.read_length(2).await?; if extension!= TLS_EXTENSION_SNI { source.seek(length, &mut hello_length)?; continue; } check_length(length, &mut hello_length)?; // This extension ends immediately after server_name_list check_length(2, &mut length)?; if length!= source.read_length(2).await? { return Err(TlsError::DecodeError); } while length > 0 { check_length(3, &mut length)?; let name_type = source.read().await?; let name_length = source.read_length(2).await?; if name_type!= TLS_SNI_HOST_NAME_TYPE { source.seek(name_length, &mut length)?; continue; } check_length(name_length, &mut length)?; // RFC 6066 section 3: "The ServerNameList MUST NOT contain more than one name of the // same name_type." So we can just extract the first one we find. // Hostnames are limited to 255 octets with a trailing dot, but RFC 6066 prohibits the // trailing dot, so the limit here is 254 octets. Enforcing this limit ensures an // attacker can't make us heap-allocate 64kB for a hostname we'll never match. if name_length > 254 { return Err(TlsError::UnrecognizedName); } // The following validation rules ensure that we won't return a hostname which could // lead to pathname traversal (e.g. "..", "", or "a/b") and that semantically // equivalent hostnames are only returned in a canonical form. This does not validate // anything else about the hostname, such as length limits on individual labels. let mut name = Vec::with_capacity(name_length); let mut start_of_label = true; for _ in 0..name_length { let b = source.read().await?.to_ascii_lowercase(); if start_of_label && (b == b'-' || b == b'.') { // a hostname label can't start with dot or dash return Err(TlsError::UnrecognizedName); } // the next byte is the start of a label iff this one was a dot start_of_label = b'.' == b; match b { b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' => name.push(b), _ => return Err(TlsError::UnrecognizedName), } } // If we're expecting a new label after reading the whole hostname, then either the // name was empty or it ended with a dot; neither is allowed. if start_of_label { return Err(TlsError::UnrecognizedName); } // safety: every byte was already checked for being a valid subset of UTF-8 let name = unsafe { String::from_utf8_unchecked(name) }; return Ok(name); } // None of the names were of the right type, and section 4.2 says "There MUST NOT be more // than one extension of the same type in a given extension block", so there definitely // isn't a server name in this ClientHello. break; } // Like when the extensions block is absent, pretend as if a server name was present but not // recognized. Err(TlsError::UnrecognizedName) } fn hash_hostname(hostname: String) -> PathBuf { #[cfg(feature = "hashed")] let hostname = { use blake2::{Blake2s, Digest}; let hash = Blake2s::digest(hostname.as_bytes()); base64::encode_config(&hash, base64::URL_SAFE_NO_PAD) }; hostname.into() } async fn connect_backend<R: AsyncReadExt>( source: R, local: SocketAddr, remote: SocketAddr, ) -> TlsResult<(R, net::UnixStream)> { let mut source = TlsHandshakeReader::new(source); // timeout can return a "Elapsed" error, or else return the result from get_server_name, which // might be a TlsError. So there are two "?" here to unwrap both. let name = timeout(Duration::from_secs(10), get_server_name(&mut source)).await??; let path = hash_hostname(name); // The client sent a name and it's been validated to be safe to use as a path. Consider it a // valid server name if connecting to the path doesn't return any of these errors: // - is a directory (NotFound after joining a relative path) // - which contains an entry named "tls-socket" (NotFound) // - which is accessible to this proxy (PermissionDenied) // - and is a listening socket (ConnectionRefused) // If it isn't a valid server name, then that's the error to report. Anything else is not the // client's fault. let mut backend = net::UnixStream::connect(path.join("tls-socket")) .await .map_err(|e| match e.kind() { ErrorKind::NotFound | ErrorKind::PermissionDenied | ErrorKind::ConnectionRefused => { TlsError::UnrecognizedName } _ => TlsError::InternalError, })?; // After this point, all I/O errors are internal errors. // If this file exists, turn on the PROXY protocol. // NOTE: This is a blocking syscall, but stat should be fast enough that it's not worth // spawning off a thread. if std::fs::metadata(path.join("send-proxy-v1")).is_ok() { let header = format!( "PROXY {} {} {} {} {}\r\n", match remote { SocketAddr::V4(_) => "TCP4", SocketAddr::V6(_) => "TCP6", }, remote.ip(), local.ip(), remote.port(), local.port(), ); backend.write_all(header.as_bytes()).await?; } let source = source.into_source(&mut backend).await?; Ok((source, backend)) } async fn handle_connection(mut client: net::TcpStream, local: SocketAddr, remote: SocketAddr) { let (client_in, mut client_out) = client.split(); let (client_in, mut backend) = match connect_backend(client_in, local, remote).await { Ok(r) => r, Err(e) => { // Try to send an alert before closing the connection, but if that fails, don't worry // about it... they'll figure it out eventually. let _ = client_out .write_all(&[ TLS_ALERT_CONTENT_TYPE, TLS_LEGACY_RECORD_VERSION[0], TLS_LEGACY_RECORD_VERSION[1], TLS_ALERT_LENGTH[0], TLS_ALERT_LENGTH[1], TLS_ALERT_LEVEL_FATAL, // AlertDescription comes from the returned error; see TlsError above e as u8, ]) .await; return; } }; let (backend_in, backend_out) = backend.split(); // Ignore errors in either direction; just half-close the destination when the source stops // being readable. And if that fails, ignore that too. async fn copy_all<R, W>(mut from: R, mut to: W) where R: AsyncReadExt + Unpin, W: AsyncWriteExt + Unpin, { let _ = io::copy(&mut from, &mut to).await; let _ = to.shutdown().await; } tokio::join!( copy_all(client_in, backend_out), copy_all(backend_in, client_out), ); } async fn main_loop() -> io::Result<()> { // safety: the rest of the program must not use stdin let listener = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(0) }; // Assume stdin is an already bound and listening TCP socket. let mut listener = net::TcpListener::from_std(listener)?; // Asking for the listening socket's local address has the side effect of checking that it is // actually a TCP socket. let local = listener.local_addr()?; println!("listening on {}", local); let mut graceful_shutdown = signal(SignalKind::hangup())?; loop { tokio::select!( result = listener.accept() => result.map(|(socket, remote)| { let local = socket.local_addr().unwrap_or(local); task::spawn_local(handle_connection(socket, local, remote)); })?, Some(_) = graceful_shutdown.recv() => break, ); } println!("got SIGHUP, shutting down"); Ok(()) } #[tokio::main] async fn main() -> io::Result<()> { let local = task::LocalSet::new(); local.run_until(main_loop()).await?; timeout(Duration::from_secs(10), local) .await .map_err(|_| ErrorKind::TimedOut.into()) }
{ while self.offset >= self.limit { self.fill_to(self.limit + 5).await?; // section 5.1: "Handshake messages MUST NOT be interleaved with other record types. // That is, if a handshake message is split over two or more records, there MUST NOT be // any other records between them." if self.buffer[self.limit] != TLS_HANDSHAKE_CONTENT_TYPE { return Err(TlsError::UnexpectedMessage); } let length = (self.buffer[self.limit + 3] as usize) << 8 | (self.buffer[self.limit + 4] as usize); // section 5.1: "Implementations MUST NOT send zero-length fragments of Handshake // types, even if those fragments contain padding." if length == 0 { return Err(TlsError::DecodeError); }
identifier_body
main.rs
// This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from // scratch based on a careful reading of the TLS 1.3 specification. use std::net::SocketAddr; use std::path::PathBuf; use std::time::Duration; use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind}; use tokio::net; use tokio::signal::unix::{signal, SignalKind}; use tokio::task; use tokio::time::{timeout, Elapsed}; // Unless otherwise specified, all quotes are from RFC 8446 (TLS 1.3). // legacy_record_version: "MUST be set to 0x0303 for all records generated by a TLS // 1.3 implementation" const TLS_LEGACY_RECORD_VERSION: [u8; 2] = [0x03, 0x03]; const TLS_HANDSHAKE_CONTENT_TYPE: u8 = 0x16; const TLS_HANDSHAKE_TYPE_CLIENT_HELLO: u8 = 0x01; const TLS_EXTENSION_SNI: usize = 0x0000; const TLS_SNI_HOST_NAME_TYPE: u8 = 0; const TLS_ALERT_CONTENT_TYPE: u8 = 21; const TLS_ALERT_LENGTH: [u8; 2] = [0x00, 0x02]; const TLS_ALERT_LEVEL_FATAL: u8 = 2; enum TlsError { UnexpectedMessage = 10, RecordOverflow = 22, DecodeError = 50, InternalError = 80, UserCanceled = 90, UnrecognizedName = 112, } impl From<Error> for TlsError { fn from(_error: Error) -> Self { TlsError::InternalError } } impl From<Elapsed> for TlsError { fn from(_error: Elapsed) -> Self { TlsError::UserCanceled } } type TlsResult<O> = Result<O, TlsError>; struct TlsHandshakeReader<R> { source: R, buffer: Vec<u8>, offset: usize, limit: usize, } fn check_length(length: usize, limit: &mut usize) -> TlsResult<()> { *limit = limit.checked_sub(length).ok_or(TlsError::DecodeError)?; Ok(()) } impl<R: AsyncReadExt> TlsHandshakeReader<R> { fn new(source: R) -> Self { TlsHandshakeReader { source: source, buffer: Vec::with_capacity(4096), offset: 0, limit: 0, } } fn seek(&mut self, offset: usize, limit: &mut usize) -> TlsResult<()> { self.offset += offset; check_length(offset, limit) } async fn fill_to(&mut self, target: usize) -> TlsResult<()> { while self.buffer.len() < target { if self.source.read_buf(&mut self.buffer).await? == 0 { return Err(TlsError::DecodeError); } } Ok(()) } async fn read(&mut self) -> TlsResult<u8> { while self.offset >= self.limit { self.fill_to(self.limit + 5).await?; // section 5.1: "Handshake messages MUST NOT be interleaved with other record types. // That is, if a handshake message is split over two or more records, there MUST NOT be // any other records between them." if self.buffer[self.limit]!= TLS_HANDSHAKE_CONTENT_TYPE { return Err(TlsError::UnexpectedMessage); } let length = (self.buffer[self.limit + 3] as usize) << 8 | (self.buffer[self.limit + 4] as usize); // section 5.1: "Implementations MUST NOT send zero-length fragments of Handshake // types, even if those fragments contain padding." if length == 0 { return Err(TlsError::DecodeError); } // section 5.1: "The record layer fragments information blocks into TLSPlaintext // records carrying data in chunks of 2^14 bytes or less." if length > (1 << 14) { return Err(TlsError::RecordOverflow); } self.offset += 5; self.limit += 5 + length; } self.fill_to(self.offset + 1).await?; let v = self.buffer[self.offset]; self.offset += 1; Ok(v) } async fn read_length(&mut self, length: u8) -> TlsResult<usize> { debug_assert!(length > 0 && length <= 4); let mut result = 0; for _ in 0..length { result <<= 8; result |= self.read().await? as usize; } Ok(result) } async fn into_source<W: AsyncWriteExt + Unpin>(self, dest: &mut W) -> io::Result<R> { dest.write_all(&self.buffer[..]).await?; Ok(self.source) } } async fn get_server_name<R: AsyncReadExt>(source: &mut TlsHandshakeReader<R>) -> TlsResult<String> { // section 4.1.2: "When a client first connects to a server, it is REQUIRED to send the // ClientHello as its first TLS message." if source.read().await?!= TLS_HANDSHAKE_TYPE_CLIENT_HELLO { return Err(TlsError::UnexpectedMessage); } let mut hello_length = source.read_length(3).await?; // skip legacy_version (2) and random (32) source.seek(34, &mut hello_length)?; // skip legacy_session_id check_length(1, &mut hello_length)?; let length = source.read_length(1).await?; source.seek(length, &mut hello_length)?; // skip cipher_suites check_length(2, &mut hello_length)?; let length = source.read_length(2).await?; source.seek(length, &mut hello_length)?; // skip legacy_compression_methods check_length(1, &mut hello_length)?; let length = source.read_length(1).await?; source.seek(length, &mut hello_length)?; // section 4.1.2: "TLS 1.3 servers might receive ClientHello messages without an extensions // field from prior versions of TLS. The presence of extensions can be detected by determining // whether there are bytes following the compression_methods field at the end of the // ClientHello. Note that this method of detecting optional data differs from the normal TLS // method of having a variable-length field, but it is used for compatibility with TLS before // extensions were defined.... If negotiating a version of TLS prior to 1.3, a server MUST // check that the message either contains no data after legacy_compression_methods or that it // contains a valid extensions block with no data following. If not, then it MUST abort the // handshake with a "decode_error" alert." // // If there is no extensions block, treat it like a server name extension was present but with // an unrecognized name. I don't think the spec allows this, but it doesn't NOT allow it? if hello_length == 0 { return Err(TlsError::UnrecognizedName); } // ClientHello ends immediately after the extensions check_length(2, &mut hello_length)?; if hello_length!= source.read_length(2).await? { return Err(TlsError::DecodeError); } while hello_length > 0 { check_length(4, &mut hello_length)?; let extension = source.read_length(2).await?; let mut length = source.read_length(2).await?; if extension!= TLS_EXTENSION_SNI { source.seek(length, &mut hello_length)?; continue; } check_length(length, &mut hello_length)?; // This extension ends immediately after server_name_list check_length(2, &mut length)?; if length!= source.read_length(2).await? { return Err(TlsError::DecodeError); } while length > 0 { check_length(3, &mut length)?; let name_type = source.read().await?; let name_length = source.read_length(2).await?; if name_type!= TLS_SNI_HOST_NAME_TYPE { source.seek(name_length, &mut length)?; continue; } check_length(name_length, &mut length)?; // RFC 6066 section 3: "The ServerNameList MUST NOT contain more than one name of the // same name_type." So we can just extract the first one we find. // Hostnames are limited to 255 octets with a trailing dot, but RFC 6066 prohibits the // trailing dot, so the limit here is 254 octets. Enforcing this limit ensures an // attacker can't make us heap-allocate 64kB for a hostname we'll never match. if name_length > 254 { return Err(TlsError::UnrecognizedName); } // The following validation rules ensure that we won't return a hostname which could // lead to pathname traversal (e.g. "..", "", or "a/b") and that semantically // equivalent hostnames are only returned in a canonical form. This does not validate // anything else about the hostname, such as length limits on individual labels. let mut name = Vec::with_capacity(name_length); let mut start_of_label = true; for _ in 0..name_length { let b = source.read().await?.to_ascii_lowercase(); if start_of_label && (b == b'-' || b == b'.') { // a hostname label can't start with dot or dash return Err(TlsError::UnrecognizedName); } // the next byte is the start of a label iff this one was a dot start_of_label = b'.' == b; match b { b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' => name.push(b), _ => return Err(TlsError::UnrecognizedName), } } // If we're expecting a new label after reading the whole hostname, then either the // name was empty or it ended with a dot; neither is allowed. if start_of_label { return Err(TlsError::UnrecognizedName); } // safety: every byte was already checked for being a valid subset of UTF-8 let name = unsafe { String::from_utf8_unchecked(name) }; return Ok(name); } // None of the names were of the right type, and section 4.2 says "There MUST NOT be more // than one extension of the same type in a given extension block", so there definitely // isn't a server name in this ClientHello. break; } // Like when the extensions block is absent, pretend as if a server name was present but not // recognized. Err(TlsError::UnrecognizedName) } fn hash_hostname(hostname: String) -> PathBuf { #[cfg(feature = "hashed")] let hostname = { use blake2::{Blake2s, Digest}; let hash = Blake2s::digest(hostname.as_bytes()); base64::encode_config(&hash, base64::URL_SAFE_NO_PAD) }; hostname.into() } async fn connect_backend<R: AsyncReadExt>( source: R, local: SocketAddr, remote: SocketAddr, ) -> TlsResult<(R, net::UnixStream)> { let mut source = TlsHandshakeReader::new(source); // timeout can return a "Elapsed" error, or else return the result from get_server_name, which // might be a TlsError. So there are two "?" here to unwrap both. let name = timeout(Duration::from_secs(10), get_server_name(&mut source)).await??; let path = hash_hostname(name); // The client sent a name and it's been validated to be safe to use as a path. Consider it a // valid server name if connecting to the path doesn't return any of these errors: // - is a directory (NotFound after joining a relative path) // - which contains an entry named "tls-socket" (NotFound) // - which is accessible to this proxy (PermissionDenied) // - and is a listening socket (ConnectionRefused) // If it isn't a valid server name, then that's the error to report. Anything else is not the // client's fault. let mut backend = net::UnixStream::connect(path.join("tls-socket")) .await .map_err(|e| match e.kind() { ErrorKind::NotFound | ErrorKind::PermissionDenied | ErrorKind::ConnectionRefused =>
_ => TlsError::InternalError, })?; // After this point, all I/O errors are internal errors. // If this file exists, turn on the PROXY protocol. // NOTE: This is a blocking syscall, but stat should be fast enough that it's not worth // spawning off a thread. if std::fs::metadata(path.join("send-proxy-v1")).is_ok() { let header = format!( "PROXY {} {} {} {} {}\r\n", match remote { SocketAddr::V4(_) => "TCP4", SocketAddr::V6(_) => "TCP6", }, remote.ip(), local.ip(), remote.port(), local.port(), ); backend.write_all(header.as_bytes()).await?; } let source = source.into_source(&mut backend).await?; Ok((source, backend)) } async fn handle_connection(mut client: net::TcpStream, local: SocketAddr, remote: SocketAddr) { let (client_in, mut client_out) = client.split(); let (client_in, mut backend) = match connect_backend(client_in, local, remote).await { Ok(r) => r, Err(e) => { // Try to send an alert before closing the connection, but if that fails, don't worry // about it... they'll figure it out eventually. let _ = client_out .write_all(&[ TLS_ALERT_CONTENT_TYPE, TLS_LEGACY_RECORD_VERSION[0], TLS_LEGACY_RECORD_VERSION[1], TLS_ALERT_LENGTH[0], TLS_ALERT_LENGTH[1], TLS_ALERT_LEVEL_FATAL, // AlertDescription comes from the returned error; see TlsError above e as u8, ]) .await; return; } }; let (backend_in, backend_out) = backend.split(); // Ignore errors in either direction; just half-close the destination when the source stops // being readable. And if that fails, ignore that too. async fn copy_all<R, W>(mut from: R, mut to: W) where R: AsyncReadExt + Unpin, W: AsyncWriteExt + Unpin, { let _ = io::copy(&mut from, &mut to).await; let _ = to.shutdown().await; } tokio::join!( copy_all(client_in, backend_out), copy_all(backend_in, client_out), ); } async fn main_loop() -> io::Result<()> { // safety: the rest of the program must not use stdin let listener = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(0) }; // Assume stdin is an already bound and listening TCP socket. let mut listener = net::TcpListener::from_std(listener)?; // Asking for the listening socket's local address has the side effect of checking that it is // actually a TCP socket. let local = listener.local_addr()?; println!("listening on {}", local); let mut graceful_shutdown = signal(SignalKind::hangup())?; loop { tokio::select!( result = listener.accept() => result.map(|(socket, remote)| { let local = socket.local_addr().unwrap_or(local); task::spawn_local(handle_connection(socket, local, remote)); })?, Some(_) = graceful_shutdown.recv() => break, ); } println!("got SIGHUP, shutting down"); Ok(()) } #[tokio::main] async fn main() -> io::Result<()> { let local = task::LocalSet::new(); local.run_until(main_loop()).await?; timeout(Duration::from_secs(10), local) .await .map_err(|_| ErrorKind::TimedOut.into()) }
{ TlsError::UnrecognizedName }
conditional_block
main.rs
// This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from // scratch based on a careful reading of the TLS 1.3 specification. use std::net::SocketAddr; use std::path::PathBuf; use std::time::Duration; use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind}; use tokio::net; use tokio::signal::unix::{signal, SignalKind}; use tokio::task; use tokio::time::{timeout, Elapsed}; // Unless otherwise specified, all quotes are from RFC 8446 (TLS 1.3). // legacy_record_version: "MUST be set to 0x0303 for all records generated by a TLS // 1.3 implementation" const TLS_LEGACY_RECORD_VERSION: [u8; 2] = [0x03, 0x03]; const TLS_HANDSHAKE_CONTENT_TYPE: u8 = 0x16; const TLS_HANDSHAKE_TYPE_CLIENT_HELLO: u8 = 0x01; const TLS_EXTENSION_SNI: usize = 0x0000; const TLS_SNI_HOST_NAME_TYPE: u8 = 0; const TLS_ALERT_CONTENT_TYPE: u8 = 21; const TLS_ALERT_LENGTH: [u8; 2] = [0x00, 0x02]; const TLS_ALERT_LEVEL_FATAL: u8 = 2; enum TlsError { UnexpectedMessage = 10, RecordOverflow = 22, DecodeError = 50, InternalError = 80, UserCanceled = 90, UnrecognizedName = 112, } impl From<Error> for TlsError { fn from(_error: Error) -> Self { TlsError::InternalError } } impl From<Elapsed> for TlsError { fn from(_error: Elapsed) -> Self { TlsError::UserCanceled } } type TlsResult<O> = Result<O, TlsError>; struct TlsHandshakeReader<R> { source: R, buffer: Vec<u8>, offset: usize, limit: usize, } fn check_length(length: usize, limit: &mut usize) -> TlsResult<()> { *limit = limit.checked_sub(length).ok_or(TlsError::DecodeError)?; Ok(()) } impl<R: AsyncReadExt> TlsHandshakeReader<R> { fn new(source: R) -> Self { TlsHandshakeReader { source: source, buffer: Vec::with_capacity(4096), offset: 0, limit: 0, } } fn seek(&mut self, offset: usize, limit: &mut usize) -> TlsResult<()> { self.offset += offset; check_length(offset, limit) } async fn fill_to(&mut self, target: usize) -> TlsResult<()> { while self.buffer.len() < target { if self.source.read_buf(&mut self.buffer).await? == 0 { return Err(TlsError::DecodeError); } } Ok(()) } async fn read(&mut self) -> TlsResult<u8> { while self.offset >= self.limit { self.fill_to(self.limit + 5).await?; // section 5.1: "Handshake messages MUST NOT be interleaved with other record types. // That is, if a handshake message is split over two or more records, there MUST NOT be // any other records between them." if self.buffer[self.limit]!= TLS_HANDSHAKE_CONTENT_TYPE { return Err(TlsError::UnexpectedMessage); } let length = (self.buffer[self.limit + 3] as usize) << 8 | (self.buffer[self.limit + 4] as usize); // section 5.1: "Implementations MUST NOT send zero-length fragments of Handshake // types, even if those fragments contain padding." if length == 0 { return Err(TlsError::DecodeError); } // section 5.1: "The record layer fragments information blocks into TLSPlaintext // records carrying data in chunks of 2^14 bytes or less." if length > (1 << 14) { return Err(TlsError::RecordOverflow); } self.offset += 5; self.limit += 5 + length;
Ok(v) } async fn read_length(&mut self, length: u8) -> TlsResult<usize> { debug_assert!(length > 0 && length <= 4); let mut result = 0; for _ in 0..length { result <<= 8; result |= self.read().await? as usize; } Ok(result) } async fn into_source<W: AsyncWriteExt + Unpin>(self, dest: &mut W) -> io::Result<R> { dest.write_all(&self.buffer[..]).await?; Ok(self.source) } } async fn get_server_name<R: AsyncReadExt>(source: &mut TlsHandshakeReader<R>) -> TlsResult<String> { // section 4.1.2: "When a client first connects to a server, it is REQUIRED to send the // ClientHello as its first TLS message." if source.read().await?!= TLS_HANDSHAKE_TYPE_CLIENT_HELLO { return Err(TlsError::UnexpectedMessage); } let mut hello_length = source.read_length(3).await?; // skip legacy_version (2) and random (32) source.seek(34, &mut hello_length)?; // skip legacy_session_id check_length(1, &mut hello_length)?; let length = source.read_length(1).await?; source.seek(length, &mut hello_length)?; // skip cipher_suites check_length(2, &mut hello_length)?; let length = source.read_length(2).await?; source.seek(length, &mut hello_length)?; // skip legacy_compression_methods check_length(1, &mut hello_length)?; let length = source.read_length(1).await?; source.seek(length, &mut hello_length)?; // section 4.1.2: "TLS 1.3 servers might receive ClientHello messages without an extensions // field from prior versions of TLS. The presence of extensions can be detected by determining // whether there are bytes following the compression_methods field at the end of the // ClientHello. Note that this method of detecting optional data differs from the normal TLS // method of having a variable-length field, but it is used for compatibility with TLS before // extensions were defined.... If negotiating a version of TLS prior to 1.3, a server MUST // check that the message either contains no data after legacy_compression_methods or that it // contains a valid extensions block with no data following. If not, then it MUST abort the // handshake with a "decode_error" alert." // // If there is no extensions block, treat it like a server name extension was present but with // an unrecognized name. I don't think the spec allows this, but it doesn't NOT allow it? if hello_length == 0 { return Err(TlsError::UnrecognizedName); } // ClientHello ends immediately after the extensions check_length(2, &mut hello_length)?; if hello_length!= source.read_length(2).await? { return Err(TlsError::DecodeError); } while hello_length > 0 { check_length(4, &mut hello_length)?; let extension = source.read_length(2).await?; let mut length = source.read_length(2).await?; if extension!= TLS_EXTENSION_SNI { source.seek(length, &mut hello_length)?; continue; } check_length(length, &mut hello_length)?; // This extension ends immediately after server_name_list check_length(2, &mut length)?; if length!= source.read_length(2).await? { return Err(TlsError::DecodeError); } while length > 0 { check_length(3, &mut length)?; let name_type = source.read().await?; let name_length = source.read_length(2).await?; if name_type!= TLS_SNI_HOST_NAME_TYPE { source.seek(name_length, &mut length)?; continue; } check_length(name_length, &mut length)?; // RFC 6066 section 3: "The ServerNameList MUST NOT contain more than one name of the // same name_type." So we can just extract the first one we find. // Hostnames are limited to 255 octets with a trailing dot, but RFC 6066 prohibits the // trailing dot, so the limit here is 254 octets. Enforcing this limit ensures an // attacker can't make us heap-allocate 64kB for a hostname we'll never match. if name_length > 254 { return Err(TlsError::UnrecognizedName); } // The following validation rules ensure that we won't return a hostname which could // lead to pathname traversal (e.g. "..", "", or "a/b") and that semantically // equivalent hostnames are only returned in a canonical form. This does not validate // anything else about the hostname, such as length limits on individual labels. let mut name = Vec::with_capacity(name_length); let mut start_of_label = true; for _ in 0..name_length { let b = source.read().await?.to_ascii_lowercase(); if start_of_label && (b == b'-' || b == b'.') { // a hostname label can't start with dot or dash return Err(TlsError::UnrecognizedName); } // the next byte is the start of a label iff this one was a dot start_of_label = b'.' == b; match b { b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' => name.push(b), _ => return Err(TlsError::UnrecognizedName), } } // If we're expecting a new label after reading the whole hostname, then either the // name was empty or it ended with a dot; neither is allowed. if start_of_label { return Err(TlsError::UnrecognizedName); } // safety: every byte was already checked for being a valid subset of UTF-8 let name = unsafe { String::from_utf8_unchecked(name) }; return Ok(name); } // None of the names were of the right type, and section 4.2 says "There MUST NOT be more // than one extension of the same type in a given extension block", so there definitely // isn't a server name in this ClientHello. break; } // Like when the extensions block is absent, pretend as if a server name was present but not // recognized. Err(TlsError::UnrecognizedName) } fn hash_hostname(hostname: String) -> PathBuf { #[cfg(feature = "hashed")] let hostname = { use blake2::{Blake2s, Digest}; let hash = Blake2s::digest(hostname.as_bytes()); base64::encode_config(&hash, base64::URL_SAFE_NO_PAD) }; hostname.into() } async fn connect_backend<R: AsyncReadExt>( source: R, local: SocketAddr, remote: SocketAddr, ) -> TlsResult<(R, net::UnixStream)> { let mut source = TlsHandshakeReader::new(source); // timeout can return a "Elapsed" error, or else return the result from get_server_name, which // might be a TlsError. So there are two "?" here to unwrap both. let name = timeout(Duration::from_secs(10), get_server_name(&mut source)).await??; let path = hash_hostname(name); // The client sent a name and it's been validated to be safe to use as a path. Consider it a // valid server name if connecting to the path doesn't return any of these errors: // - is a directory (NotFound after joining a relative path) // - which contains an entry named "tls-socket" (NotFound) // - which is accessible to this proxy (PermissionDenied) // - and is a listening socket (ConnectionRefused) // If it isn't a valid server name, then that's the error to report. Anything else is not the // client's fault. let mut backend = net::UnixStream::connect(path.join("tls-socket")) .await .map_err(|e| match e.kind() { ErrorKind::NotFound | ErrorKind::PermissionDenied | ErrorKind::ConnectionRefused => { TlsError::UnrecognizedName } _ => TlsError::InternalError, })?; // After this point, all I/O errors are internal errors. // If this file exists, turn on the PROXY protocol. // NOTE: This is a blocking syscall, but stat should be fast enough that it's not worth // spawning off a thread. if std::fs::metadata(path.join("send-proxy-v1")).is_ok() { let header = format!( "PROXY {} {} {} {} {}\r\n", match remote { SocketAddr::V4(_) => "TCP4", SocketAddr::V6(_) => "TCP6", }, remote.ip(), local.ip(), remote.port(), local.port(), ); backend.write_all(header.as_bytes()).await?; } let source = source.into_source(&mut backend).await?; Ok((source, backend)) } async fn handle_connection(mut client: net::TcpStream, local: SocketAddr, remote: SocketAddr) { let (client_in, mut client_out) = client.split(); let (client_in, mut backend) = match connect_backend(client_in, local, remote).await { Ok(r) => r, Err(e) => { // Try to send an alert before closing the connection, but if that fails, don't worry // about it... they'll figure it out eventually. let _ = client_out .write_all(&[ TLS_ALERT_CONTENT_TYPE, TLS_LEGACY_RECORD_VERSION[0], TLS_LEGACY_RECORD_VERSION[1], TLS_ALERT_LENGTH[0], TLS_ALERT_LENGTH[1], TLS_ALERT_LEVEL_FATAL, // AlertDescription comes from the returned error; see TlsError above e as u8, ]) .await; return; } }; let (backend_in, backend_out) = backend.split(); // Ignore errors in either direction; just half-close the destination when the source stops // being readable. And if that fails, ignore that too. async fn copy_all<R, W>(mut from: R, mut to: W) where R: AsyncReadExt + Unpin, W: AsyncWriteExt + Unpin, { let _ = io::copy(&mut from, &mut to).await; let _ = to.shutdown().await; } tokio::join!( copy_all(client_in, backend_out), copy_all(backend_in, client_out), ); } async fn main_loop() -> io::Result<()> { // safety: the rest of the program must not use stdin let listener = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(0) }; // Assume stdin is an already bound and listening TCP socket. let mut listener = net::TcpListener::from_std(listener)?; // Asking for the listening socket's local address has the side effect of checking that it is // actually a TCP socket. let local = listener.local_addr()?; println!("listening on {}", local); let mut graceful_shutdown = signal(SignalKind::hangup())?; loop { tokio::select!( result = listener.accept() => result.map(|(socket, remote)| { let local = socket.local_addr().unwrap_or(local); task::spawn_local(handle_connection(socket, local, remote)); })?, Some(_) = graceful_shutdown.recv() => break, ); } println!("got SIGHUP, shutting down"); Ok(()) } #[tokio::main] async fn main() -> io::Result<()> { let local = task::LocalSet::new(); local.run_until(main_loop()).await?; timeout(Duration::from_secs(10), local) .await .map_err(|_| ErrorKind::TimedOut.into()) }
} self.fill_to(self.offset + 1).await?; let v = self.buffer[self.offset]; self.offset += 1;
random_line_split
main.rs
// This implementation is inspired by https://github.com/dlundquist/sniproxy, but I wrote it from // scratch based on a careful reading of the TLS 1.3 specification. use std::net::SocketAddr; use std::path::PathBuf; use std::time::Duration; use tokio::io::{self, AsyncReadExt, AsyncWriteExt, Error, ErrorKind}; use tokio::net; use tokio::signal::unix::{signal, SignalKind}; use tokio::task; use tokio::time::{timeout, Elapsed}; // Unless otherwise specified, all quotes are from RFC 8446 (TLS 1.3). // legacy_record_version: "MUST be set to 0x0303 for all records generated by a TLS // 1.3 implementation" const TLS_LEGACY_RECORD_VERSION: [u8; 2] = [0x03, 0x03]; const TLS_HANDSHAKE_CONTENT_TYPE: u8 = 0x16; const TLS_HANDSHAKE_TYPE_CLIENT_HELLO: u8 = 0x01; const TLS_EXTENSION_SNI: usize = 0x0000; const TLS_SNI_HOST_NAME_TYPE: u8 = 0; const TLS_ALERT_CONTENT_TYPE: u8 = 21; const TLS_ALERT_LENGTH: [u8; 2] = [0x00, 0x02]; const TLS_ALERT_LEVEL_FATAL: u8 = 2; enum TlsError { UnexpectedMessage = 10, RecordOverflow = 22, DecodeError = 50, InternalError = 80, UserCanceled = 90, UnrecognizedName = 112, } impl From<Error> for TlsError { fn from(_error: Error) -> Self { TlsError::InternalError } } impl From<Elapsed> for TlsError { fn from(_error: Elapsed) -> Self { TlsError::UserCanceled } } type TlsResult<O> = Result<O, TlsError>; struct TlsHandshakeReader<R> { source: R, buffer: Vec<u8>, offset: usize, limit: usize, } fn
(length: usize, limit: &mut usize) -> TlsResult<()> { *limit = limit.checked_sub(length).ok_or(TlsError::DecodeError)?; Ok(()) } impl<R: AsyncReadExt> TlsHandshakeReader<R> { fn new(source: R) -> Self { TlsHandshakeReader { source: source, buffer: Vec::with_capacity(4096), offset: 0, limit: 0, } } fn seek(&mut self, offset: usize, limit: &mut usize) -> TlsResult<()> { self.offset += offset; check_length(offset, limit) } async fn fill_to(&mut self, target: usize) -> TlsResult<()> { while self.buffer.len() < target { if self.source.read_buf(&mut self.buffer).await? == 0 { return Err(TlsError::DecodeError); } } Ok(()) } async fn read(&mut self) -> TlsResult<u8> { while self.offset >= self.limit { self.fill_to(self.limit + 5).await?; // section 5.1: "Handshake messages MUST NOT be interleaved with other record types. // That is, if a handshake message is split over two or more records, there MUST NOT be // any other records between them." if self.buffer[self.limit]!= TLS_HANDSHAKE_CONTENT_TYPE { return Err(TlsError::UnexpectedMessage); } let length = (self.buffer[self.limit + 3] as usize) << 8 | (self.buffer[self.limit + 4] as usize); // section 5.1: "Implementations MUST NOT send zero-length fragments of Handshake // types, even if those fragments contain padding." if length == 0 { return Err(TlsError::DecodeError); } // section 5.1: "The record layer fragments information blocks into TLSPlaintext // records carrying data in chunks of 2^14 bytes or less." if length > (1 << 14) { return Err(TlsError::RecordOverflow); } self.offset += 5; self.limit += 5 + length; } self.fill_to(self.offset + 1).await?; let v = self.buffer[self.offset]; self.offset += 1; Ok(v) } async fn read_length(&mut self, length: u8) -> TlsResult<usize> { debug_assert!(length > 0 && length <= 4); let mut result = 0; for _ in 0..length { result <<= 8; result |= self.read().await? as usize; } Ok(result) } async fn into_source<W: AsyncWriteExt + Unpin>(self, dest: &mut W) -> io::Result<R> { dest.write_all(&self.buffer[..]).await?; Ok(self.source) } } async fn get_server_name<R: AsyncReadExt>(source: &mut TlsHandshakeReader<R>) -> TlsResult<String> { // section 4.1.2: "When a client first connects to a server, it is REQUIRED to send the // ClientHello as its first TLS message." if source.read().await?!= TLS_HANDSHAKE_TYPE_CLIENT_HELLO { return Err(TlsError::UnexpectedMessage); } let mut hello_length = source.read_length(3).await?; // skip legacy_version (2) and random (32) source.seek(34, &mut hello_length)?; // skip legacy_session_id check_length(1, &mut hello_length)?; let length = source.read_length(1).await?; source.seek(length, &mut hello_length)?; // skip cipher_suites check_length(2, &mut hello_length)?; let length = source.read_length(2).await?; source.seek(length, &mut hello_length)?; // skip legacy_compression_methods check_length(1, &mut hello_length)?; let length = source.read_length(1).await?; source.seek(length, &mut hello_length)?; // section 4.1.2: "TLS 1.3 servers might receive ClientHello messages without an extensions // field from prior versions of TLS. The presence of extensions can be detected by determining // whether there are bytes following the compression_methods field at the end of the // ClientHello. Note that this method of detecting optional data differs from the normal TLS // method of having a variable-length field, but it is used for compatibility with TLS before // extensions were defined.... If negotiating a version of TLS prior to 1.3, a server MUST // check that the message either contains no data after legacy_compression_methods or that it // contains a valid extensions block with no data following. If not, then it MUST abort the // handshake with a "decode_error" alert." // // If there is no extensions block, treat it like a server name extension was present but with // an unrecognized name. I don't think the spec allows this, but it doesn't NOT allow it? if hello_length == 0 { return Err(TlsError::UnrecognizedName); } // ClientHello ends immediately after the extensions check_length(2, &mut hello_length)?; if hello_length!= source.read_length(2).await? { return Err(TlsError::DecodeError); } while hello_length > 0 { check_length(4, &mut hello_length)?; let extension = source.read_length(2).await?; let mut length = source.read_length(2).await?; if extension!= TLS_EXTENSION_SNI { source.seek(length, &mut hello_length)?; continue; } check_length(length, &mut hello_length)?; // This extension ends immediately after server_name_list check_length(2, &mut length)?; if length!= source.read_length(2).await? { return Err(TlsError::DecodeError); } while length > 0 { check_length(3, &mut length)?; let name_type = source.read().await?; let name_length = source.read_length(2).await?; if name_type!= TLS_SNI_HOST_NAME_TYPE { source.seek(name_length, &mut length)?; continue; } check_length(name_length, &mut length)?; // RFC 6066 section 3: "The ServerNameList MUST NOT contain more than one name of the // same name_type." So we can just extract the first one we find. // Hostnames are limited to 255 octets with a trailing dot, but RFC 6066 prohibits the // trailing dot, so the limit here is 254 octets. Enforcing this limit ensures an // attacker can't make us heap-allocate 64kB for a hostname we'll never match. if name_length > 254 { return Err(TlsError::UnrecognizedName); } // The following validation rules ensure that we won't return a hostname which could // lead to pathname traversal (e.g. "..", "", or "a/b") and that semantically // equivalent hostnames are only returned in a canonical form. This does not validate // anything else about the hostname, such as length limits on individual labels. let mut name = Vec::with_capacity(name_length); let mut start_of_label = true; for _ in 0..name_length { let b = source.read().await?.to_ascii_lowercase(); if start_of_label && (b == b'-' || b == b'.') { // a hostname label can't start with dot or dash return Err(TlsError::UnrecognizedName); } // the next byte is the start of a label iff this one was a dot start_of_label = b'.' == b; match b { b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' => name.push(b), _ => return Err(TlsError::UnrecognizedName), } } // If we're expecting a new label after reading the whole hostname, then either the // name was empty or it ended with a dot; neither is allowed. if start_of_label { return Err(TlsError::UnrecognizedName); } // safety: every byte was already checked for being a valid subset of UTF-8 let name = unsafe { String::from_utf8_unchecked(name) }; return Ok(name); } // None of the names were of the right type, and section 4.2 says "There MUST NOT be more // than one extension of the same type in a given extension block", so there definitely // isn't a server name in this ClientHello. break; } // Like when the extensions block is absent, pretend as if a server name was present but not // recognized. Err(TlsError::UnrecognizedName) } fn hash_hostname(hostname: String) -> PathBuf { #[cfg(feature = "hashed")] let hostname = { use blake2::{Blake2s, Digest}; let hash = Blake2s::digest(hostname.as_bytes()); base64::encode_config(&hash, base64::URL_SAFE_NO_PAD) }; hostname.into() } async fn connect_backend<R: AsyncReadExt>( source: R, local: SocketAddr, remote: SocketAddr, ) -> TlsResult<(R, net::UnixStream)> { let mut source = TlsHandshakeReader::new(source); // timeout can return a "Elapsed" error, or else return the result from get_server_name, which // might be a TlsError. So there are two "?" here to unwrap both. let name = timeout(Duration::from_secs(10), get_server_name(&mut source)).await??; let path = hash_hostname(name); // The client sent a name and it's been validated to be safe to use as a path. Consider it a // valid server name if connecting to the path doesn't return any of these errors: // - is a directory (NotFound after joining a relative path) // - which contains an entry named "tls-socket" (NotFound) // - which is accessible to this proxy (PermissionDenied) // - and is a listening socket (ConnectionRefused) // If it isn't a valid server name, then that's the error to report. Anything else is not the // client's fault. let mut backend = net::UnixStream::connect(path.join("tls-socket")) .await .map_err(|e| match e.kind() { ErrorKind::NotFound | ErrorKind::PermissionDenied | ErrorKind::ConnectionRefused => { TlsError::UnrecognizedName } _ => TlsError::InternalError, })?; // After this point, all I/O errors are internal errors. // If this file exists, turn on the PROXY protocol. // NOTE: This is a blocking syscall, but stat should be fast enough that it's not worth // spawning off a thread. if std::fs::metadata(path.join("send-proxy-v1")).is_ok() { let header = format!( "PROXY {} {} {} {} {}\r\n", match remote { SocketAddr::V4(_) => "TCP4", SocketAddr::V6(_) => "TCP6", }, remote.ip(), local.ip(), remote.port(), local.port(), ); backend.write_all(header.as_bytes()).await?; } let source = source.into_source(&mut backend).await?; Ok((source, backend)) } async fn handle_connection(mut client: net::TcpStream, local: SocketAddr, remote: SocketAddr) { let (client_in, mut client_out) = client.split(); let (client_in, mut backend) = match connect_backend(client_in, local, remote).await { Ok(r) => r, Err(e) => { // Try to send an alert before closing the connection, but if that fails, don't worry // about it... they'll figure it out eventually. let _ = client_out .write_all(&[ TLS_ALERT_CONTENT_TYPE, TLS_LEGACY_RECORD_VERSION[0], TLS_LEGACY_RECORD_VERSION[1], TLS_ALERT_LENGTH[0], TLS_ALERT_LENGTH[1], TLS_ALERT_LEVEL_FATAL, // AlertDescription comes from the returned error; see TlsError above e as u8, ]) .await; return; } }; let (backend_in, backend_out) = backend.split(); // Ignore errors in either direction; just half-close the destination when the source stops // being readable. And if that fails, ignore that too. async fn copy_all<R, W>(mut from: R, mut to: W) where R: AsyncReadExt + Unpin, W: AsyncWriteExt + Unpin, { let _ = io::copy(&mut from, &mut to).await; let _ = to.shutdown().await; } tokio::join!( copy_all(client_in, backend_out), copy_all(backend_in, client_out), ); } async fn main_loop() -> io::Result<()> { // safety: the rest of the program must not use stdin let listener = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(0) }; // Assume stdin is an already bound and listening TCP socket. let mut listener = net::TcpListener::from_std(listener)?; // Asking for the listening socket's local address has the side effect of checking that it is // actually a TCP socket. let local = listener.local_addr()?; println!("listening on {}", local); let mut graceful_shutdown = signal(SignalKind::hangup())?; loop { tokio::select!( result = listener.accept() => result.map(|(socket, remote)| { let local = socket.local_addr().unwrap_or(local); task::spawn_local(handle_connection(socket, local, remote)); })?, Some(_) = graceful_shutdown.recv() => break, ); } println!("got SIGHUP, shutting down"); Ok(()) } #[tokio::main] async fn main() -> io::Result<()> { let local = task::LocalSet::new(); local.run_until(main_loop()).await?; timeout(Duration::from_secs(10), local) .await .map_err(|_| ErrorKind::TimedOut.into()) }
check_length
identifier_name
app.rs
use crate::{ auth::Resource, default_resource, diffable, error::ServiceError, generation, models::{ fix_null_default, sql::{slice_iter, SelectBuilder}, Lock, TypedAlias, }, update_aliases, Client, }; use async_trait::async_trait; use chrono::{DateTime, Utc}; use core::pin::Pin; use drogue_client::{meta, registry}; use drogue_cloud_service_api::{auth::user::UserInformation, labels::LabelSelector}; use futures::{future, Stream, TryStreamExt}; use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use std::collections::{hash_map::RandomState, HashMap, HashSet}; use tokio_postgres::{ types::{Json, ToSql, Type}, Row, }; use uuid::Uuid; /// An application entity record. pub struct Application { pub uid: Uuid, pub name: String, pub labels: HashMap<String, String>, pub annotations: HashMap<String, String>, pub creation_timestamp: DateTime<Utc>, pub resource_version: Uuid, pub generation: u64, pub deletion_timestamp: Option<DateTime<Utc>>, pub finalizers: Vec<String>, /// ownership information pub owner: Option<String>, /// transfer to new owner pub transfer_owner: Option<String>, /// members list pub members: IndexMap<String, MemberEntry>, /// arbitrary payload pub data: Value, } diffable!(Application); generation!(Application => generation); default_resource!(Application); impl Resource for Application { fn owner(&self) -> Option<&str> { self.owner.as_deref() } fn members(&self) -> &IndexMap<String, MemberEntry> { &self.members } } #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Role { /// Allow everything, including changing members Admin, /// Allow reading and writing, but not changing members. Manager, /// Allow reading only. Reader, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct MemberEntry { pub role: Role, } /// Extract a section from the application data. Prevents cloning the whole struct. fn extract_sect(mut app: Application, key: &str) -> (Application, Option<Map<String, Value>>) { let sect = app .data .get_mut(key) .map(|v| v.take()) .and_then(|v| match v { Value::Object(v) => Some(v), _ => None, }); (app, sect) } impl From<Application> for registry::v1::Application { fn from(app: Application) -> Self { let (app, spec) = extract_sect(app, "spec"); let (app, status) = extract_sect(app, "status"); registry::v1::Application { metadata: meta::v1::NonScopedMetadata { uid: app.uid.to_string(), name: app.name, labels: app.labels, annotations: app.annotations, creation_timestamp: app.creation_timestamp, generation: app.generation, resource_version: app.resource_version.to_string(), deletion_timestamp: app.deletion_timestamp, finalizers: app.finalizers, }, spec: spec.unwrap_or_default(), status: status.unwrap_or_default(), } } } #[async_trait] pub trait ApplicationAccessor { /// Lookup an application async fn lookup(&self, alias: &str) -> Result<Option<Application>, ServiceError>; /// Delete an application async fn delete(&self, app: &str) -> Result<(), ServiceError>; /// Get an application async fn get(&self, app: &str, lock: Lock) -> Result<Option<Application>, ServiceError> { Ok(self .list( Some(app), LabelSelector::default(), Some(1), None, None, lock, &[], ) .await? .try_next() .await?) } /// Get a list of applications async fn list( &self, name: Option<&str>, labels: LabelSelector, limit: Option<usize>, offset: Option<usize>, id: Option<&UserInformation>, lock: Lock, sort: &[&str], ) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError>; /// Create a new application async fn create( &self, application: Application, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError>; /// Update an existing application's data async fn update_data( &self, application: Application, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError>; /// Update an existing application's owner information async fn update_transfer( &self, app: String, owner: Option<String>, transfer_owner: Option<String>, ) -> Result<u64, ServiceError>; /// Set the member list async fn set_members( &self, app: &str, members: IndexMap<String, MemberEntry>, ) -> Result<u64, ServiceError>; } pub struct PostgresApplicationAccessor<'c, C: Client> { client: &'c C, } impl<'c, C: Client> PostgresApplicationAccessor<'c, C> { pub fn new(client: &'c C) -> Self { Self { client } } pub fn from_row(row: Row) -> Result<Application, tokio_postgres::Error> { log::debug!("Row: {:?}", row); Ok(Application { uid: row.try_get("UID")?, name: row.try_get("NAME")?, creation_timestamp: row.try_get("CREATION_TIMESTAMP")?, generation: row.try_get::<_, i64>("GENERATION")? as u64, resource_version: row.try_get("RESOURCE_VERSION")?, labels: super::row_to_map(&row, "LABELS")?, annotations: super::row_to_map(&row, "ANNOTATIONS")?, deletion_timestamp: row.try_get("DELETION_TIMESTAMP")?, finalizers: super::row_to_vec(&row, "FINALIZERS")?, owner: row.try_get("OWNER")?, transfer_owner: row.try_get("TRANSFER_OWNER")?, members: row .try_get::<_, Json<IndexMap<String, MemberEntry>>>("MEMBERS") .map(|json| json.0) .or_else(fix_null_default)?, data: row.try_get::<_, Json<_>>("DATA")?.0, }) } async fn insert_aliases( &self, id: &str, aliases: &HashSet<TypedAlias>, ) -> Result<(), tokio_postgres::Error> { if aliases.is_empty() { return Ok(()); } let stmt = self .client .prepare_typed( "INSERT INTO APPLICATION_ALIASES (APP, TYPE, ALIAS) VALUES ($1, $2, $3)", &[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR], ) .await?; for alias in aliases { self.client .execute(&stmt, &[&id, &alias.0, &alias.1]) .await?; } Ok(()) } } trait Param: ToSql + Sync {} #[async_trait] impl<'c, C: Client> ApplicationAccessor for PostgresApplicationAccessor<'c, C> { async fn lookup(&self, alias: &str) -> Result<Option<Application>, ServiceError> { let sql = r#" SELECT A2.NAME, A2.UID, A2.LABELS, A2.CREATION_TIMESTAMP, A2.GENERATION, A2.RESOURCE_VERSION, A2.ANNOTATIONS, A2.DELETION_TIMESTAMP, A2.FINALIZERS, A2.OWNER, A2.TRANSFER_OWNER, A2.MEMBERS, A2.DATA FROM APPLICATION_ALIASES A1 INNER JOIN APPLICATIONS A2 ON A1.APP=A2.NAME WHERE A1.ALIAS = $1 "#; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let row = self.client.query_opt(&stmt, &[&alias]).await?; Ok(row.map(Self::from_row).transpose()?) } async fn delete(&self, id: &str) -> Result<(), ServiceError> { let sql = "DELETE FROM APPLICATIONS WHERE NAME = $1"; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let count = self.client.execute(&stmt, &[&id]).await?; if count > 0 { Ok(()) } else { Err(ServiceError::NotFound) } } async fn list( &self, name: Option<&str>, labels: LabelSelector, limit: Option<usize>, offset: Option<usize>, id: Option<&UserInformation>, lock: Lock, sort: &[&str], ) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError>
let builder = SelectBuilder::new(select, Vec::new(), Vec::new()) .name(&name) .labels(&labels.0) .auth_read(&id) .lock(lock) .sort(sort) .limit(limit) .offset(offset); let (select, params, types) = builder.build(); let stmt = self.client.prepare_typed(&select, &types).await?; let stream = self .client .query_raw(&stmt, slice_iter(&params[..])) .await .map_err(|err| { log::debug!("Failed to get: {}", err); err })? .and_then(|row| future::ready(Self::from_row(row))) .map_err(ServiceError::Database); Ok(Box::pin(stream)) } async fn create( &self, application: Application, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError> { let name = application.name; let data = application.data; let labels = application.labels; let annotations = application.annotations; self.client .execute( r#" INSERT INTO APPLICATIONS ( NAME, UID, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, FINALIZERS, OWNER, DATA ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 )"#, &[ &name, &application.uid, &Json(labels), &Json(annotations), &Utc::now(), &(application.generation as i64), &Uuid::new_v4(), &application.finalizers, &application.owner, &Json(data), ], ) .await?; self.insert_aliases(&name, &aliases).await?; Ok(()) } async fn update_data( &self, application: Application, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError> { let name = application.name; let labels = application.labels; let data = application.data; let annotations = application.annotations; // update device let count = self .client .execute( r#" UPDATE APPLICATIONS SET LABELS = $2, ANNOTATIONS = $3, GENERATION = $4, RESOURCE_VERSION = $5, DELETION_TIMESTAMP = $6, FINALIZERS = $7, DATA = $8 WHERE NAME = $1 "#, &[ &name, &Json(labels), &Json(annotations), &(application.generation as i64), &Uuid::new_v4(), &application.deletion_timestamp, &application.finalizers, &Json(data), ], ) .await?; update_aliases!(count, aliases, |aliases| { // clear existing aliases let sql = "DELETE FROM APPLICATION_ALIASES WHERE APP=$1"; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; self.client.execute(&stmt, &[&name]).await?; // insert new alias set self.insert_aliases(&name, &aliases).await?; Ok(count) }) } async fn update_transfer( &self, app: String, owner: Option<String>, transfer_owner: Option<String>, ) -> Result<u64, ServiceError> { // update application let sql = r#" UPDATE APPLICATIONS SET OWNER = $2, TRANSFER_OWNER = $3 WHERE NAME = $1 "#; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR]) .await?; let count = self .client .execute(&stmt, &[&app, &owner, &transfer_owner]) .await?; Ok(count) } async fn set_members( &self, app: &str, members: IndexMap<String, MemberEntry>, ) -> Result<u64, ServiceError> { // update application let sql = r#" UPDATE APPLICATIONS SET MEMBERS = $2 WHERE NAME = $1 "#; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::JSONB]) .await?; let count = self.client.execute(&stmt, &[&app, &Json(members)]).await?; Ok(count) } }
{ let select = r#" SELECT NAME, UID, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, DELETION_TIMESTAMP, FINALIZERS, OWNER, TRANSFER_OWNER, MEMBERS, DATA FROM APPLICATIONS "# .to_string();
identifier_body
app.rs
use crate::{ auth::Resource, default_resource, diffable, error::ServiceError, generation, models::{ fix_null_default, sql::{slice_iter, SelectBuilder}, Lock, TypedAlias, }, update_aliases, Client, }; use async_trait::async_trait; use chrono::{DateTime, Utc}; use core::pin::Pin; use drogue_client::{meta, registry}; use drogue_cloud_service_api::{auth::user::UserInformation, labels::LabelSelector}; use futures::{future, Stream, TryStreamExt}; use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use std::collections::{hash_map::RandomState, HashMap, HashSet}; use tokio_postgres::{ types::{Json, ToSql, Type}, Row, }; use uuid::Uuid; /// An application entity record. pub struct Application { pub uid: Uuid, pub name: String, pub labels: HashMap<String, String>, pub annotations: HashMap<String, String>, pub creation_timestamp: DateTime<Utc>, pub resource_version: Uuid, pub generation: u64, pub deletion_timestamp: Option<DateTime<Utc>>, pub finalizers: Vec<String>, /// ownership information pub owner: Option<String>, /// transfer to new owner pub transfer_owner: Option<String>, /// members list pub members: IndexMap<String, MemberEntry>, /// arbitrary payload pub data: Value, } diffable!(Application); generation!(Application => generation); default_resource!(Application); impl Resource for Application { fn owner(&self) -> Option<&str> { self.owner.as_deref() } fn members(&self) -> &IndexMap<String, MemberEntry> { &self.members } } #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Role { /// Allow everything, including changing members Admin, /// Allow reading and writing, but not changing members. Manager, /// Allow reading only. Reader, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct MemberEntry { pub role: Role, } /// Extract a section from the application data. Prevents cloning the whole struct. fn extract_sect(mut app: Application, key: &str) -> (Application, Option<Map<String, Value>>) { let sect = app .data .get_mut(key) .map(|v| v.take()) .and_then(|v| match v { Value::Object(v) => Some(v), _ => None, }); (app, sect) } impl From<Application> for registry::v1::Application { fn from(app: Application) -> Self { let (app, spec) = extract_sect(app, "spec"); let (app, status) = extract_sect(app, "status"); registry::v1::Application { metadata: meta::v1::NonScopedMetadata { uid: app.uid.to_string(), name: app.name, labels: app.labels, annotations: app.annotations, creation_timestamp: app.creation_timestamp, generation: app.generation, resource_version: app.resource_version.to_string(), deletion_timestamp: app.deletion_timestamp, finalizers: app.finalizers, }, spec: spec.unwrap_or_default(), status: status.unwrap_or_default(), } } } #[async_trait] pub trait ApplicationAccessor { /// Lookup an application async fn lookup(&self, alias: &str) -> Result<Option<Application>, ServiceError>; /// Delete an application async fn delete(&self, app: &str) -> Result<(), ServiceError>; /// Get an application async fn get(&self, app: &str, lock: Lock) -> Result<Option<Application>, ServiceError> { Ok(self .list( Some(app), LabelSelector::default(), Some(1), None, None, lock, &[], ) .await? .try_next() .await?) } /// Get a list of applications async fn list( &self, name: Option<&str>, labels: LabelSelector, limit: Option<usize>, offset: Option<usize>, id: Option<&UserInformation>, lock: Lock, sort: &[&str], ) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError>; /// Create a new application async fn create( &self, application: Application, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError>; /// Update an existing application's data async fn update_data( &self, application: Application, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError>; /// Update an existing application's owner information async fn update_transfer( &self, app: String, owner: Option<String>, transfer_owner: Option<String>, ) -> Result<u64, ServiceError>; /// Set the member list async fn set_members( &self, app: &str, members: IndexMap<String, MemberEntry>, ) -> Result<u64, ServiceError>; } pub struct PostgresApplicationAccessor<'c, C: Client> { client: &'c C, } impl<'c, C: Client> PostgresApplicationAccessor<'c, C> { pub fn new(client: &'c C) -> Self { Self { client } } pub fn from_row(row: Row) -> Result<Application, tokio_postgres::Error> { log::debug!("Row: {:?}", row); Ok(Application { uid: row.try_get("UID")?, name: row.try_get("NAME")?, creation_timestamp: row.try_get("CREATION_TIMESTAMP")?, generation: row.try_get::<_, i64>("GENERATION")? as u64, resource_version: row.try_get("RESOURCE_VERSION")?, labels: super::row_to_map(&row, "LABELS")?, annotations: super::row_to_map(&row, "ANNOTATIONS")?, deletion_timestamp: row.try_get("DELETION_TIMESTAMP")?, finalizers: super::row_to_vec(&row, "FINALIZERS")?, owner: row.try_get("OWNER")?, transfer_owner: row.try_get("TRANSFER_OWNER")?, members: row .try_get::<_, Json<IndexMap<String, MemberEntry>>>("MEMBERS") .map(|json| json.0) .or_else(fix_null_default)?, data: row.try_get::<_, Json<_>>("DATA")?.0, }) } async fn insert_aliases( &self, id: &str, aliases: &HashSet<TypedAlias>, ) -> Result<(), tokio_postgres::Error> { if aliases.is_empty() { return Ok(()); } let stmt = self .client .prepare_typed( "INSERT INTO APPLICATION_ALIASES (APP, TYPE, ALIAS) VALUES ($1, $2, $3)", &[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR], ) .await?; for alias in aliases { self.client .execute(&stmt, &[&id, &alias.0, &alias.1]) .await?; } Ok(()) } } trait Param: ToSql + Sync {} #[async_trait] impl<'c, C: Client> ApplicationAccessor for PostgresApplicationAccessor<'c, C> { async fn lookup(&self, alias: &str) -> Result<Option<Application>, ServiceError> { let sql = r#" SELECT A2.NAME, A2.UID, A2.LABELS, A2.CREATION_TIMESTAMP, A2.GENERATION, A2.RESOURCE_VERSION, A2.ANNOTATIONS, A2.DELETION_TIMESTAMP, A2.FINALIZERS, A2.OWNER, A2.TRANSFER_OWNER, A2.MEMBERS, A2.DATA FROM APPLICATION_ALIASES A1 INNER JOIN APPLICATIONS A2 ON A1.APP=A2.NAME WHERE A1.ALIAS = $1 "#; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let row = self.client.query_opt(&stmt, &[&alias]).await?; Ok(row.map(Self::from_row).transpose()?) } async fn delete(&self, id: &str) -> Result<(), ServiceError> { let sql = "DELETE FROM APPLICATIONS WHERE NAME = $1"; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let count = self.client.execute(&stmt, &[&id]).await?; if count > 0 { Ok(()) } else { Err(ServiceError::NotFound) } } async fn list( &self, name: Option<&str>, labels: LabelSelector, limit: Option<usize>,
{ let select = r#" SELECT NAME, UID, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, DELETION_TIMESTAMP, FINALIZERS, OWNER, TRANSFER_OWNER, MEMBERS, DATA FROM APPLICATIONS "# .to_string(); let builder = SelectBuilder::new(select, Vec::new(), Vec::new()) .name(&name) .labels(&labels.0) .auth_read(&id) .lock(lock) .sort(sort) .limit(limit) .offset(offset); let (select, params, types) = builder.build(); let stmt = self.client.prepare_typed(&select, &types).await?; let stream = self .client .query_raw(&stmt, slice_iter(&params[..])) .await .map_err(|err| { log::debug!("Failed to get: {}", err); err })? .and_then(|row| future::ready(Self::from_row(row))) .map_err(ServiceError::Database); Ok(Box::pin(stream)) } async fn create( &self, application: Application, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError> { let name = application.name; let data = application.data; let labels = application.labels; let annotations = application.annotations; self.client .execute( r#" INSERT INTO APPLICATIONS ( NAME, UID, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, FINALIZERS, OWNER, DATA ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 )"#, &[ &name, &application.uid, &Json(labels), &Json(annotations), &Utc::now(), &(application.generation as i64), &Uuid::new_v4(), &application.finalizers, &application.owner, &Json(data), ], ) .await?; self.insert_aliases(&name, &aliases).await?; Ok(()) } async fn update_data( &self, application: Application, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError> { let name = application.name; let labels = application.labels; let data = application.data; let annotations = application.annotations; // update device let count = self .client .execute( r#" UPDATE APPLICATIONS SET LABELS = $2, ANNOTATIONS = $3, GENERATION = $4, RESOURCE_VERSION = $5, DELETION_TIMESTAMP = $6, FINALIZERS = $7, DATA = $8 WHERE NAME = $1 "#, &[ &name, &Json(labels), &Json(annotations), &(application.generation as i64), &Uuid::new_v4(), &application.deletion_timestamp, &application.finalizers, &Json(data), ], ) .await?; update_aliases!(count, aliases, |aliases| { // clear existing aliases let sql = "DELETE FROM APPLICATION_ALIASES WHERE APP=$1"; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; self.client.execute(&stmt, &[&name]).await?; // insert new alias set self.insert_aliases(&name, &aliases).await?; Ok(count) }) } async fn update_transfer( &self, app: String, owner: Option<String>, transfer_owner: Option<String>, ) -> Result<u64, ServiceError> { // update application let sql = r#" UPDATE APPLICATIONS SET OWNER = $2, TRANSFER_OWNER = $3 WHERE NAME = $1 "#; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR]) .await?; let count = self .client .execute(&stmt, &[&app, &owner, &transfer_owner]) .await?; Ok(count) } async fn set_members( &self, app: &str, members: IndexMap<String, MemberEntry>, ) -> Result<u64, ServiceError> { // update application let sql = r#" UPDATE APPLICATIONS SET MEMBERS = $2 WHERE NAME = $1 "#; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::JSONB]) .await?; let count = self.client.execute(&stmt, &[&app, &Json(members)]).await?; Ok(count) } }
offset: Option<usize>, id: Option<&UserInformation>, lock: Lock, sort: &[&str], ) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError>
random_line_split
app.rs
use crate::{ auth::Resource, default_resource, diffable, error::ServiceError, generation, models::{ fix_null_default, sql::{slice_iter, SelectBuilder}, Lock, TypedAlias, }, update_aliases, Client, }; use async_trait::async_trait; use chrono::{DateTime, Utc}; use core::pin::Pin; use drogue_client::{meta, registry}; use drogue_cloud_service_api::{auth::user::UserInformation, labels::LabelSelector}; use futures::{future, Stream, TryStreamExt}; use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use std::collections::{hash_map::RandomState, HashMap, HashSet}; use tokio_postgres::{ types::{Json, ToSql, Type}, Row, }; use uuid::Uuid; /// An application entity record. pub struct Application { pub uid: Uuid, pub name: String, pub labels: HashMap<String, String>, pub annotations: HashMap<String, String>, pub creation_timestamp: DateTime<Utc>, pub resource_version: Uuid, pub generation: u64, pub deletion_timestamp: Option<DateTime<Utc>>, pub finalizers: Vec<String>, /// ownership information pub owner: Option<String>, /// transfer to new owner pub transfer_owner: Option<String>, /// members list pub members: IndexMap<String, MemberEntry>, /// arbitrary payload pub data: Value, } diffable!(Application); generation!(Application => generation); default_resource!(Application); impl Resource for Application { fn owner(&self) -> Option<&str> { self.owner.as_deref() } fn members(&self) -> &IndexMap<String, MemberEntry> { &self.members } } #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Role { /// Allow everything, including changing members Admin, /// Allow reading and writing, but not changing members. Manager, /// Allow reading only. Reader, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct MemberEntry { pub role: Role, } /// Extract a section from the application data. Prevents cloning the whole struct. fn extract_sect(mut app: Application, key: &str) -> (Application, Option<Map<String, Value>>) { let sect = app .data .get_mut(key) .map(|v| v.take()) .and_then(|v| match v { Value::Object(v) => Some(v), _ => None, }); (app, sect) } impl From<Application> for registry::v1::Application { fn from(app: Application) -> Self { let (app, spec) = extract_sect(app, "spec"); let (app, status) = extract_sect(app, "status"); registry::v1::Application { metadata: meta::v1::NonScopedMetadata { uid: app.uid.to_string(), name: app.name, labels: app.labels, annotations: app.annotations, creation_timestamp: app.creation_timestamp, generation: app.generation, resource_version: app.resource_version.to_string(), deletion_timestamp: app.deletion_timestamp, finalizers: app.finalizers, }, spec: spec.unwrap_or_default(), status: status.unwrap_or_default(), } } } #[async_trait] pub trait ApplicationAccessor { /// Lookup an application async fn lookup(&self, alias: &str) -> Result<Option<Application>, ServiceError>; /// Delete an application async fn delete(&self, app: &str) -> Result<(), ServiceError>; /// Get an application async fn get(&self, app: &str, lock: Lock) -> Result<Option<Application>, ServiceError> { Ok(self .list( Some(app), LabelSelector::default(), Some(1), None, None, lock, &[], ) .await? .try_next() .await?) } /// Get a list of applications async fn list( &self, name: Option<&str>, labels: LabelSelector, limit: Option<usize>, offset: Option<usize>, id: Option<&UserInformation>, lock: Lock, sort: &[&str], ) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError>; /// Create a new application async fn create( &self, application: Application, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError>; /// Update an existing application's data async fn update_data( &self, application: Application, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError>; /// Update an existing application's owner information async fn update_transfer( &self, app: String, owner: Option<String>, transfer_owner: Option<String>, ) -> Result<u64, ServiceError>; /// Set the member list async fn set_members( &self, app: &str, members: IndexMap<String, MemberEntry>, ) -> Result<u64, ServiceError>; } pub struct PostgresApplicationAccessor<'c, C: Client> { client: &'c C, } impl<'c, C: Client> PostgresApplicationAccessor<'c, C> { pub fn new(client: &'c C) -> Self { Self { client } } pub fn from_row(row: Row) -> Result<Application, tokio_postgres::Error> { log::debug!("Row: {:?}", row); Ok(Application { uid: row.try_get("UID")?, name: row.try_get("NAME")?, creation_timestamp: row.try_get("CREATION_TIMESTAMP")?, generation: row.try_get::<_, i64>("GENERATION")? as u64, resource_version: row.try_get("RESOURCE_VERSION")?, labels: super::row_to_map(&row, "LABELS")?, annotations: super::row_to_map(&row, "ANNOTATIONS")?, deletion_timestamp: row.try_get("DELETION_TIMESTAMP")?, finalizers: super::row_to_vec(&row, "FINALIZERS")?, owner: row.try_get("OWNER")?, transfer_owner: row.try_get("TRANSFER_OWNER")?, members: row .try_get::<_, Json<IndexMap<String, MemberEntry>>>("MEMBERS") .map(|json| json.0) .or_else(fix_null_default)?, data: row.try_get::<_, Json<_>>("DATA")?.0, }) } async fn insert_aliases( &self, id: &str, aliases: &HashSet<TypedAlias>, ) -> Result<(), tokio_postgres::Error> { if aliases.is_empty() { return Ok(()); } let stmt = self .client .prepare_typed( "INSERT INTO APPLICATION_ALIASES (APP, TYPE, ALIAS) VALUES ($1, $2, $3)", &[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR], ) .await?; for alias in aliases { self.client .execute(&stmt, &[&id, &alias.0, &alias.1]) .await?; } Ok(()) } } trait Param: ToSql + Sync {} #[async_trait] impl<'c, C: Client> ApplicationAccessor for PostgresApplicationAccessor<'c, C> { async fn lookup(&self, alias: &str) -> Result<Option<Application>, ServiceError> { let sql = r#" SELECT A2.NAME, A2.UID, A2.LABELS, A2.CREATION_TIMESTAMP, A2.GENERATION, A2.RESOURCE_VERSION, A2.ANNOTATIONS, A2.DELETION_TIMESTAMP, A2.FINALIZERS, A2.OWNER, A2.TRANSFER_OWNER, A2.MEMBERS, A2.DATA FROM APPLICATION_ALIASES A1 INNER JOIN APPLICATIONS A2 ON A1.APP=A2.NAME WHERE A1.ALIAS = $1 "#; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let row = self.client.query_opt(&stmt, &[&alias]).await?; Ok(row.map(Self::from_row).transpose()?) } async fn
(&self, id: &str) -> Result<(), ServiceError> { let sql = "DELETE FROM APPLICATIONS WHERE NAME = $1"; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let count = self.client.execute(&stmt, &[&id]).await?; if count > 0 { Ok(()) } else { Err(ServiceError::NotFound) } } async fn list( &self, name: Option<&str>, labels: LabelSelector, limit: Option<usize>, offset: Option<usize>, id: Option<&UserInformation>, lock: Lock, sort: &[&str], ) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError> { let select = r#" SELECT NAME, UID, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, DELETION_TIMESTAMP, FINALIZERS, OWNER, TRANSFER_OWNER, MEMBERS, DATA FROM APPLICATIONS "# .to_string(); let builder = SelectBuilder::new(select, Vec::new(), Vec::new()) .name(&name) .labels(&labels.0) .auth_read(&id) .lock(lock) .sort(sort) .limit(limit) .offset(offset); let (select, params, types) = builder.build(); let stmt = self.client.prepare_typed(&select, &types).await?; let stream = self .client .query_raw(&stmt, slice_iter(&params[..])) .await .map_err(|err| { log::debug!("Failed to get: {}", err); err })? .and_then(|row| future::ready(Self::from_row(row))) .map_err(ServiceError::Database); Ok(Box::pin(stream)) } async fn create( &self, application: Application, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError> { let name = application.name; let data = application.data; let labels = application.labels; let annotations = application.annotations; self.client .execute( r#" INSERT INTO APPLICATIONS ( NAME, UID, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, FINALIZERS, OWNER, DATA ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 )"#, &[ &name, &application.uid, &Json(labels), &Json(annotations), &Utc::now(), &(application.generation as i64), &Uuid::new_v4(), &application.finalizers, &application.owner, &Json(data), ], ) .await?; self.insert_aliases(&name, &aliases).await?; Ok(()) } async fn update_data( &self, application: Application, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError> { let name = application.name; let labels = application.labels; let data = application.data; let annotations = application.annotations; // update device let count = self .client .execute( r#" UPDATE APPLICATIONS SET LABELS = $2, ANNOTATIONS = $3, GENERATION = $4, RESOURCE_VERSION = $5, DELETION_TIMESTAMP = $6, FINALIZERS = $7, DATA = $8 WHERE NAME = $1 "#, &[ &name, &Json(labels), &Json(annotations), &(application.generation as i64), &Uuid::new_v4(), &application.deletion_timestamp, &application.finalizers, &Json(data), ], ) .await?; update_aliases!(count, aliases, |aliases| { // clear existing aliases let sql = "DELETE FROM APPLICATION_ALIASES WHERE APP=$1"; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; self.client.execute(&stmt, &[&name]).await?; // insert new alias set self.insert_aliases(&name, &aliases).await?; Ok(count) }) } async fn update_transfer( &self, app: String, owner: Option<String>, transfer_owner: Option<String>, ) -> Result<u64, ServiceError> { // update application let sql = r#" UPDATE APPLICATIONS SET OWNER = $2, TRANSFER_OWNER = $3 WHERE NAME = $1 "#; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR]) .await?; let count = self .client .execute(&stmt, &[&app, &owner, &transfer_owner]) .await?; Ok(count) } async fn set_members( &self, app: &str, members: IndexMap<String, MemberEntry>, ) -> Result<u64, ServiceError> { // update application let sql = r#" UPDATE APPLICATIONS SET MEMBERS = $2 WHERE NAME = $1 "#; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::JSONB]) .await?; let count = self.client.execute(&stmt, &[&app, &Json(members)]).await?; Ok(count) } }
delete
identifier_name
app.rs
use crate::{ auth::Resource, default_resource, diffable, error::ServiceError, generation, models::{ fix_null_default, sql::{slice_iter, SelectBuilder}, Lock, TypedAlias, }, update_aliases, Client, }; use async_trait::async_trait; use chrono::{DateTime, Utc}; use core::pin::Pin; use drogue_client::{meta, registry}; use drogue_cloud_service_api::{auth::user::UserInformation, labels::LabelSelector}; use futures::{future, Stream, TryStreamExt}; use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use std::collections::{hash_map::RandomState, HashMap, HashSet}; use tokio_postgres::{ types::{Json, ToSql, Type}, Row, }; use uuid::Uuid; /// An application entity record. pub struct Application { pub uid: Uuid, pub name: String, pub labels: HashMap<String, String>, pub annotations: HashMap<String, String>, pub creation_timestamp: DateTime<Utc>, pub resource_version: Uuid, pub generation: u64, pub deletion_timestamp: Option<DateTime<Utc>>, pub finalizers: Vec<String>, /// ownership information pub owner: Option<String>, /// transfer to new owner pub transfer_owner: Option<String>, /// members list pub members: IndexMap<String, MemberEntry>, /// arbitrary payload pub data: Value, } diffable!(Application); generation!(Application => generation); default_resource!(Application); impl Resource for Application { fn owner(&self) -> Option<&str> { self.owner.as_deref() } fn members(&self) -> &IndexMap<String, MemberEntry> { &self.members } } #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Role { /// Allow everything, including changing members Admin, /// Allow reading and writing, but not changing members. Manager, /// Allow reading only. Reader, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct MemberEntry { pub role: Role, } /// Extract a section from the application data. Prevents cloning the whole struct. fn extract_sect(mut app: Application, key: &str) -> (Application, Option<Map<String, Value>>) { let sect = app .data .get_mut(key) .map(|v| v.take()) .and_then(|v| match v { Value::Object(v) => Some(v), _ => None, }); (app, sect) } impl From<Application> for registry::v1::Application { fn from(app: Application) -> Self { let (app, spec) = extract_sect(app, "spec"); let (app, status) = extract_sect(app, "status"); registry::v1::Application { metadata: meta::v1::NonScopedMetadata { uid: app.uid.to_string(), name: app.name, labels: app.labels, annotations: app.annotations, creation_timestamp: app.creation_timestamp, generation: app.generation, resource_version: app.resource_version.to_string(), deletion_timestamp: app.deletion_timestamp, finalizers: app.finalizers, }, spec: spec.unwrap_or_default(), status: status.unwrap_or_default(), } } } #[async_trait] pub trait ApplicationAccessor { /// Lookup an application async fn lookup(&self, alias: &str) -> Result<Option<Application>, ServiceError>; /// Delete an application async fn delete(&self, app: &str) -> Result<(), ServiceError>; /// Get an application async fn get(&self, app: &str, lock: Lock) -> Result<Option<Application>, ServiceError> { Ok(self .list( Some(app), LabelSelector::default(), Some(1), None, None, lock, &[], ) .await? .try_next() .await?) } /// Get a list of applications async fn list( &self, name: Option<&str>, labels: LabelSelector, limit: Option<usize>, offset: Option<usize>, id: Option<&UserInformation>, lock: Lock, sort: &[&str], ) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError>; /// Create a new application async fn create( &self, application: Application, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError>; /// Update an existing application's data async fn update_data( &self, application: Application, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError>; /// Update an existing application's owner information async fn update_transfer( &self, app: String, owner: Option<String>, transfer_owner: Option<String>, ) -> Result<u64, ServiceError>; /// Set the member list async fn set_members( &self, app: &str, members: IndexMap<String, MemberEntry>, ) -> Result<u64, ServiceError>; } pub struct PostgresApplicationAccessor<'c, C: Client> { client: &'c C, } impl<'c, C: Client> PostgresApplicationAccessor<'c, C> { pub fn new(client: &'c C) -> Self { Self { client } } pub fn from_row(row: Row) -> Result<Application, tokio_postgres::Error> { log::debug!("Row: {:?}", row); Ok(Application { uid: row.try_get("UID")?, name: row.try_get("NAME")?, creation_timestamp: row.try_get("CREATION_TIMESTAMP")?, generation: row.try_get::<_, i64>("GENERATION")? as u64, resource_version: row.try_get("RESOURCE_VERSION")?, labels: super::row_to_map(&row, "LABELS")?, annotations: super::row_to_map(&row, "ANNOTATIONS")?, deletion_timestamp: row.try_get("DELETION_TIMESTAMP")?, finalizers: super::row_to_vec(&row, "FINALIZERS")?, owner: row.try_get("OWNER")?, transfer_owner: row.try_get("TRANSFER_OWNER")?, members: row .try_get::<_, Json<IndexMap<String, MemberEntry>>>("MEMBERS") .map(|json| json.0) .or_else(fix_null_default)?, data: row.try_get::<_, Json<_>>("DATA")?.0, }) } async fn insert_aliases( &self, id: &str, aliases: &HashSet<TypedAlias>, ) -> Result<(), tokio_postgres::Error> { if aliases.is_empty()
let stmt = self .client .prepare_typed( "INSERT INTO APPLICATION_ALIASES (APP, TYPE, ALIAS) VALUES ($1, $2, $3)", &[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR], ) .await?; for alias in aliases { self.client .execute(&stmt, &[&id, &alias.0, &alias.1]) .await?; } Ok(()) } } trait Param: ToSql + Sync {} #[async_trait] impl<'c, C: Client> ApplicationAccessor for PostgresApplicationAccessor<'c, C> { async fn lookup(&self, alias: &str) -> Result<Option<Application>, ServiceError> { let sql = r#" SELECT A2.NAME, A2.UID, A2.LABELS, A2.CREATION_TIMESTAMP, A2.GENERATION, A2.RESOURCE_VERSION, A2.ANNOTATIONS, A2.DELETION_TIMESTAMP, A2.FINALIZERS, A2.OWNER, A2.TRANSFER_OWNER, A2.MEMBERS, A2.DATA FROM APPLICATION_ALIASES A1 INNER JOIN APPLICATIONS A2 ON A1.APP=A2.NAME WHERE A1.ALIAS = $1 "#; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let row = self.client.query_opt(&stmt, &[&alias]).await?; Ok(row.map(Self::from_row).transpose()?) } async fn delete(&self, id: &str) -> Result<(), ServiceError> { let sql = "DELETE FROM APPLICATIONS WHERE NAME = $1"; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; let count = self.client.execute(&stmt, &[&id]).await?; if count > 0 { Ok(()) } else { Err(ServiceError::NotFound) } } async fn list( &self, name: Option<&str>, labels: LabelSelector, limit: Option<usize>, offset: Option<usize>, id: Option<&UserInformation>, lock: Lock, sort: &[&str], ) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError> { let select = r#" SELECT NAME, UID, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, DELETION_TIMESTAMP, FINALIZERS, OWNER, TRANSFER_OWNER, MEMBERS, DATA FROM APPLICATIONS "# .to_string(); let builder = SelectBuilder::new(select, Vec::new(), Vec::new()) .name(&name) .labels(&labels.0) .auth_read(&id) .lock(lock) .sort(sort) .limit(limit) .offset(offset); let (select, params, types) = builder.build(); let stmt = self.client.prepare_typed(&select, &types).await?; let stream = self .client .query_raw(&stmt, slice_iter(&params[..])) .await .map_err(|err| { log::debug!("Failed to get: {}", err); err })? .and_then(|row| future::ready(Self::from_row(row))) .map_err(ServiceError::Database); Ok(Box::pin(stream)) } async fn create( &self, application: Application, aliases: HashSet<TypedAlias>, ) -> Result<(), ServiceError> { let name = application.name; let data = application.data; let labels = application.labels; let annotations = application.annotations; self.client .execute( r#" INSERT INTO APPLICATIONS ( NAME, UID, LABELS, ANNOTATIONS, CREATION_TIMESTAMP, GENERATION, RESOURCE_VERSION, FINALIZERS, OWNER, DATA ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 )"#, &[ &name, &application.uid, &Json(labels), &Json(annotations), &Utc::now(), &(application.generation as i64), &Uuid::new_v4(), &application.finalizers, &application.owner, &Json(data), ], ) .await?; self.insert_aliases(&name, &aliases).await?; Ok(()) } async fn update_data( &self, application: Application, aliases: Option<HashSet<TypedAlias>>, ) -> Result<u64, ServiceError> { let name = application.name; let labels = application.labels; let data = application.data; let annotations = application.annotations; // update device let count = self .client .execute( r#" UPDATE APPLICATIONS SET LABELS = $2, ANNOTATIONS = $3, GENERATION = $4, RESOURCE_VERSION = $5, DELETION_TIMESTAMP = $6, FINALIZERS = $7, DATA = $8 WHERE NAME = $1 "#, &[ &name, &Json(labels), &Json(annotations), &(application.generation as i64), &Uuid::new_v4(), &application.deletion_timestamp, &application.finalizers, &Json(data), ], ) .await?; update_aliases!(count, aliases, |aliases| { // clear existing aliases let sql = "DELETE FROM APPLICATION_ALIASES WHERE APP=$1"; let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?; self.client.execute(&stmt, &[&name]).await?; // insert new alias set self.insert_aliases(&name, &aliases).await?; Ok(count) }) } async fn update_transfer( &self, app: String, owner: Option<String>, transfer_owner: Option<String>, ) -> Result<u64, ServiceError> { // update application let sql = r#" UPDATE APPLICATIONS SET OWNER = $2, TRANSFER_OWNER = $3 WHERE NAME = $1 "#; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR]) .await?; let count = self .client .execute(&stmt, &[&app, &owner, &transfer_owner]) .await?; Ok(count) } async fn set_members( &self, app: &str, members: IndexMap<String, MemberEntry>, ) -> Result<u64, ServiceError> { // update application let sql = r#" UPDATE APPLICATIONS SET MEMBERS = $2 WHERE NAME = $1 "#; let stmt = self .client .prepare_typed(sql, &[Type::VARCHAR, Type::JSONB]) .await?; let count = self.client.execute(&stmt, &[&app, &Json(members)]).await?; Ok(count) } }
{ return Ok(()); }
conditional_block
main.rs
#![no_std] #![feature( test, start, array_map, const_panic,
isa_attribute, core_intrinsics, maybe_uninit_ref, bindings_after_at, stmt_expr_attributes, default_alloc_error_handler, const_fn_floating_point_arithmetic, )] extern crate alloc; mod gfx; mod heap; mod mem; use core::fmt::Write; use alloc::{vec::Vec, vec}; use vek::*; use num_traits::float::Float; use gba::{ io::{ irq::{set_irq_handler, IrqFlags, IrqEnableSetting, IE, IME, BIOS_IF}, display::{ DisplayControlSetting, DisplayStatusSetting, DisplayMode, DISPCNT, DISPSTAT, VCOUNT, VBLANK_SCANLINE, }, background::{BackgroundControlSetting, BG2HOFS}, timers::{TimerControlSetting, TimerTickRate, TM2CNT_H, TM2CNT_L}, keypad::read_key_input, }, bios, vram::bitmap::{Mode3, Mode5}, Color, }; pub use mem::*; pub type F32 = fixed::types::I16F16; pub const fn num(x: f32) -> F32 { use fixed::traits::Fixed; F32::from_bits((x * (1 << F32::FRAC_NBITS) as f32) as <F32 as Fixed>::Bits) } fn normalize_quat_fast(q: Quaternion<F32>) -> Quaternion<F32> { fn finvsqrt(x: f32) -> f32 { let y = f32::from_bits(0x5f375a86 - (x.to_bits() >> 1)); y * (1.5 - ( x * 0.5 * y * y )) } fn fsqrt(x: f32) -> f32 { f32::from_bits((x.to_bits() + (127 << 23)) >> 1) } let v = q.into_vec4(); (v * F32::from_num(finvsqrt(v.magnitude_squared().to_num::<f32>()))).into() } fn cos_fast(mut x: F32) -> F32 { use core::f32; x *= num(f32::consts::FRAC_1_PI / 2.0); x -= num(0.25) + (x + num(0.25)).floor(); x *= num(16.0) * (x.abs() - num(0.5)); x += num(0.225) * x * (x.abs() - num(1.0)); x } fn sin_fast(x: F32) -> F32 { use core::f32; cos_fast(x - num(f32::consts::PI / 2.0)) } fn tan_fast(x: F32) -> F32 { sin_fast(x) / cos_fast(x) } fn rotation_3d(angle_radians: F32, axis: Vec3<F32>) -> Quaternion<F32> { // let axis = axis.normalized(); let Vec3 { x, y, z } = axis * sin_fast(angle_radians * num(0.5)); let w = cos_fast(angle_radians * num(0.5)); Quaternion { x, y, z, w } } #[repr(transparent)] #[derive(Copy, Clone)] struct NumWrap(F32); impl core::ops::Mul<NumWrap> for NumWrap { type Output = NumWrap; fn mul(self, rhs: Self) -> Self { NumWrap(self.0 * rhs.0) } } impl vek::ops::MulAdd<NumWrap, NumWrap> for NumWrap { type Output = NumWrap; fn mul_add(self, mul: NumWrap, add: NumWrap) -> NumWrap { NumWrap(self.0 * mul.0 + add.0) } } fn apply(m: Mat3<F32>, n: Mat3<F32>) -> Mat3<F32> { (m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0) } fn apply4(m: Mat4<F32>, n: Mat4<F32>) -> Mat4<F32> { (m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0) } #[panic_handler] fn panic(info: &core::panic::PanicInfo) ->! { gba::error!("Panic: {:?}", info); Mode3::clear_to(Color::from_rgb(0xFF, 0, 0)); loop {} } #[start] fn main(_argc: isize, _argv: *const *const u8) -> isize { heap::init(); gba::info!("Starting..."); set_irq_handler(irq_handler); IME.write(IrqEnableSetting::IRQ_YES); DISPSTAT.write(DisplayStatusSetting::new() .with_hblank_irq_enable(true) .with_vblank_irq_enable(true)); TM2CNT_H.write(TimerControlSetting::new() .with_tick_rate(TimerTickRate::CPU1024) .with_enabled(true)); let model = wavefront::Obj::from_lines(include_str!("../data/ship-small.obj").lines()).unwrap(); let mut ship_verts = Vec::new(); let mut ship_tris = Vec::new(); for &p in model.positions() { ship_verts.push(Vec3::<f32>::from(p).map(num)); } model .triangles() .for_each(|vs| { let pos = vs.map(|v| Vec3::<f32>::from(v.position())); let cross = (pos[1] - pos[0]).cross(pos[2] - pos[0]); ship_tris.push(( (cross / micromath::F32Ext::sqrt(cross.magnitude_squared())).map(num), vs.map(|v| v.position_index() as u16), )); }); gba::info!("Model has {} vertices and {} triangles", ship_verts.len(), ship_tris.len()); let mut pos = Vec3::new(0.0, 0.0, 3.0).map(num); let mut ori = normalize_quat_fast(Quaternion::<F32>::identity()); let mut tick = 0; let mut last_time = 0; let mut sum_fps = 0.0; let mut screen = unsafe { gfx::mode5::init() }; let mut scene = unsafe { gfx::scene::init() }; let mut time_mvp = 0; let mut time_clear = 0; let mut time_model = 0; let mut time_vertices = 0; let mut time_faces = 0; let mut time_render = 0; loop { let new_time = TM2CNT_L.read(); if tick % 32 == 0 { if new_time > last_time { gba::info!("FPS: {}", sum_fps / 32.0); gba::info!( "Timings: {{ mvp = {}, clear = {}, model = {}, vertices = {}, faces = {}, render = {} }}", time_mvp, time_clear, time_model, time_vertices, time_faces, time_render, ); } sum_fps = 0.0; } let fps = (16_780_000.0 / (new_time - last_time) as f32) / 1024.0; sum_fps += fps; last_time = new_time; let dt = num(fps).recip(); // Wait for vblank IE.write(IrqFlags::new().with_vblank(true)); // bios::vblank_interrupt_wait(); screen.flip(); let keys = read_key_input(); time_mvp = gba::time_this01! {{ ori = normalize_quat_fast(ori * rotation_3d( if keys.down() { num(4.0) * dt } else { num(0.0) } - if keys.up() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_x(), ) * rotation_3d( if keys.right() { num(4.0) * dt } else { num(0.0) } - if keys.left() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_y(), ) * rotation_3d( if keys.r() { num(4.0) * dt } else { num(0.0) } - if keys.l() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_z(), )); pos += gfx::scene::transform_pos(Mat4::from(ori).transposed(), Vec3::unit_z() * ( if keys.a() { num(0.05) } else { num(0.0) } - if keys.b() { num(0.05) } else { num(0.0) } )).xyz(); }}; let mut fb = screen.back(); time_clear = gba::time_this01! {{ fb.clear(Color::from_rgb(1, 3, 4).0); }}; fn perspective_fov_rh_zo(fov_y_radians: F32, width: F32, height: F32, near: F32, far: F32) -> Mat4<F32> { let rad = fov_y_radians; let h = cos_fast(rad * num(0.5)) / sin_fast(rad * num(0.5)); let w = h * height / width; let m00 = w; let m11 = h; let m22 = -(far + near) / (far - near); let m23 = -(num(2.0) * far * near) / (far - near); let m32 = -num(1.0); let mut m = Mat4::new( m00, num(0.0), num(0.0), num(0.0), num(0.0), m11, num(0.0), num(0.0), num(0.0), num(0.0), m22, m23, num(0.0), num(0.0), m32, num(0.0) ); m } let proj = perspective_fov_rh_zo(num(1.0), num(fb.screen_size().x as f32), num(fb.screen_size().y as f32), num(0.5), num(256.0)); let mut frame = scene.begin_frame(gfx::scene::SceneState { proj, view: Mat4::identity(), light_dir: Vec3::new(0.0, -1.0, 0.0).normalized().map(num), ambiance: num(0.2), light_col: Rgb::new(1.0, 0.0, 0.5).map(num), }); let mut ship_model; time_model = gba::time_this01! {{ ship_model = frame.add_model(apply4(Mat4::translation_3d(pos), Mat4::from(apply(Mat3::from(ori), Mat3::scaling_3d(num(0.2)))))); }}; time_vertices = gba::time_this01! {{ for &v in &ship_verts { frame.add_vert(ship_model, v); } }}; time_faces = gba::time_this01! {{ for &(norm, indices) in &ship_tris { let color = Rgb::new(1.0, 1.0, 1.0).map(num); let verts = [ indices[0], indices[1], indices[2], ]; frame.add_convex(ship_model, (verts, color), norm); } }}; // frame.add_flat_quad( // 0, // ([ // Vec3::new(-0.3, -0.5, 0.0).map(num), // Vec3::new(0.0, 1.0, 0.0).map(num), // Vec3::new(0.8, 0.8, 0.0).map(num), // Vec3::new(1.0, 0.0, 0.0).map(num), // ], Rgb::broadcast(num(1.0))), // -Vec3::unit_z(), // ); time_render = gba::time_this01! {{ frame.render(fb); }}; tick += 1; } } extern "C" fn irq_handler(flags: IrqFlags) { if flags.vblank() { vblank_handler(); } if flags.hblank() { hblank_handler(); } if flags.vcounter() { vcounter_handler(); } if flags.timer0() { timer0_handler(); } if flags.timer1() { timer1_handler(); } } fn vblank_handler() { BIOS_IF.write(BIOS_IF.read().with_vblank(true)); } fn hblank_handler() { BIOS_IF.write(BIOS_IF.read().with_hblank(true)); } fn vcounter_handler() { BIOS_IF.write(BIOS_IF.read().with_vcounter(true)); } fn timer0_handler() { BIOS_IF.write(BIOS_IF.read().with_timer0(true)); } fn timer1_handler() { BIOS_IF.write(BIOS_IF.read().with_timer1(true)); } #[no_mangle] pub unsafe extern fn __truncdfsf2() {} // #[no_mangle] // pub unsafe extern "C" fn memcpy(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 { // mem::copy_fast( // core::slice::from_raw_parts(src, n), // core::slice::from_raw_parts_mut(dst, n), // ); // dst // }
random_line_split
main.rs
#![no_std] #![feature( test, start, array_map, const_panic, isa_attribute, core_intrinsics, maybe_uninit_ref, bindings_after_at, stmt_expr_attributes, default_alloc_error_handler, const_fn_floating_point_arithmetic, )] extern crate alloc; mod gfx; mod heap; mod mem; use core::fmt::Write; use alloc::{vec::Vec, vec}; use vek::*; use num_traits::float::Float; use gba::{ io::{ irq::{set_irq_handler, IrqFlags, IrqEnableSetting, IE, IME, BIOS_IF}, display::{ DisplayControlSetting, DisplayStatusSetting, DisplayMode, DISPCNT, DISPSTAT, VCOUNT, VBLANK_SCANLINE, }, background::{BackgroundControlSetting, BG2HOFS}, timers::{TimerControlSetting, TimerTickRate, TM2CNT_H, TM2CNT_L}, keypad::read_key_input, }, bios, vram::bitmap::{Mode3, Mode5}, Color, }; pub use mem::*; pub type F32 = fixed::types::I16F16; pub const fn num(x: f32) -> F32 { use fixed::traits::Fixed; F32::from_bits((x * (1 << F32::FRAC_NBITS) as f32) as <F32 as Fixed>::Bits) } fn normalize_quat_fast(q: Quaternion<F32>) -> Quaternion<F32> { fn finvsqrt(x: f32) -> f32 { let y = f32::from_bits(0x5f375a86 - (x.to_bits() >> 1)); y * (1.5 - ( x * 0.5 * y * y )) } fn fsqrt(x: f32) -> f32 { f32::from_bits((x.to_bits() + (127 << 23)) >> 1) } let v = q.into_vec4(); (v * F32::from_num(finvsqrt(v.magnitude_squared().to_num::<f32>()))).into() } fn cos_fast(mut x: F32) -> F32 { use core::f32; x *= num(f32::consts::FRAC_1_PI / 2.0); x -= num(0.25) + (x + num(0.25)).floor(); x *= num(16.0) * (x.abs() - num(0.5)); x += num(0.225) * x * (x.abs() - num(1.0)); x } fn sin_fast(x: F32) -> F32 { use core::f32; cos_fast(x - num(f32::consts::PI / 2.0)) } fn tan_fast(x: F32) -> F32 { sin_fast(x) / cos_fast(x) } fn rotation_3d(angle_radians: F32, axis: Vec3<F32>) -> Quaternion<F32> { // let axis = axis.normalized(); let Vec3 { x, y, z } = axis * sin_fast(angle_radians * num(0.5)); let w = cos_fast(angle_radians * num(0.5)); Quaternion { x, y, z, w } } #[repr(transparent)] #[derive(Copy, Clone)] struct NumWrap(F32); impl core::ops::Mul<NumWrap> for NumWrap { type Output = NumWrap; fn mul(self, rhs: Self) -> Self { NumWrap(self.0 * rhs.0) } } impl vek::ops::MulAdd<NumWrap, NumWrap> for NumWrap { type Output = NumWrap; fn mul_add(self, mul: NumWrap, add: NumWrap) -> NumWrap { NumWrap(self.0 * mul.0 + add.0) } } fn apply(m: Mat3<F32>, n: Mat3<F32>) -> Mat3<F32> { (m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0) } fn apply4(m: Mat4<F32>, n: Mat4<F32>) -> Mat4<F32> { (m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0) } #[panic_handler] fn panic(info: &core::panic::PanicInfo) ->! { gba::error!("Panic: {:?}", info); Mode3::clear_to(Color::from_rgb(0xFF, 0, 0)); loop {} } #[start] fn main(_argc: isize, _argv: *const *const u8) -> isize { heap::init(); gba::info!("Starting..."); set_irq_handler(irq_handler); IME.write(IrqEnableSetting::IRQ_YES); DISPSTAT.write(DisplayStatusSetting::new() .with_hblank_irq_enable(true) .with_vblank_irq_enable(true)); TM2CNT_H.write(TimerControlSetting::new() .with_tick_rate(TimerTickRate::CPU1024) .with_enabled(true)); let model = wavefront::Obj::from_lines(include_str!("../data/ship-small.obj").lines()).unwrap(); let mut ship_verts = Vec::new(); let mut ship_tris = Vec::new(); for &p in model.positions() { ship_verts.push(Vec3::<f32>::from(p).map(num)); } model .triangles() .for_each(|vs| { let pos = vs.map(|v| Vec3::<f32>::from(v.position())); let cross = (pos[1] - pos[0]).cross(pos[2] - pos[0]); ship_tris.push(( (cross / micromath::F32Ext::sqrt(cross.magnitude_squared())).map(num), vs.map(|v| v.position_index() as u16), )); }); gba::info!("Model has {} vertices and {} triangles", ship_verts.len(), ship_tris.len()); let mut pos = Vec3::new(0.0, 0.0, 3.0).map(num); let mut ori = normalize_quat_fast(Quaternion::<F32>::identity()); let mut tick = 0; let mut last_time = 0; let mut sum_fps = 0.0; let mut screen = unsafe { gfx::mode5::init() }; let mut scene = unsafe { gfx::scene::init() }; let mut time_mvp = 0; let mut time_clear = 0; let mut time_model = 0; let mut time_vertices = 0; let mut time_faces = 0; let mut time_render = 0; loop { let new_time = TM2CNT_L.read(); if tick % 32 == 0 { if new_time > last_time { gba::info!("FPS: {}", sum_fps / 32.0); gba::info!( "Timings: {{ mvp = {}, clear = {}, model = {}, vertices = {}, faces = {}, render = {} }}", time_mvp, time_clear, time_model, time_vertices, time_faces, time_render, ); } sum_fps = 0.0; } let fps = (16_780_000.0 / (new_time - last_time) as f32) / 1024.0; sum_fps += fps; last_time = new_time; let dt = num(fps).recip(); // Wait for vblank IE.write(IrqFlags::new().with_vblank(true)); // bios::vblank_interrupt_wait(); screen.flip(); let keys = read_key_input(); time_mvp = gba::time_this01! {{ ori = normalize_quat_fast(ori * rotation_3d( if keys.down() { num(4.0) * dt } else { num(0.0) } - if keys.up() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_x(), ) * rotation_3d( if keys.right() { num(4.0) * dt } else { num(0.0) } - if keys.left() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_y(), ) * rotation_3d( if keys.r() { num(4.0) * dt } else { num(0.0) } - if keys.l() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_z(), )); pos += gfx::scene::transform_pos(Mat4::from(ori).transposed(), Vec3::unit_z() * ( if keys.a() { num(0.05) } else { num(0.0) } - if keys.b() { num(0.05) } else { num(0.0) } )).xyz(); }}; let mut fb = screen.back(); time_clear = gba::time_this01! {{ fb.clear(Color::from_rgb(1, 3, 4).0); }}; fn perspective_fov_rh_zo(fov_y_radians: F32, width: F32, height: F32, near: F32, far: F32) -> Mat4<F32> { let rad = fov_y_radians; let h = cos_fast(rad * num(0.5)) / sin_fast(rad * num(0.5)); let w = h * height / width; let m00 = w; let m11 = h; let m22 = -(far + near) / (far - near); let m23 = -(num(2.0) * far * near) / (far - near); let m32 = -num(1.0); let mut m = Mat4::new( m00, num(0.0), num(0.0), num(0.0), num(0.0), m11, num(0.0), num(0.0), num(0.0), num(0.0), m22, m23, num(0.0), num(0.0), m32, num(0.0) ); m } let proj = perspective_fov_rh_zo(num(1.0), num(fb.screen_size().x as f32), num(fb.screen_size().y as f32), num(0.5), num(256.0)); let mut frame = scene.begin_frame(gfx::scene::SceneState { proj, view: Mat4::identity(), light_dir: Vec3::new(0.0, -1.0, 0.0).normalized().map(num), ambiance: num(0.2), light_col: Rgb::new(1.0, 0.0, 0.5).map(num), }); let mut ship_model; time_model = gba::time_this01! {{ ship_model = frame.add_model(apply4(Mat4::translation_3d(pos), Mat4::from(apply(Mat3::from(ori), Mat3::scaling_3d(num(0.2)))))); }}; time_vertices = gba::time_this01! {{ for &v in &ship_verts { frame.add_vert(ship_model, v); } }}; time_faces = gba::time_this01! {{ for &(norm, indices) in &ship_tris { let color = Rgb::new(1.0, 1.0, 1.0).map(num); let verts = [ indices[0], indices[1], indices[2], ]; frame.add_convex(ship_model, (verts, color), norm); } }}; // frame.add_flat_quad( // 0, // ([ // Vec3::new(-0.3, -0.5, 0.0).map(num), // Vec3::new(0.0, 1.0, 0.0).map(num), // Vec3::new(0.8, 0.8, 0.0).map(num), // Vec3::new(1.0, 0.0, 0.0).map(num), // ], Rgb::broadcast(num(1.0))), // -Vec3::unit_z(), // ); time_render = gba::time_this01! {{ frame.render(fb); }}; tick += 1; } } extern "C" fn irq_handler(flags: IrqFlags) { if flags.vblank() { vblank_handler(); } if flags.hblank() { hblank_handler(); } if flags.vcounter() { vcounter_handler(); } if flags.timer0()
if flags.timer1() { timer1_handler(); } } fn vblank_handler() { BIOS_IF.write(BIOS_IF.read().with_vblank(true)); } fn hblank_handler() { BIOS_IF.write(BIOS_IF.read().with_hblank(true)); } fn vcounter_handler() { BIOS_IF.write(BIOS_IF.read().with_vcounter(true)); } fn timer0_handler() { BIOS_IF.write(BIOS_IF.read().with_timer0(true)); } fn timer1_handler() { BIOS_IF.write(BIOS_IF.read().with_timer1(true)); } #[no_mangle] pub unsafe extern fn __truncdfsf2() {} // #[no_mangle] // pub unsafe extern "C" fn memcpy(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 { // mem::copy_fast( // core::slice::from_raw_parts(src, n), // core::slice::from_raw_parts_mut(dst, n), // ); // dst // }
{ timer0_handler(); }
conditional_block
main.rs
#![no_std] #![feature( test, start, array_map, const_panic, isa_attribute, core_intrinsics, maybe_uninit_ref, bindings_after_at, stmt_expr_attributes, default_alloc_error_handler, const_fn_floating_point_arithmetic, )] extern crate alloc; mod gfx; mod heap; mod mem; use core::fmt::Write; use alloc::{vec::Vec, vec}; use vek::*; use num_traits::float::Float; use gba::{ io::{ irq::{set_irq_handler, IrqFlags, IrqEnableSetting, IE, IME, BIOS_IF}, display::{ DisplayControlSetting, DisplayStatusSetting, DisplayMode, DISPCNT, DISPSTAT, VCOUNT, VBLANK_SCANLINE, }, background::{BackgroundControlSetting, BG2HOFS}, timers::{TimerControlSetting, TimerTickRate, TM2CNT_H, TM2CNT_L}, keypad::read_key_input, }, bios, vram::bitmap::{Mode3, Mode5}, Color, }; pub use mem::*; pub type F32 = fixed::types::I16F16; pub const fn num(x: f32) -> F32 { use fixed::traits::Fixed; F32::from_bits((x * (1 << F32::FRAC_NBITS) as f32) as <F32 as Fixed>::Bits) } fn normalize_quat_fast(q: Quaternion<F32>) -> Quaternion<F32> { fn finvsqrt(x: f32) -> f32 { let y = f32::from_bits(0x5f375a86 - (x.to_bits() >> 1)); y * (1.5 - ( x * 0.5 * y * y )) } fn fsqrt(x: f32) -> f32 { f32::from_bits((x.to_bits() + (127 << 23)) >> 1) } let v = q.into_vec4(); (v * F32::from_num(finvsqrt(v.magnitude_squared().to_num::<f32>()))).into() } fn cos_fast(mut x: F32) -> F32 { use core::f32; x *= num(f32::consts::FRAC_1_PI / 2.0); x -= num(0.25) + (x + num(0.25)).floor(); x *= num(16.0) * (x.abs() - num(0.5)); x += num(0.225) * x * (x.abs() - num(1.0)); x } fn sin_fast(x: F32) -> F32 { use core::f32; cos_fast(x - num(f32::consts::PI / 2.0)) } fn tan_fast(x: F32) -> F32 { sin_fast(x) / cos_fast(x) } fn rotation_3d(angle_radians: F32, axis: Vec3<F32>) -> Quaternion<F32> { // let axis = axis.normalized(); let Vec3 { x, y, z } = axis * sin_fast(angle_radians * num(0.5)); let w = cos_fast(angle_radians * num(0.5)); Quaternion { x, y, z, w } } #[repr(transparent)] #[derive(Copy, Clone)] struct NumWrap(F32); impl core::ops::Mul<NumWrap> for NumWrap { type Output = NumWrap; fn mul(self, rhs: Self) -> Self { NumWrap(self.0 * rhs.0) } } impl vek::ops::MulAdd<NumWrap, NumWrap> for NumWrap { type Output = NumWrap; fn mul_add(self, mul: NumWrap, add: NumWrap) -> NumWrap { NumWrap(self.0 * mul.0 + add.0) } } fn apply(m: Mat3<F32>, n: Mat3<F32>) -> Mat3<F32> { (m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0) } fn
(m: Mat4<F32>, n: Mat4<F32>) -> Mat4<F32> { (m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0) } #[panic_handler] fn panic(info: &core::panic::PanicInfo) ->! { gba::error!("Panic: {:?}", info); Mode3::clear_to(Color::from_rgb(0xFF, 0, 0)); loop {} } #[start] fn main(_argc: isize, _argv: *const *const u8) -> isize { heap::init(); gba::info!("Starting..."); set_irq_handler(irq_handler); IME.write(IrqEnableSetting::IRQ_YES); DISPSTAT.write(DisplayStatusSetting::new() .with_hblank_irq_enable(true) .with_vblank_irq_enable(true)); TM2CNT_H.write(TimerControlSetting::new() .with_tick_rate(TimerTickRate::CPU1024) .with_enabled(true)); let model = wavefront::Obj::from_lines(include_str!("../data/ship-small.obj").lines()).unwrap(); let mut ship_verts = Vec::new(); let mut ship_tris = Vec::new(); for &p in model.positions() { ship_verts.push(Vec3::<f32>::from(p).map(num)); } model .triangles() .for_each(|vs| { let pos = vs.map(|v| Vec3::<f32>::from(v.position())); let cross = (pos[1] - pos[0]).cross(pos[2] - pos[0]); ship_tris.push(( (cross / micromath::F32Ext::sqrt(cross.magnitude_squared())).map(num), vs.map(|v| v.position_index() as u16), )); }); gba::info!("Model has {} vertices and {} triangles", ship_verts.len(), ship_tris.len()); let mut pos = Vec3::new(0.0, 0.0, 3.0).map(num); let mut ori = normalize_quat_fast(Quaternion::<F32>::identity()); let mut tick = 0; let mut last_time = 0; let mut sum_fps = 0.0; let mut screen = unsafe { gfx::mode5::init() }; let mut scene = unsafe { gfx::scene::init() }; let mut time_mvp = 0; let mut time_clear = 0; let mut time_model = 0; let mut time_vertices = 0; let mut time_faces = 0; let mut time_render = 0; loop { let new_time = TM2CNT_L.read(); if tick % 32 == 0 { if new_time > last_time { gba::info!("FPS: {}", sum_fps / 32.0); gba::info!( "Timings: {{ mvp = {}, clear = {}, model = {}, vertices = {}, faces = {}, render = {} }}", time_mvp, time_clear, time_model, time_vertices, time_faces, time_render, ); } sum_fps = 0.0; } let fps = (16_780_000.0 / (new_time - last_time) as f32) / 1024.0; sum_fps += fps; last_time = new_time; let dt = num(fps).recip(); // Wait for vblank IE.write(IrqFlags::new().with_vblank(true)); // bios::vblank_interrupt_wait(); screen.flip(); let keys = read_key_input(); time_mvp = gba::time_this01! {{ ori = normalize_quat_fast(ori * rotation_3d( if keys.down() { num(4.0) * dt } else { num(0.0) } - if keys.up() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_x(), ) * rotation_3d( if keys.right() { num(4.0) * dt } else { num(0.0) } - if keys.left() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_y(), ) * rotation_3d( if keys.r() { num(4.0) * dt } else { num(0.0) } - if keys.l() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_z(), )); pos += gfx::scene::transform_pos(Mat4::from(ori).transposed(), Vec3::unit_z() * ( if keys.a() { num(0.05) } else { num(0.0) } - if keys.b() { num(0.05) } else { num(0.0) } )).xyz(); }}; let mut fb = screen.back(); time_clear = gba::time_this01! {{ fb.clear(Color::from_rgb(1, 3, 4).0); }}; fn perspective_fov_rh_zo(fov_y_radians: F32, width: F32, height: F32, near: F32, far: F32) -> Mat4<F32> { let rad = fov_y_radians; let h = cos_fast(rad * num(0.5)) / sin_fast(rad * num(0.5)); let w = h * height / width; let m00 = w; let m11 = h; let m22 = -(far + near) / (far - near); let m23 = -(num(2.0) * far * near) / (far - near); let m32 = -num(1.0); let mut m = Mat4::new( m00, num(0.0), num(0.0), num(0.0), num(0.0), m11, num(0.0), num(0.0), num(0.0), num(0.0), m22, m23, num(0.0), num(0.0), m32, num(0.0) ); m } let proj = perspective_fov_rh_zo(num(1.0), num(fb.screen_size().x as f32), num(fb.screen_size().y as f32), num(0.5), num(256.0)); let mut frame = scene.begin_frame(gfx::scene::SceneState { proj, view: Mat4::identity(), light_dir: Vec3::new(0.0, -1.0, 0.0).normalized().map(num), ambiance: num(0.2), light_col: Rgb::new(1.0, 0.0, 0.5).map(num), }); let mut ship_model; time_model = gba::time_this01! {{ ship_model = frame.add_model(apply4(Mat4::translation_3d(pos), Mat4::from(apply(Mat3::from(ori), Mat3::scaling_3d(num(0.2)))))); }}; time_vertices = gba::time_this01! {{ for &v in &ship_verts { frame.add_vert(ship_model, v); } }}; time_faces = gba::time_this01! {{ for &(norm, indices) in &ship_tris { let color = Rgb::new(1.0, 1.0, 1.0).map(num); let verts = [ indices[0], indices[1], indices[2], ]; frame.add_convex(ship_model, (verts, color), norm); } }}; // frame.add_flat_quad( // 0, // ([ // Vec3::new(-0.3, -0.5, 0.0).map(num), // Vec3::new(0.0, 1.0, 0.0).map(num), // Vec3::new(0.8, 0.8, 0.0).map(num), // Vec3::new(1.0, 0.0, 0.0).map(num), // ], Rgb::broadcast(num(1.0))), // -Vec3::unit_z(), // ); time_render = gba::time_this01! {{ frame.render(fb); }}; tick += 1; } } extern "C" fn irq_handler(flags: IrqFlags) { if flags.vblank() { vblank_handler(); } if flags.hblank() { hblank_handler(); } if flags.vcounter() { vcounter_handler(); } if flags.timer0() { timer0_handler(); } if flags.timer1() { timer1_handler(); } } fn vblank_handler() { BIOS_IF.write(BIOS_IF.read().with_vblank(true)); } fn hblank_handler() { BIOS_IF.write(BIOS_IF.read().with_hblank(true)); } fn vcounter_handler() { BIOS_IF.write(BIOS_IF.read().with_vcounter(true)); } fn timer0_handler() { BIOS_IF.write(BIOS_IF.read().with_timer0(true)); } fn timer1_handler() { BIOS_IF.write(BIOS_IF.read().with_timer1(true)); } #[no_mangle] pub unsafe extern fn __truncdfsf2() {} // #[no_mangle] // pub unsafe extern "C" fn memcpy(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 { // mem::copy_fast( // core::slice::from_raw_parts(src, n), // core::slice::from_raw_parts_mut(dst, n), // ); // dst // }
apply4
identifier_name
main.rs
#![no_std] #![feature( test, start, array_map, const_panic, isa_attribute, core_intrinsics, maybe_uninit_ref, bindings_after_at, stmt_expr_attributes, default_alloc_error_handler, const_fn_floating_point_arithmetic, )] extern crate alloc; mod gfx; mod heap; mod mem; use core::fmt::Write; use alloc::{vec::Vec, vec}; use vek::*; use num_traits::float::Float; use gba::{ io::{ irq::{set_irq_handler, IrqFlags, IrqEnableSetting, IE, IME, BIOS_IF}, display::{ DisplayControlSetting, DisplayStatusSetting, DisplayMode, DISPCNT, DISPSTAT, VCOUNT, VBLANK_SCANLINE, }, background::{BackgroundControlSetting, BG2HOFS}, timers::{TimerControlSetting, TimerTickRate, TM2CNT_H, TM2CNT_L}, keypad::read_key_input, }, bios, vram::bitmap::{Mode3, Mode5}, Color, }; pub use mem::*; pub type F32 = fixed::types::I16F16; pub const fn num(x: f32) -> F32 { use fixed::traits::Fixed; F32::from_bits((x * (1 << F32::FRAC_NBITS) as f32) as <F32 as Fixed>::Bits) } fn normalize_quat_fast(q: Quaternion<F32>) -> Quaternion<F32> { fn finvsqrt(x: f32) -> f32 { let y = f32::from_bits(0x5f375a86 - (x.to_bits() >> 1)); y * (1.5 - ( x * 0.5 * y * y )) } fn fsqrt(x: f32) -> f32 { f32::from_bits((x.to_bits() + (127 << 23)) >> 1) } let v = q.into_vec4(); (v * F32::from_num(finvsqrt(v.magnitude_squared().to_num::<f32>()))).into() } fn cos_fast(mut x: F32) -> F32 { use core::f32; x *= num(f32::consts::FRAC_1_PI / 2.0); x -= num(0.25) + (x + num(0.25)).floor(); x *= num(16.0) * (x.abs() - num(0.5)); x += num(0.225) * x * (x.abs() - num(1.0)); x } fn sin_fast(x: F32) -> F32 { use core::f32; cos_fast(x - num(f32::consts::PI / 2.0)) } fn tan_fast(x: F32) -> F32 { sin_fast(x) / cos_fast(x) } fn rotation_3d(angle_radians: F32, axis: Vec3<F32>) -> Quaternion<F32> { // let axis = axis.normalized(); let Vec3 { x, y, z } = axis * sin_fast(angle_radians * num(0.5)); let w = cos_fast(angle_radians * num(0.5)); Quaternion { x, y, z, w } } #[repr(transparent)] #[derive(Copy, Clone)] struct NumWrap(F32); impl core::ops::Mul<NumWrap> for NumWrap { type Output = NumWrap; fn mul(self, rhs: Self) -> Self
} impl vek::ops::MulAdd<NumWrap, NumWrap> for NumWrap { type Output = NumWrap; fn mul_add(self, mul: NumWrap, add: NumWrap) -> NumWrap { NumWrap(self.0 * mul.0 + add.0) } } fn apply(m: Mat3<F32>, n: Mat3<F32>) -> Mat3<F32> { (m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0) } fn apply4(m: Mat4<F32>, n: Mat4<F32>) -> Mat4<F32> { (m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0) } #[panic_handler] fn panic(info: &core::panic::PanicInfo) ->! { gba::error!("Panic: {:?}", info); Mode3::clear_to(Color::from_rgb(0xFF, 0, 0)); loop {} } #[start] fn main(_argc: isize, _argv: *const *const u8) -> isize { heap::init(); gba::info!("Starting..."); set_irq_handler(irq_handler); IME.write(IrqEnableSetting::IRQ_YES); DISPSTAT.write(DisplayStatusSetting::new() .with_hblank_irq_enable(true) .with_vblank_irq_enable(true)); TM2CNT_H.write(TimerControlSetting::new() .with_tick_rate(TimerTickRate::CPU1024) .with_enabled(true)); let model = wavefront::Obj::from_lines(include_str!("../data/ship-small.obj").lines()).unwrap(); let mut ship_verts = Vec::new(); let mut ship_tris = Vec::new(); for &p in model.positions() { ship_verts.push(Vec3::<f32>::from(p).map(num)); } model .triangles() .for_each(|vs| { let pos = vs.map(|v| Vec3::<f32>::from(v.position())); let cross = (pos[1] - pos[0]).cross(pos[2] - pos[0]); ship_tris.push(( (cross / micromath::F32Ext::sqrt(cross.magnitude_squared())).map(num), vs.map(|v| v.position_index() as u16), )); }); gba::info!("Model has {} vertices and {} triangles", ship_verts.len(), ship_tris.len()); let mut pos = Vec3::new(0.0, 0.0, 3.0).map(num); let mut ori = normalize_quat_fast(Quaternion::<F32>::identity()); let mut tick = 0; let mut last_time = 0; let mut sum_fps = 0.0; let mut screen = unsafe { gfx::mode5::init() }; let mut scene = unsafe { gfx::scene::init() }; let mut time_mvp = 0; let mut time_clear = 0; let mut time_model = 0; let mut time_vertices = 0; let mut time_faces = 0; let mut time_render = 0; loop { let new_time = TM2CNT_L.read(); if tick % 32 == 0 { if new_time > last_time { gba::info!("FPS: {}", sum_fps / 32.0); gba::info!( "Timings: {{ mvp = {}, clear = {}, model = {}, vertices = {}, faces = {}, render = {} }}", time_mvp, time_clear, time_model, time_vertices, time_faces, time_render, ); } sum_fps = 0.0; } let fps = (16_780_000.0 / (new_time - last_time) as f32) / 1024.0; sum_fps += fps; last_time = new_time; let dt = num(fps).recip(); // Wait for vblank IE.write(IrqFlags::new().with_vblank(true)); // bios::vblank_interrupt_wait(); screen.flip(); let keys = read_key_input(); time_mvp = gba::time_this01! {{ ori = normalize_quat_fast(ori * rotation_3d( if keys.down() { num(4.0) * dt } else { num(0.0) } - if keys.up() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_x(), ) * rotation_3d( if keys.right() { num(4.0) * dt } else { num(0.0) } - if keys.left() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_y(), ) * rotation_3d( if keys.r() { num(4.0) * dt } else { num(0.0) } - if keys.l() { num(4.0) * dt } else { num(0.0) }, Vec3::unit_z(), )); pos += gfx::scene::transform_pos(Mat4::from(ori).transposed(), Vec3::unit_z() * ( if keys.a() { num(0.05) } else { num(0.0) } - if keys.b() { num(0.05) } else { num(0.0) } )).xyz(); }}; let mut fb = screen.back(); time_clear = gba::time_this01! {{ fb.clear(Color::from_rgb(1, 3, 4).0); }}; fn perspective_fov_rh_zo(fov_y_radians: F32, width: F32, height: F32, near: F32, far: F32) -> Mat4<F32> { let rad = fov_y_radians; let h = cos_fast(rad * num(0.5)) / sin_fast(rad * num(0.5)); let w = h * height / width; let m00 = w; let m11 = h; let m22 = -(far + near) / (far - near); let m23 = -(num(2.0) * far * near) / (far - near); let m32 = -num(1.0); let mut m = Mat4::new( m00, num(0.0), num(0.0), num(0.0), num(0.0), m11, num(0.0), num(0.0), num(0.0), num(0.0), m22, m23, num(0.0), num(0.0), m32, num(0.0) ); m } let proj = perspective_fov_rh_zo(num(1.0), num(fb.screen_size().x as f32), num(fb.screen_size().y as f32), num(0.5), num(256.0)); let mut frame = scene.begin_frame(gfx::scene::SceneState { proj, view: Mat4::identity(), light_dir: Vec3::new(0.0, -1.0, 0.0).normalized().map(num), ambiance: num(0.2), light_col: Rgb::new(1.0, 0.0, 0.5).map(num), }); let mut ship_model; time_model = gba::time_this01! {{ ship_model = frame.add_model(apply4(Mat4::translation_3d(pos), Mat4::from(apply(Mat3::from(ori), Mat3::scaling_3d(num(0.2)))))); }}; time_vertices = gba::time_this01! {{ for &v in &ship_verts { frame.add_vert(ship_model, v); } }}; time_faces = gba::time_this01! {{ for &(norm, indices) in &ship_tris { let color = Rgb::new(1.0, 1.0, 1.0).map(num); let verts = [ indices[0], indices[1], indices[2], ]; frame.add_convex(ship_model, (verts, color), norm); } }}; // frame.add_flat_quad( // 0, // ([ // Vec3::new(-0.3, -0.5, 0.0).map(num), // Vec3::new(0.0, 1.0, 0.0).map(num), // Vec3::new(0.8, 0.8, 0.0).map(num), // Vec3::new(1.0, 0.0, 0.0).map(num), // ], Rgb::broadcast(num(1.0))), // -Vec3::unit_z(), // ); time_render = gba::time_this01! {{ frame.render(fb); }}; tick += 1; } } extern "C" fn irq_handler(flags: IrqFlags) { if flags.vblank() { vblank_handler(); } if flags.hblank() { hblank_handler(); } if flags.vcounter() { vcounter_handler(); } if flags.timer0() { timer0_handler(); } if flags.timer1() { timer1_handler(); } } fn vblank_handler() { BIOS_IF.write(BIOS_IF.read().with_vblank(true)); } fn hblank_handler() { BIOS_IF.write(BIOS_IF.read().with_hblank(true)); } fn vcounter_handler() { BIOS_IF.write(BIOS_IF.read().with_vcounter(true)); } fn timer0_handler() { BIOS_IF.write(BIOS_IF.read().with_timer0(true)); } fn timer1_handler() { BIOS_IF.write(BIOS_IF.read().with_timer1(true)); } #[no_mangle] pub unsafe extern fn __truncdfsf2() {} // #[no_mangle] // pub unsafe extern "C" fn memcpy(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 { // mem::copy_fast( // core::slice::from_raw_parts(src, n), // core::slice::from_raw_parts_mut(dst, n), // ); // dst // }
{ NumWrap(self.0 * rhs.0) }
identifier_body
main.rs
use cargo::core::dependency::Kind; use cargo::core::manifest::ManifestMetadata; use cargo::core::package::PackageSet; use cargo::core::registry::PackageRegistry; use cargo::core::resolver::Method; use cargo::core::shell::Shell; use cargo::core::{Package, PackageId, Resolve, Workspace}; use cargo::ops; use cargo::util::{self, important_paths, CargoResult, Cfg, Rustc}; use cargo::{CliResult, Config}; use failure::bail; use petgraph::graph::NodeIndex; use petgraph::visit::EdgeRef; use petgraph::EdgeDirection; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::str::{self, FromStr}; use structopt::clap::AppSettings; use structopt::StructOpt; use crate::format::Pattern; mod format; #[derive(StructOpt)] #[structopt(bin_name = "cargo")] enum Opts { #[structopt( name = "tree", raw( setting = "AppSettings::UnifiedHelpMessage", setting = "AppSettings::DeriveDisplayOrder", setting = "AppSettings::DontCollapseArgsInUsage" ) )] /// Display a tree visualization of a dependency graph Tree(Args), } #[derive(StructOpt)] struct Args { #[structopt(long = "package", short = "p", value_name = "SPEC")] /// Package to be used as the root of the tree package: Option<String>, #[structopt(long = "features", value_name = "FEATURES")] /// Space-separated list of features to activate features: Option<String>, #[structopt(long = "all-features")] /// Activate all available features all_features: bool, #[structopt(long = "no-default-features")] /// Do not activate the `default` feature no_default_features: bool, #[structopt(long = "target", value_name = "TARGET")] /// Set the target triple target: Option<String>, /// Directory for all generated artifacts #[structopt(long = "target-dir", value_name = "DIRECTORY", parse(from_os_str))] target_dir: Option<PathBuf>, #[structopt(long = "all-targets")] /// Return dependencies for all targets. By default only the host target is matched. all_targets: bool, #[structopt(long = "no-dev-dependencies")] /// Skip dev dependencies. no_dev_dependencies: bool, #[structopt(long = "manifest-path", value_name = "PATH", parse(from_os_str))] /// Path to Cargo.toml manifest_path: Option<PathBuf>, #[structopt(long = "invert", short = "i")] /// Invert the tree direction invert: bool, #[structopt(long = "no-indent")] /// Display the dependencies as a list (rather than a tree) no_indent: bool, #[structopt(long = "prefix-depth")] /// Display the dependencies as a list (rather than a tree), but prefixed with the depth prefix_depth: bool, #[structopt(long = "all", short = "a")] /// Don't truncate dependencies that have already been displayed all: bool, #[structopt(long = "duplicate", short = "d")] /// Show only dependencies which come in multiple versions (implies -i) duplicates: bool, #[structopt(long = "charset", value_name = "CHARSET", default_value = "utf8")] /// Character set to use in output: utf8, ascii charset: Charset, #[structopt( long = "format", short = "f", value_name = "FORMAT", default_value = "{p}" )] /// Format string used for printing dependencies format: String, #[structopt(long = "verbose", short = "v", parse(from_occurrences))] /// Use verbose output (-vv very verbose/build.rs output) verbose: u32, #[structopt(long = "quiet", short = "q")] /// No output printed to stdout other than the tree quiet: Option<bool>, #[structopt(long = "color", value_name = "WHEN")] /// Coloring: auto, always, never color: Option<String>, #[structopt(long = "frozen")] /// Require Cargo.lock and cache are up to date frozen: bool, #[structopt(long = "locked")] /// Require Cargo.lock is up to date locked: bool, #[structopt(short = "Z", value_name = "FLAG")] /// Unstable (nightly-only) flags to Cargo unstable_flags: Vec<String>, } enum Charset { Utf8, Ascii, } #[derive(Clone, Copy)] enum Prefix { None, Indent, Depth, } impl FromStr for Charset { type Err = &'static str; fn from_str(s: &str) -> Result<Charset, &'static str> { match s { "utf8" => Ok(Charset::Utf8), "ascii" => Ok(Charset::Ascii), _ => Err("invalid charset"), } } } struct Symbols { down: &'static str, tee: &'static str, ell: &'static str, right: &'static str, } static UTF8_SYMBOLS: Symbols = Symbols { down: "│", tee: "├", ell: "└", right: "─", }; static ASCII_SYMBOLS: Symbols = Symbols { down: "|", tee: "|", ell: "`", right: "-", }; fn main() { env_logger::init(); let mut config = match Config::default() { Ok(cfg) => cfg, Err(e) => { let mut shell = Shell::new(); cargo::exit_with_error(e.into(), &mut shell) } }; let Opts::Tree(args) = Opts::from_args(); if let Err(e) = real_main(args, &mut config) { let mut shell = Shell::new(); cargo::exit_with_error(e.into(), &mut shell) } } fn real_main(args: Args, config: &mut Config) -> CliResult { config.configure( args.verbose, args.quiet, &args.color, args.frozen, args.locked, &args.target_dir, &args.unstable_flags, )?; let workspace = workspace(config, args.manifest_path)?; let package = workspace.current()?; let mut registry = registry(config, &package)?; let (packages, resolve) = resolve( &mut registry, &workspace, args.features, args.all_features, args.no_default_features, args.no_dev_dependencies, )?; let ids = packages.package_ids().collect::<Vec<_>>(); let packages = registry.get(&ids)?; let root = match args.package { Some(ref pkg) => resolve.query(pkg)?, None => package.package_id(), }; let rustc = config.rustc(Some(&workspace))?; let target = if args.all_targets { None } else { Some(args.target.as_ref().unwrap_or(&rustc.host).as_str()) }; let format = Pattern::new(&args.format).map_err(|e| failure::err_msg(e.to_string()))?; let cfgs = get_cfgs(&rustc, &args.target)?; let graph = build_graph( &resolve, &packages, package.package_id(), target, cfgs.as_ref().map(|r| &**r), )?; let direction = if args.invert || args.duplicates { EdgeDirection::Incoming } else { EdgeDirection::Outgoing }; let symbols = match args.charset { Charset::Ascii => &ASCII_SYMBOLS, Charset::Utf8 => &UTF8_SYMBOLS, }; let prefix = if args.prefix_depth { Prefix::Depth } else if args.no_indent { Prefix::None } else { Prefix::Indent }; if args.duplicates { let dups = find_duplicates(&graph); for dup in &dups { print_tree(dup, &graph, &format, direction, symbols, prefix, args.all)?; println!(); } } else { print_tree(&root, &graph, &format, direction, symbols, prefix, args.all)?; } Ok(()) } fn find_duplicates<'a>(graph: &Graph<'a>) -> Vec<PackageId> { let mut counts = HashMap::new(); // Count by name only. Source and version are irrelevant here. for package in graph.nodes.keys() { *counts.entry(package.name()).or_insert(0) += 1; } // Theoretically inefficient, but in practice we're only listing duplicates and // there won't be enough dependencies for it to matter. let mut dup_ids = Vec::new(); for name in counts.drain().filter(|&(_, v)| v > 1).map(|(k, _)| k) { dup_ids.extend(graph.nodes.keys().filter(|p| p.name() == name)); } dup_ids.sort(); dup_ids } fn get_cfgs(rustc: &Rustc, target: &Option<String>) -> CargoResult<Option<Vec<Cfg>>> { let mut process = util::process(&rustc.path); process.arg("--print=cfg").env_remove("RUST_LOG"); if let Some(ref s) = *target { process.arg("--target").arg(s); } let output = match process.exec_with_output() { Ok(output) => output, Err(e) => return Err(e), }; let output = str::from_utf8(&output.stdout).unwrap(); let lines = output.lines(); Ok(Some( lines.map(Cfg::from_str).collect::<CargoResult<Vec<_>>>()?, )) } fn workspace(config: &Config, manifest_path: Option<PathBuf>) -> CargoResult<Workspace<'_>> { let root = match manifest_path { Some(path) => path, None => important_paths::find_root_manifest_for_wd(config.cwd())?, }; Workspace::new(&root, config) } fn registry<'a>(config: &'a Config, package: &Package) -> CargoResult<PackageRegistry<'a>> { let mut registry = PackageRegistry::new(config)?; registry.add_sources(Some(package.package_id().source_id().clone()))?; Ok(registry) } fn resolve<'a, 'cfg>( registry: &mut PackageRegistry<'cfg>, workspace: &'a Workspace<'cfg>, features: Option<String>, all_features: bool, no_default_features: bool, no_dev_dependencies: bool, ) -> CargoResult<(PackageSet<'a>, Resolve)> { let features = Method::split_features(&features.into_iter().collect::<Vec<_>>()); let (packages, resolve) = ops::resolve_ws(workspace)?; let method = Method::Required { dev_deps:!no_dev_dependencies, features: &features, all_features, uses_default_features:!no_default_features, }; let resolve = ops::resolve_with_previous( registry, workspace, method, Some(&resolve), None, &[], true, true, )?; Ok((packages, resolve)) } struct Node<'a> { id: PackageId, metadata: &'a ManifestMetadata, } struct Graph<'a
graph: petgraph::Graph<Node<'a>, Kind>, nodes: HashMap<PackageId, NodeIndex>, } fn build_graph<'a>( resolve: &'a Resolve, packages: &'a PackageSet<'_>, root: PackageId, target: Option<&str>, cfgs: Option<&[Cfg]>, ) -> CargoResult<Graph<'a>> { let mut graph = Graph { graph: petgraph::Graph::new(), nodes: HashMap::new(), }; let node = Node { id: root.clone(), metadata: packages.get_one(root)?.manifest().metadata(), }; graph.nodes.insert(root.clone(), graph.graph.add_node(node)); let mut pending = vec![root]; while let Some(pkg_id) = pending.pop() { let idx = graph.nodes[&pkg_id]; let pkg = packages.get_one(pkg_id)?; for raw_dep_id in resolve.deps_not_replaced(pkg_id) { let it = pkg .dependencies() .iter() .filter(|d| d.matches_ignoring_source(raw_dep_id)) .filter(|d| { d.platform() .and_then(|p| target.map(|t| p.matches(t, cfgs))) .unwrap_or(true) }); let dep_id = match resolve.replacement(raw_dep_id) { Some(id) => id, None => raw_dep_id, }; for dep in it { let dep_idx = match graph.nodes.entry(dep_id) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { pending.push(dep_id); let node = Node { id: dep_id, metadata: packages.get_one(dep_id)?.manifest().metadata(), }; *e.insert(graph.graph.add_node(node)) } }; graph.graph.add_edge(idx, dep_idx, dep.kind()); } } } Ok(graph) } fn print_tree<'a>( package: &'a PackageId, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, prefix: Prefix, all: bool, ) -> CargoResult<()> { let mut visited_deps = HashSet::new(); let mut levels_continue = vec![]; let package = match graph.nodes.get(package) { Some(package) => package, None => bail!("package {} not found", package), }; let node = &graph.graph[*package]; print_dependency( node, &graph, format, direction, symbols, &mut visited_deps, &mut levels_continue, prefix, all, ); Ok(()) } fn print_dependency<'a>( package: &Node<'a>, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, visited_deps: &mut HashSet<PackageId>, levels_continue: &mut Vec<bool>, prefix: Prefix, all: bool, ) { let new = all || visited_deps.insert(package.id); let star = if new { "" } else { " (*)" }; match prefix { Prefix::Depth => print!("{} ", levels_continue.len()), Prefix::Indent => { if let Some((&last_continues, rest)) = levels_continue.split_last() { for &continues in rest { let c = if continues { symbols.down } else { " " }; print!("{} ", c); } let c = if last_continues { symbols.tee } else { symbols.ell }; print!("{0}{1}{1} ", c, symbols.right); } } Prefix::None => (), } println!("{}{}", format.display(&package.id, package.metadata), star); if!new { return; } let mut normal = vec![]; let mut build = vec![]; let mut development = vec![]; for edge in graph .graph .edges_directed(graph.nodes[&package.id], direction) { let dep = match direction { EdgeDirection::Incoming => &graph.graph[edge.source()], EdgeDirection::Outgoing => &graph.graph[edge.target()], }; match *edge.weight() { Kind::Normal => normal.push(dep), Kind::Build => build.push(dep), Kind::Development => development.push(dep), } } print_dependency_kind( Kind::Normal, normal, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); print_dependency_kind( Kind::Build, build, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); print_dependency_kind( Kind::Development, development, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); } fn print_dependency_kind<'a>( kind: Kind, mut deps: Vec<&Node<'a>>, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, visited_deps: &mut HashSet<PackageId>, levels_continue: &mut Vec<bool>, prefix: Prefix, all: bool, ) { if deps.is_empty() { return; } // Resolve uses Hash data types internally but we want consistent output ordering deps.sort_by_key(|n| n.id); let name = match kind { Kind::Normal => None, Kind::Build => Some("[build-dependencies]"), Kind::Development => Some("[dev-dependencies]"), }; if let Prefix::Indent = prefix { if let Some(name) = name { for &continues in &**levels_continue { let c = if continues { symbols.down } else { " " }; print!("{} ", c); } println!("{}", name); } } let mut it = deps.iter().peekable(); while let Some(dependency) = it.next() { levels_continue.push(it.peek().is_some()); print_dependency( dependency, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); levels_continue.pop(); } }
> {
identifier_name
main.rs
use cargo::core::dependency::Kind; use cargo::core::manifest::ManifestMetadata; use cargo::core::package::PackageSet; use cargo::core::registry::PackageRegistry; use cargo::core::resolver::Method; use cargo::core::shell::Shell; use cargo::core::{Package, PackageId, Resolve, Workspace}; use cargo::ops; use cargo::util::{self, important_paths, CargoResult, Cfg, Rustc}; use cargo::{CliResult, Config}; use failure::bail; use petgraph::graph::NodeIndex; use petgraph::visit::EdgeRef; use petgraph::EdgeDirection; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::str::{self, FromStr}; use structopt::clap::AppSettings; use structopt::StructOpt; use crate::format::Pattern; mod format; #[derive(StructOpt)] #[structopt(bin_name = "cargo")] enum Opts { #[structopt( name = "tree", raw( setting = "AppSettings::UnifiedHelpMessage", setting = "AppSettings::DeriveDisplayOrder", setting = "AppSettings::DontCollapseArgsInUsage" ) )] /// Display a tree visualization of a dependency graph Tree(Args), } #[derive(StructOpt)] struct Args { #[structopt(long = "package", short = "p", value_name = "SPEC")] /// Package to be used as the root of the tree package: Option<String>, #[structopt(long = "features", value_name = "FEATURES")] /// Space-separated list of features to activate features: Option<String>, #[structopt(long = "all-features")] /// Activate all available features all_features: bool, #[structopt(long = "no-default-features")] /// Do not activate the `default` feature no_default_features: bool, #[structopt(long = "target", value_name = "TARGET")] /// Set the target triple target: Option<String>, /// Directory for all generated artifacts #[structopt(long = "target-dir", value_name = "DIRECTORY", parse(from_os_str))] target_dir: Option<PathBuf>, #[structopt(long = "all-targets")] /// Return dependencies for all targets. By default only the host target is matched. all_targets: bool, #[structopt(long = "no-dev-dependencies")] /// Skip dev dependencies. no_dev_dependencies: bool, #[structopt(long = "manifest-path", value_name = "PATH", parse(from_os_str))] /// Path to Cargo.toml manifest_path: Option<PathBuf>, #[structopt(long = "invert", short = "i")] /// Invert the tree direction invert: bool, #[structopt(long = "no-indent")] /// Display the dependencies as a list (rather than a tree) no_indent: bool, #[structopt(long = "prefix-depth")] /// Display the dependencies as a list (rather than a tree), but prefixed with the depth prefix_depth: bool, #[structopt(long = "all", short = "a")] /// Don't truncate dependencies that have already been displayed all: bool, #[structopt(long = "duplicate", short = "d")] /// Show only dependencies which come in multiple versions (implies -i) duplicates: bool, #[structopt(long = "charset", value_name = "CHARSET", default_value = "utf8")] /// Character set to use in output: utf8, ascii charset: Charset, #[structopt( long = "format", short = "f", value_name = "FORMAT", default_value = "{p}" )] /// Format string used for printing dependencies format: String, #[structopt(long = "verbose", short = "v", parse(from_occurrences))] /// Use verbose output (-vv very verbose/build.rs output) verbose: u32, #[structopt(long = "quiet", short = "q")] /// No output printed to stdout other than the tree quiet: Option<bool>, #[structopt(long = "color", value_name = "WHEN")] /// Coloring: auto, always, never color: Option<String>, #[structopt(long = "frozen")] /// Require Cargo.lock and cache are up to date frozen: bool, #[structopt(long = "locked")] /// Require Cargo.lock is up to date locked: bool, #[structopt(short = "Z", value_name = "FLAG")] /// Unstable (nightly-only) flags to Cargo unstable_flags: Vec<String>, } enum Charset { Utf8, Ascii, } #[derive(Clone, Copy)] enum Prefix { None, Indent, Depth, } impl FromStr for Charset { type Err = &'static str; fn from_str(s: &str) -> Result<Charset, &'static str> { match s { "utf8" => Ok(Charset::Utf8), "ascii" => Ok(Charset::Ascii), _ => Err("invalid charset"), } } } struct Symbols { down: &'static str, tee: &'static str, ell: &'static str, right: &'static str, } static UTF8_SYMBOLS: Symbols = Symbols { down: "│", tee: "├", ell: "└", right: "─", }; static ASCII_SYMBOLS: Symbols = Symbols { down: "|", tee: "|", ell: "`", right: "-", }; fn main() { en
l_main(args: Args, config: &mut Config) -> CliResult { config.configure( args.verbose, args.quiet, &args.color, args.frozen, args.locked, &args.target_dir, &args.unstable_flags, )?; let workspace = workspace(config, args.manifest_path)?; let package = workspace.current()?; let mut registry = registry(config, &package)?; let (packages, resolve) = resolve( &mut registry, &workspace, args.features, args.all_features, args.no_default_features, args.no_dev_dependencies, )?; let ids = packages.package_ids().collect::<Vec<_>>(); let packages = registry.get(&ids)?; let root = match args.package { Some(ref pkg) => resolve.query(pkg)?, None => package.package_id(), }; let rustc = config.rustc(Some(&workspace))?; let target = if args.all_targets { None } else { Some(args.target.as_ref().unwrap_or(&rustc.host).as_str()) }; let format = Pattern::new(&args.format).map_err(|e| failure::err_msg(e.to_string()))?; let cfgs = get_cfgs(&rustc, &args.target)?; let graph = build_graph( &resolve, &packages, package.package_id(), target, cfgs.as_ref().map(|r| &**r), )?; let direction = if args.invert || args.duplicates { EdgeDirection::Incoming } else { EdgeDirection::Outgoing }; let symbols = match args.charset { Charset::Ascii => &ASCII_SYMBOLS, Charset::Utf8 => &UTF8_SYMBOLS, }; let prefix = if args.prefix_depth { Prefix::Depth } else if args.no_indent { Prefix::None } else { Prefix::Indent }; if args.duplicates { let dups = find_duplicates(&graph); for dup in &dups { print_tree(dup, &graph, &format, direction, symbols, prefix, args.all)?; println!(); } } else { print_tree(&root, &graph, &format, direction, symbols, prefix, args.all)?; } Ok(()) } fn find_duplicates<'a>(graph: &Graph<'a>) -> Vec<PackageId> { let mut counts = HashMap::new(); // Count by name only. Source and version are irrelevant here. for package in graph.nodes.keys() { *counts.entry(package.name()).or_insert(0) += 1; } // Theoretically inefficient, but in practice we're only listing duplicates and // there won't be enough dependencies for it to matter. let mut dup_ids = Vec::new(); for name in counts.drain().filter(|&(_, v)| v > 1).map(|(k, _)| k) { dup_ids.extend(graph.nodes.keys().filter(|p| p.name() == name)); } dup_ids.sort(); dup_ids } fn get_cfgs(rustc: &Rustc, target: &Option<String>) -> CargoResult<Option<Vec<Cfg>>> { let mut process = util::process(&rustc.path); process.arg("--print=cfg").env_remove("RUST_LOG"); if let Some(ref s) = *target { process.arg("--target").arg(s); } let output = match process.exec_with_output() { Ok(output) => output, Err(e) => return Err(e), }; let output = str::from_utf8(&output.stdout).unwrap(); let lines = output.lines(); Ok(Some( lines.map(Cfg::from_str).collect::<CargoResult<Vec<_>>>()?, )) } fn workspace(config: &Config, manifest_path: Option<PathBuf>) -> CargoResult<Workspace<'_>> { let root = match manifest_path { Some(path) => path, None => important_paths::find_root_manifest_for_wd(config.cwd())?, }; Workspace::new(&root, config) } fn registry<'a>(config: &'a Config, package: &Package) -> CargoResult<PackageRegistry<'a>> { let mut registry = PackageRegistry::new(config)?; registry.add_sources(Some(package.package_id().source_id().clone()))?; Ok(registry) } fn resolve<'a, 'cfg>( registry: &mut PackageRegistry<'cfg>, workspace: &'a Workspace<'cfg>, features: Option<String>, all_features: bool, no_default_features: bool, no_dev_dependencies: bool, ) -> CargoResult<(PackageSet<'a>, Resolve)> { let features = Method::split_features(&features.into_iter().collect::<Vec<_>>()); let (packages, resolve) = ops::resolve_ws(workspace)?; let method = Method::Required { dev_deps:!no_dev_dependencies, features: &features, all_features, uses_default_features:!no_default_features, }; let resolve = ops::resolve_with_previous( registry, workspace, method, Some(&resolve), None, &[], true, true, )?; Ok((packages, resolve)) } struct Node<'a> { id: PackageId, metadata: &'a ManifestMetadata, } struct Graph<'a> { graph: petgraph::Graph<Node<'a>, Kind>, nodes: HashMap<PackageId, NodeIndex>, } fn build_graph<'a>( resolve: &'a Resolve, packages: &'a PackageSet<'_>, root: PackageId, target: Option<&str>, cfgs: Option<&[Cfg]>, ) -> CargoResult<Graph<'a>> { let mut graph = Graph { graph: petgraph::Graph::new(), nodes: HashMap::new(), }; let node = Node { id: root.clone(), metadata: packages.get_one(root)?.manifest().metadata(), }; graph.nodes.insert(root.clone(), graph.graph.add_node(node)); let mut pending = vec![root]; while let Some(pkg_id) = pending.pop() { let idx = graph.nodes[&pkg_id]; let pkg = packages.get_one(pkg_id)?; for raw_dep_id in resolve.deps_not_replaced(pkg_id) { let it = pkg .dependencies() .iter() .filter(|d| d.matches_ignoring_source(raw_dep_id)) .filter(|d| { d.platform() .and_then(|p| target.map(|t| p.matches(t, cfgs))) .unwrap_or(true) }); let dep_id = match resolve.replacement(raw_dep_id) { Some(id) => id, None => raw_dep_id, }; for dep in it { let dep_idx = match graph.nodes.entry(dep_id) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { pending.push(dep_id); let node = Node { id: dep_id, metadata: packages.get_one(dep_id)?.manifest().metadata(), }; *e.insert(graph.graph.add_node(node)) } }; graph.graph.add_edge(idx, dep_idx, dep.kind()); } } } Ok(graph) } fn print_tree<'a>( package: &'a PackageId, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, prefix: Prefix, all: bool, ) -> CargoResult<()> { let mut visited_deps = HashSet::new(); let mut levels_continue = vec![]; let package = match graph.nodes.get(package) { Some(package) => package, None => bail!("package {} not found", package), }; let node = &graph.graph[*package]; print_dependency( node, &graph, format, direction, symbols, &mut visited_deps, &mut levels_continue, prefix, all, ); Ok(()) } fn print_dependency<'a>( package: &Node<'a>, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, visited_deps: &mut HashSet<PackageId>, levels_continue: &mut Vec<bool>, prefix: Prefix, all: bool, ) { let new = all || visited_deps.insert(package.id); let star = if new { "" } else { " (*)" }; match prefix { Prefix::Depth => print!("{} ", levels_continue.len()), Prefix::Indent => { if let Some((&last_continues, rest)) = levels_continue.split_last() { for &continues in rest { let c = if continues { symbols.down } else { " " }; print!("{} ", c); } let c = if last_continues { symbols.tee } else { symbols.ell }; print!("{0}{1}{1} ", c, symbols.right); } } Prefix::None => (), } println!("{}{}", format.display(&package.id, package.metadata), star); if!new { return; } let mut normal = vec![]; let mut build = vec![]; let mut development = vec![]; for edge in graph .graph .edges_directed(graph.nodes[&package.id], direction) { let dep = match direction { EdgeDirection::Incoming => &graph.graph[edge.source()], EdgeDirection::Outgoing => &graph.graph[edge.target()], }; match *edge.weight() { Kind::Normal => normal.push(dep), Kind::Build => build.push(dep), Kind::Development => development.push(dep), } } print_dependency_kind( Kind::Normal, normal, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); print_dependency_kind( Kind::Build, build, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); print_dependency_kind( Kind::Development, development, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); } fn print_dependency_kind<'a>( kind: Kind, mut deps: Vec<&Node<'a>>, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, visited_deps: &mut HashSet<PackageId>, levels_continue: &mut Vec<bool>, prefix: Prefix, all: bool, ) { if deps.is_empty() { return; } // Resolve uses Hash data types internally but we want consistent output ordering deps.sort_by_key(|n| n.id); let name = match kind { Kind::Normal => None, Kind::Build => Some("[build-dependencies]"), Kind::Development => Some("[dev-dependencies]"), }; if let Prefix::Indent = prefix { if let Some(name) = name { for &continues in &**levels_continue { let c = if continues { symbols.down } else { " " }; print!("{} ", c); } println!("{}", name); } } let mut it = deps.iter().peekable(); while let Some(dependency) = it.next() { levels_continue.push(it.peek().is_some()); print_dependency( dependency, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); levels_continue.pop(); } }
v_logger::init(); let mut config = match Config::default() { Ok(cfg) => cfg, Err(e) => { let mut shell = Shell::new(); cargo::exit_with_error(e.into(), &mut shell) } }; let Opts::Tree(args) = Opts::from_args(); if let Err(e) = real_main(args, &mut config) { let mut shell = Shell::new(); cargo::exit_with_error(e.into(), &mut shell) } } fn rea
identifier_body
main.rs
use cargo::core::dependency::Kind; use cargo::core::manifest::ManifestMetadata; use cargo::core::package::PackageSet; use cargo::core::registry::PackageRegistry; use cargo::core::resolver::Method; use cargo::core::shell::Shell; use cargo::core::{Package, PackageId, Resolve, Workspace}; use cargo::ops; use cargo::util::{self, important_paths, CargoResult, Cfg, Rustc}; use cargo::{CliResult, Config}; use failure::bail; use petgraph::graph::NodeIndex; use petgraph::visit::EdgeRef; use petgraph::EdgeDirection; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::str::{self, FromStr}; use structopt::clap::AppSettings; use structopt::StructOpt; use crate::format::Pattern; mod format; #[derive(StructOpt)] #[structopt(bin_name = "cargo")] enum Opts { #[structopt( name = "tree", raw( setting = "AppSettings::UnifiedHelpMessage", setting = "AppSettings::DeriveDisplayOrder", setting = "AppSettings::DontCollapseArgsInUsage" ) )] /// Display a tree visualization of a dependency graph Tree(Args), } #[derive(StructOpt)] struct Args { #[structopt(long = "package", short = "p", value_name = "SPEC")] /// Package to be used as the root of the tree package: Option<String>, #[structopt(long = "features", value_name = "FEATURES")] /// Space-separated list of features to activate features: Option<String>, #[structopt(long = "all-features")] /// Activate all available features all_features: bool, #[structopt(long = "no-default-features")] /// Do not activate the `default` feature no_default_features: bool, #[structopt(long = "target", value_name = "TARGET")] /// Set the target triple target: Option<String>, /// Directory for all generated artifacts #[structopt(long = "target-dir", value_name = "DIRECTORY", parse(from_os_str))] target_dir: Option<PathBuf>, #[structopt(long = "all-targets")] /// Return dependencies for all targets. By default only the host target is matched. all_targets: bool, #[structopt(long = "no-dev-dependencies")] /// Skip dev dependencies. no_dev_dependencies: bool, #[structopt(long = "manifest-path", value_name = "PATH", parse(from_os_str))] /// Path to Cargo.toml manifest_path: Option<PathBuf>, #[structopt(long = "invert", short = "i")] /// Invert the tree direction invert: bool, #[structopt(long = "no-indent")] /// Display the dependencies as a list (rather than a tree) no_indent: bool, #[structopt(long = "prefix-depth")] /// Display the dependencies as a list (rather than a tree), but prefixed with the depth prefix_depth: bool, #[structopt(long = "all", short = "a")] /// Don't truncate dependencies that have already been displayed all: bool, #[structopt(long = "duplicate", short = "d")] /// Show only dependencies which come in multiple versions (implies -i) duplicates: bool, #[structopt(long = "charset", value_name = "CHARSET", default_value = "utf8")] /// Character set to use in output: utf8, ascii charset: Charset, #[structopt( long = "format", short = "f", value_name = "FORMAT", default_value = "{p}" )] /// Format string used for printing dependencies format: String, #[structopt(long = "verbose", short = "v", parse(from_occurrences))] /// Use verbose output (-vv very verbose/build.rs output) verbose: u32, #[structopt(long = "quiet", short = "q")] /// No output printed to stdout other than the tree quiet: Option<bool>, #[structopt(long = "color", value_name = "WHEN")] /// Coloring: auto, always, never color: Option<String>, #[structopt(long = "frozen")] /// Require Cargo.lock and cache are up to date frozen: bool, #[structopt(long = "locked")] /// Require Cargo.lock is up to date locked: bool, #[structopt(short = "Z", value_name = "FLAG")] /// Unstable (nightly-only) flags to Cargo unstable_flags: Vec<String>, } enum Charset { Utf8, Ascii, } #[derive(Clone, Copy)] enum Prefix { None, Indent, Depth, } impl FromStr for Charset { type Err = &'static str; fn from_str(s: &str) -> Result<Charset, &'static str> { match s { "utf8" => Ok(Charset::Utf8), "ascii" => Ok(Charset::Ascii), _ => Err("invalid charset"), } } } struct Symbols { down: &'static str, tee: &'static str, ell: &'static str, right: &'static str, } static UTF8_SYMBOLS: Symbols = Symbols { down: "│", tee: "├", ell: "└", right: "─", }; static ASCII_SYMBOLS: Symbols = Symbols { down: "|", tee: "|", ell: "`", right: "-", }; fn main() { env_logger::init(); let mut config = match Config::default() { Ok(cfg) => cfg, Err(e) => { let mut shell = Shell::new(); cargo::exit_with_error(e.into(), &mut shell) } }; let Opts::Tree(args) = Opts::from_args(); if let Err(e) = real_main(args, &mut config) { let mut shell = Shell::new(); cargo::exit_with_error(e.into(), &mut shell) } } fn real_main(args: Args, config: &mut Config) -> CliResult { config.configure( args.verbose, args.quiet, &args.color, args.frozen, args.locked, &args.target_dir, &args.unstable_flags, )?; let workspace = workspace(config, args.manifest_path)?; let package = workspace.current()?; let mut registry = registry(config, &package)?; let (packages, resolve) = resolve( &mut registry, &workspace, args.features, args.all_features, args.no_default_features, args.no_dev_dependencies, )?; let ids = packages.package_ids().collect::<Vec<_>>(); let packages = registry.get(&ids)?; let root = match args.package { Some(ref pkg) => resolve.query(pkg)?, None => package.package_id(), }; let rustc = config.rustc(Some(&workspace))?; let target = if args.all_targets { None } else { Some(args.target.as_ref().unwrap_or(&rustc.host).as_str()) }; let format = Pattern::new(&args.format).map_err(|e| failure::err_msg(e.to_string()))?; let cfgs = get_cfgs(&rustc, &args.target)?; let graph = build_graph( &resolve, &packages, package.package_id(), target, cfgs.as_ref().map(|r| &**r), )?; let direction = if args.invert || args.duplicates { EdgeDirection::Incoming } else { EdgeDirection::Outgoing }; let symbols = match args.charset { Charset::Ascii => &ASCII_SYMBOLS, Charset::Utf8 => &UTF8_SYMBOLS, }; let prefix = if args.prefix_depth { Prefix::Depth } else if args.no_indent { Prefix::None } else { Prefix::Indent }; if args.duplicates { let dups = find_duplicates(&graph); for dup in &dups { print_tree(dup, &graph, &format, direction, symbols, prefix, args.all)?; println!(); } } else { print_tree(&root, &graph, &format, direction, symbols, prefix, args.all)?; } Ok(()) } fn find_duplicates<'a>(graph: &Graph<'a>) -> Vec<PackageId> { let mut counts = HashMap::new(); // Count by name only. Source and version are irrelevant here. for package in graph.nodes.keys() { *counts.entry(package.name()).or_insert(0) += 1; } // Theoretically inefficient, but in practice we're only listing duplicates and // there won't be enough dependencies for it to matter. let mut dup_ids = Vec::new(); for name in counts.drain().filter(|&(_, v)| v > 1).map(|(k, _)| k) { dup_ids.extend(graph.nodes.keys().filter(|p| p.name() == name)); } dup_ids.sort(); dup_ids } fn get_cfgs(rustc: &Rustc, target: &Option<String>) -> CargoResult<Option<Vec<Cfg>>> { let mut process = util::process(&rustc.path); process.arg("--print=cfg").env_remove("RUST_LOG"); if let Some(ref s) = *target { process.arg("--target").arg(s); } let output = match process.exec_with_output() { Ok(output) => output, Err(e) => return Err(e), }; let output = str::from_utf8(&output.stdout).unwrap(); let lines = output.lines(); Ok(Some( lines.map(Cfg::from_str).collect::<CargoResult<Vec<_>>>()?, )) } fn workspace(config: &Config, manifest_path: Option<PathBuf>) -> CargoResult<Workspace<'_>> { let root = match manifest_path { Some(path) => path, None => important_paths::find_root_manifest_for_wd(config.cwd())?, }; Workspace::new(&root, config) } fn registry<'a>(config: &'a Config, package: &Package) -> CargoResult<PackageRegistry<'a>> { let mut registry = PackageRegistry::new(config)?; registry.add_sources(Some(package.package_id().source_id().clone()))?; Ok(registry) } fn resolve<'a, 'cfg>( registry: &mut PackageRegistry<'cfg>, workspace: &'a Workspace<'cfg>, features: Option<String>, all_features: bool, no_default_features: bool, no_dev_dependencies: bool, ) -> CargoResult<(PackageSet<'a>, Resolve)> { let features = Method::split_features(&features.into_iter().collect::<Vec<_>>()); let (packages, resolve) = ops::resolve_ws(workspace)?; let method = Method::Required { dev_deps:!no_dev_dependencies, features: &features, all_features, uses_default_features:!no_default_features, }; let resolve = ops::resolve_with_previous( registry, workspace, method, Some(&resolve), None, &[], true, true, )?; Ok((packages, resolve)) } struct Node<'a> { id: PackageId, metadata: &'a ManifestMetadata, } struct Graph<'a> { graph: petgraph::Graph<Node<'a>, Kind>, nodes: HashMap<PackageId, NodeIndex>, } fn build_graph<'a>( resolve: &'a Resolve, packages: &'a PackageSet<'_>, root: PackageId, target: Option<&str>, cfgs: Option<&[Cfg]>, ) -> CargoResult<Graph<'a>> { let mut graph = Graph { graph: petgraph::Graph::new(), nodes: HashMap::new(), }; let node = Node { id: root.clone(), metadata: packages.get_one(root)?.manifest().metadata(), }; graph.nodes.insert(root.clone(), graph.graph.add_node(node)); let mut pending = vec![root]; while let Some(pkg_id) = pending.pop() { let idx = graph.nodes[&pkg_id]; let pkg = packages.get_one(pkg_id)?; for raw_dep_id in resolve.deps_not_replaced(pkg_id) { let it = pkg .dependencies() .iter() .filter(|d| d.matches_ignoring_source(raw_dep_id)) .filter(|d| { d.platform() .and_then(|p| target.map(|t| p.matches(t, cfgs))) .unwrap_or(true) }); let dep_id = match resolve.replacement(raw_dep_id) { Some(id) => id, None => raw_dep_id, };
for dep in it { let dep_idx = match graph.nodes.entry(dep_id) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { pending.push(dep_id); let node = Node { id: dep_id, metadata: packages.get_one(dep_id)?.manifest().metadata(), }; *e.insert(graph.graph.add_node(node)) } }; graph.graph.add_edge(idx, dep_idx, dep.kind()); } } } Ok(graph) } fn print_tree<'a>( package: &'a PackageId, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, prefix: Prefix, all: bool, ) -> CargoResult<()> { let mut visited_deps = HashSet::new(); let mut levels_continue = vec![]; let package = match graph.nodes.get(package) { Some(package) => package, None => bail!("package {} not found", package), }; let node = &graph.graph[*package]; print_dependency( node, &graph, format, direction, symbols, &mut visited_deps, &mut levels_continue, prefix, all, ); Ok(()) } fn print_dependency<'a>( package: &Node<'a>, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, visited_deps: &mut HashSet<PackageId>, levels_continue: &mut Vec<bool>, prefix: Prefix, all: bool, ) { let new = all || visited_deps.insert(package.id); let star = if new { "" } else { " (*)" }; match prefix { Prefix::Depth => print!("{} ", levels_continue.len()), Prefix::Indent => { if let Some((&last_continues, rest)) = levels_continue.split_last() { for &continues in rest { let c = if continues { symbols.down } else { " " }; print!("{} ", c); } let c = if last_continues { symbols.tee } else { symbols.ell }; print!("{0}{1}{1} ", c, symbols.right); } } Prefix::None => (), } println!("{}{}", format.display(&package.id, package.metadata), star); if!new { return; } let mut normal = vec![]; let mut build = vec![]; let mut development = vec![]; for edge in graph .graph .edges_directed(graph.nodes[&package.id], direction) { let dep = match direction { EdgeDirection::Incoming => &graph.graph[edge.source()], EdgeDirection::Outgoing => &graph.graph[edge.target()], }; match *edge.weight() { Kind::Normal => normal.push(dep), Kind::Build => build.push(dep), Kind::Development => development.push(dep), } } print_dependency_kind( Kind::Normal, normal, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); print_dependency_kind( Kind::Build, build, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); print_dependency_kind( Kind::Development, development, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); } fn print_dependency_kind<'a>( kind: Kind, mut deps: Vec<&Node<'a>>, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, visited_deps: &mut HashSet<PackageId>, levels_continue: &mut Vec<bool>, prefix: Prefix, all: bool, ) { if deps.is_empty() { return; } // Resolve uses Hash data types internally but we want consistent output ordering deps.sort_by_key(|n| n.id); let name = match kind { Kind::Normal => None, Kind::Build => Some("[build-dependencies]"), Kind::Development => Some("[dev-dependencies]"), }; if let Prefix::Indent = prefix { if let Some(name) = name { for &continues in &**levels_continue { let c = if continues { symbols.down } else { " " }; print!("{} ", c); } println!("{}", name); } } let mut it = deps.iter().peekable(); while let Some(dependency) = it.next() { levels_continue.push(it.peek().is_some()); print_dependency( dependency, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); levels_continue.pop(); } }
random_line_split
main.rs
use cargo::core::dependency::Kind; use cargo::core::manifest::ManifestMetadata; use cargo::core::package::PackageSet; use cargo::core::registry::PackageRegistry; use cargo::core::resolver::Method; use cargo::core::shell::Shell; use cargo::core::{Package, PackageId, Resolve, Workspace}; use cargo::ops; use cargo::util::{self, important_paths, CargoResult, Cfg, Rustc}; use cargo::{CliResult, Config}; use failure::bail; use petgraph::graph::NodeIndex; use petgraph::visit::EdgeRef; use petgraph::EdgeDirection; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::str::{self, FromStr}; use structopt::clap::AppSettings; use structopt::StructOpt; use crate::format::Pattern; mod format; #[derive(StructOpt)] #[structopt(bin_name = "cargo")] enum Opts { #[structopt( name = "tree", raw( setting = "AppSettings::UnifiedHelpMessage", setting = "AppSettings::DeriveDisplayOrder", setting = "AppSettings::DontCollapseArgsInUsage" ) )] /// Display a tree visualization of a dependency graph Tree(Args), } #[derive(StructOpt)] struct Args { #[structopt(long = "package", short = "p", value_name = "SPEC")] /// Package to be used as the root of the tree package: Option<String>, #[structopt(long = "features", value_name = "FEATURES")] /// Space-separated list of features to activate features: Option<String>, #[structopt(long = "all-features")] /// Activate all available features all_features: bool, #[structopt(long = "no-default-features")] /// Do not activate the `default` feature no_default_features: bool, #[structopt(long = "target", value_name = "TARGET")] /// Set the target triple target: Option<String>, /// Directory for all generated artifacts #[structopt(long = "target-dir", value_name = "DIRECTORY", parse(from_os_str))] target_dir: Option<PathBuf>, #[structopt(long = "all-targets")] /// Return dependencies for all targets. By default only the host target is matched. all_targets: bool, #[structopt(long = "no-dev-dependencies")] /// Skip dev dependencies. no_dev_dependencies: bool, #[structopt(long = "manifest-path", value_name = "PATH", parse(from_os_str))] /// Path to Cargo.toml manifest_path: Option<PathBuf>, #[structopt(long = "invert", short = "i")] /// Invert the tree direction invert: bool, #[structopt(long = "no-indent")] /// Display the dependencies as a list (rather than a tree) no_indent: bool, #[structopt(long = "prefix-depth")] /// Display the dependencies as a list (rather than a tree), but prefixed with the depth prefix_depth: bool, #[structopt(long = "all", short = "a")] /// Don't truncate dependencies that have already been displayed all: bool, #[structopt(long = "duplicate", short = "d")] /// Show only dependencies which come in multiple versions (implies -i) duplicates: bool, #[structopt(long = "charset", value_name = "CHARSET", default_value = "utf8")] /// Character set to use in output: utf8, ascii charset: Charset, #[structopt( long = "format", short = "f", value_name = "FORMAT", default_value = "{p}" )] /// Format string used for printing dependencies format: String, #[structopt(long = "verbose", short = "v", parse(from_occurrences))] /// Use verbose output (-vv very verbose/build.rs output) verbose: u32, #[structopt(long = "quiet", short = "q")] /// No output printed to stdout other than the tree quiet: Option<bool>, #[structopt(long = "color", value_name = "WHEN")] /// Coloring: auto, always, never color: Option<String>, #[structopt(long = "frozen")] /// Require Cargo.lock and cache are up to date frozen: bool, #[structopt(long = "locked")] /// Require Cargo.lock is up to date locked: bool, #[structopt(short = "Z", value_name = "FLAG")] /// Unstable (nightly-only) flags to Cargo unstable_flags: Vec<String>, } enum Charset { Utf8, Ascii, } #[derive(Clone, Copy)] enum Prefix { None, Indent, Depth, } impl FromStr for Charset { type Err = &'static str; fn from_str(s: &str) -> Result<Charset, &'static str> { match s { "utf8" => Ok(Charset::Utf8), "ascii" => Ok(Charset::Ascii), _ => Err("invalid charset"), } } } struct Symbols { down: &'static str, tee: &'static str, ell: &'static str, right: &'static str, } static UTF8_SYMBOLS: Symbols = Symbols { down: "│", tee: "├", ell: "└", right: "─", }; static ASCII_SYMBOLS: Symbols = Symbols { down: "|", tee: "|", ell: "`", right: "-", }; fn main() { env_logger::init(); let mut config = match Config::default() { Ok(cfg) => cfg, Err(e) => { let mut shell = Shell::new(); cargo::exit_with_error(e.into(), &mut shell) } }; let Opts::Tree(args) = Opts::from_args(); if let Err(e) = real_main(args, &mut config) { let mut shell = Shell::new(); cargo::exit_with_error(e.into(), &mut shell) } } fn real_main(args: Args, config: &mut Config) -> CliResult { config.configure( args.verbose, args.quiet, &args.color, args.frozen, args.locked, &args.target_dir, &args.unstable_flags, )?; let workspace = workspace(config, args.manifest_path)?; let package = workspace.current()?; let mut registry = registry(config, &package)?; let (packages, resolve) = resolve( &mut registry, &workspace, args.features, args.all_features, args.no_default_features, args.no_dev_dependencies, )?; let ids = packages.package_ids().collect::<Vec<_>>(); let packages = registry.get(&ids)?; let root = match args.package { Some(ref pkg) => resolve.query(pkg)?, None => package.package_id(), }; let rustc = config.rustc(Some(&workspace))?; let target = if args.all_targets { None } else { Some(args.target.as_ref().unwrap_or(&rustc.host).as_str()) }; let format = Pattern::new(&args.format).map_err(|e| failure::err_msg(e.to_string()))?; let cfgs = get_cfgs(&rustc, &args.target)?; let graph = build_graph( &resolve, &packages, package.package_id(), target, cfgs.as_ref().map(|r| &**r), )?; let direction = if args.invert || args.duplicates { EdgeDirection::Incoming } else { EdgeDirection::Outgoing }; let symbols = match args.charset { Charset::Ascii => &ASCII_SYMBOLS, Charset::Utf8 => &UTF8_SYMBOLS, }; let prefix = if args.prefix_depth { Prefix::Depth } else if args.no_indent { Prefix::None } else { Prefix::Indent }; if args.duplicates { let dups = find_duplicates(&graph); for dup in &dups { print_tree(dup, &graph, &format, direction, symbols, prefix, args.all)?; println!(); } } else { print_tree(&root, &graph, &format, direction, symbols, prefix, args.all)?; } Ok(()) } fn find_duplicates<'a>(graph: &Graph<'a>) -> Vec<PackageId> { let mut counts = HashMap::new(); // Count by name only. Source and version are irrelevant here. for package in graph.nodes.keys() { *counts.entry(package.name()).or_insert(0) += 1; } // Theoretically inefficient, but in practice we're only listing duplicates and // there won't be enough dependencies for it to matter. let mut dup_ids = Vec::new(); for name in counts.drain().filter(|&(_, v)| v > 1).map(|(k, _)| k) { dup_ids.extend(graph.nodes.keys().filter(|p| p.name() == name)); } dup_ids.sort(); dup_ids } fn get_cfgs(rustc: &Rustc, target: &Option<String>) -> CargoResult<Option<Vec<Cfg>>> { let mut process = util::process(&rustc.path); process.arg("--print=cfg").env_remove("RUST_LOG"); if let Some(ref s) = *target { process.arg("--target").arg(s); } let output = match process.exec_with_output() { Ok(output) => output, Err(e) => return Err(e), }; let output = str::from_utf8(&output.stdout).unwrap(); let lines = output.lines(); Ok(Some( lines.map(Cfg::from_str).collect::<CargoResult<Vec<_>>>()?, )) } fn workspace(config: &Config, manifest_path: Option<PathBuf>) -> CargoResult<Workspace<'_>> { let root = match manifest_path { Some(path) => path, None => important_paths::find_root_manifest_for_wd(config.cwd())?, }; Workspace::new(&root, config) } fn registry<'a>(config: &'a Config, package: &Package) -> CargoResult<PackageRegistry<'a>> { let mut registry = PackageRegistry::new(config)?; registry.add_sources(Some(package.package_id().source_id().clone()))?; Ok(registry) } fn resolve<'a, 'cfg>( registry: &mut PackageRegistry<'cfg>, workspace: &'a Workspace<'cfg>, features: Option<String>, all_features: bool, no_default_features: bool, no_dev_dependencies: bool, ) -> CargoResult<(PackageSet<'a>, Resolve)> { let features = Method::split_features(&features.into_iter().collect::<Vec<_>>()); let (packages, resolve) = ops::resolve_ws(workspace)?; let method = Method::Required { dev_deps:!no_dev_dependencies, features: &features, all_features, uses_default_features:!no_default_features, }; let resolve = ops::resolve_with_previous( registry, workspace, method, Some(&resolve), None, &[], true, true, )?; Ok((packages, resolve)) } struct Node<'a> { id: PackageId, metadata: &'a ManifestMetadata, } struct Graph<'a> { graph: petgraph::Graph<Node<'a>, Kind>, nodes: HashMap<PackageId, NodeIndex>, } fn build_graph<'a>( resolve: &'a Resolve, packages: &'a PackageSet<'_>, root: PackageId, target: Option<&str>, cfgs: Option<&[Cfg]>, ) -> CargoResult<Graph<'a>> { let mut graph = Graph { graph: petgraph::Graph::new(), nodes: HashMap::new(), }; let node = Node { id: root.clone(), metadata: packages.get_one(root)?.manifest().metadata(), }; graph.nodes.insert(root.clone(), graph.graph.add_node(node)); let mut pending = vec![root]; while let Some(pkg_id) = pending.pop() { let idx = graph.nodes[&pkg_id]; let pkg = packages.get_one(pkg_id)?; for raw_dep_id in resolve.deps_not_replaced(pkg_id) { let it = pkg .dependencies() .iter() .filter(|d| d.matches_ignoring_source(raw_dep_id)) .filter(|d| { d.platform() .and_then(|p| target.map(|t| p.matches(t, cfgs))) .unwrap_or(true) }); let dep_id = match resolve.replacement(raw_dep_id) { Some(id) => id, None => raw_dep_id, }; for dep in it { let dep_idx = match graph.nodes.entry(dep_id) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { pending.push(dep_id); let node = Node { id: dep_id, metadata: packages.get_one(dep_id)?.manifest().metadata(), }; *e.insert(graph.graph.add_node(node)) } }; graph.graph.add_edge(idx, dep_idx, dep.kind()); } } } Ok(graph) } fn print_tree<'a>( package: &'a PackageId, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, prefix: Prefix, all: bool, ) -> CargoResult<()> { let mut visited_deps = HashSet::new(); let mut levels_continue = vec![]; let package = match graph.nodes.get(package) { Some(package) => package, None => bail!("package {} not found", package), }; let node = &graph.graph[*package]; print_dependency( node, &graph, format, direction, symbols, &mut visited_deps, &mut levels_continue, prefix, all, ); Ok(()) } fn print_dependency<'a>( package: &Node<'a>, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, visited_deps: &mut HashSet<PackageId>, levels_continue: &mut Vec<bool>, prefix: Prefix, all: bool, ) { let new = all || visited_deps.insert(package.id); let star = if new { "" } else { " (*)" }; match prefix { Prefix::Depth => print!("{} ", levels_continue.len()), Prefix::Indent => { if let Some((&last_continues, rest)) = levels_continue.split_last() { for &continues in rest { let c = if continues { symbols.down } else { " " }; print!("{} ", c); } let c = if last_continues { symbols.tee } else { symbols.ell }; print!("{0}{1}{1} ", c, symbols.right); } } Prefix::None => (), } println!("{}{}", format.display(&package.id, package.metadata), star); if!new { return; } let mut normal = vec![]; let mut build = vec![]; let mut development = vec![]; for edge in graph .graph .edges_directed(graph.nodes[&package.id], direction) { let dep = match direction { EdgeDirection::Incoming => &graph.graph[edge.source()], EdgeDirection::Outgoing => &graph.graph[edge.target()], }; match *edge.weight() { Kind::Normal => normal.push(dep), Kind::Build => build.push(dep), Kind::Development => development.push(dep), } } print_dependency_kind( Kind::Normal, normal, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); print_dependency_kind( Kind::Build, build, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); print_dependency_kind( Kind::Development, development, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); } fn print_dependency_kind<'a>( kind: Kind, mut deps: Vec<&Node<'a>>, graph: &Graph<'a>, format: &Pattern, direction: EdgeDirection, symbols: &Symbols, visited_deps: &mut HashSet<PackageId>, levels_continue: &mut Vec<bool>, prefix: Prefix, all: bool, ) { if deps.is_empty() {
Resolve uses Hash data types internally but we want consistent output ordering deps.sort_by_key(|n| n.id); let name = match kind { Kind::Normal => None, Kind::Build => Some("[build-dependencies]"), Kind::Development => Some("[dev-dependencies]"), }; if let Prefix::Indent = prefix { if let Some(name) = name { for &continues in &**levels_continue { let c = if continues { symbols.down } else { " " }; print!("{} ", c); } println!("{}", name); } } let mut it = deps.iter().peekable(); while let Some(dependency) = it.next() { levels_continue.push(it.peek().is_some()); print_dependency( dependency, graph, format, direction, symbols, visited_deps, levels_continue, prefix, all, ); levels_continue.pop(); } }
return; } //
conditional_block
arena.rs
// Copyright 2019 Fullstop000 <[email protected]>. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use crate::util::slice::Slice; use std::mem; use std::slice; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use super::skiplist::{Node, MAX_HEIGHT, MAX_NODE_SIZE}; pub trait Arena { /// Allocate memory for a node by given height. /// This method allocates a Node size + height * ptr ( u64 ) memory area. // TODO: define the potential errors and return Result<Error, *mut Node> instead of raw pointer fn alloc_node(&self, height: usize) -> *mut Node; /// Copy bytes data of the Slice into arena directly and return the starting offset fn alloc_bytes(&self, data: &Slice) -> u32; /// Get in memory arena bytes as Slice from start point to start + offset fn get(&self, offset: usize, count: usize) -> Slice; /// Return bool to indicate whether there is enough room for given size /// If false, use a new arena for allocating and flush the old. fn has_room_for(&self, size: usize) -> bool; /// Return the size of memory that allocated fn size(&self) -> usize; /// Return the size of memory that has been allocated. fn memory_used(&self) -> usize; } // TODO: implement CommonArena: https://github.com/google/leveldb/blob/master/util/arena.cc /// AggressiveArena is a memory pool for allocating and handling Node memory dynamically. /// Unlike CommonArena, this simplify the memory handling by aggressively pre-allocating /// the total fixed memory so it's caller's responsibility to ensure the room before allocating. pub struct AggressiveArena { // indicates that how many memories has been allocated actually pub(super) offset: AtomicUsize, pub(super) mem: Vec<u8>, } impl AggressiveArena { /// Create an AggressiveArena with given cap. /// This function will allocate a cap size memory block directly for further usage pub fn new(cap: usize) -> AggressiveArena { AggressiveArena { offset: AtomicUsize::new(0), mem: Vec::<u8>::with_capacity(cap), } } /// For test pub(super) fn display_all(&self) -> Vec<u8> { let mut result = Vec::with_capacity(self.mem.capacity()); unsafe { let ptr = self.mem.as_ptr(); for i in 0..self.offset.load(Ordering::Acquire) { let p = ptr.add(i) as *mut u8; result.push(*p) } } result } } impl Arena for AggressiveArena { fn alloc_node(&self, height: usize) -> *mut Node { let ptr_size = mem::size_of::<*mut u8>(); // truncate node size to reduce waste let used_node_size = MAX_NODE_SIZE - (MAX_HEIGHT - height) * ptr_size; let n = self.offset.fetch_add(used_node_size, Ordering::SeqCst); unsafe { let node_ptr = self.mem.as_ptr().add(n) as *mut u8; // get the actually to-be-used memory of node and spilt it into 2 parts: // node part: the Node struct // nexts part: the pre allocated memory used by elements of next_nodes let (node_part, nexts_part) = slice::from_raw_parts_mut(node_ptr, used_node_size) .split_at_mut(used_node_size - height * ptr_size); #[allow(clippy::cast_ptr_alignment)] let node = node_part.as_mut_ptr() as *mut Node; // FIXME: Box::from_raw can be unsafe when releasing memory #[allow(clippy::cast_ptr_alignment)] let next_nodes = Box::from_raw(slice::from_raw_parts_mut( nexts_part.as_mut_ptr() as *mut AtomicPtr<Node>, height, )); (*node).height = height; (*node).next_nodes = next_nodes; node } } fn alloc_bytes(&self, data: &Slice) -> u32 { let start = self.offset.fetch_add(data.size(), Ordering::SeqCst); unsafe { let ptr = self.mem.as_ptr().add(start) as *mut u8; for (i, b) in data.to_slice().iter().enumerate() { let p = ptr.add(i) as *mut u8; (*p) = *b; } } start as u32 } fn get(&self, start: usize, count: usize) -> Slice { let o = self.offset.load(Ordering::Acquire); invarint!( start + count <= o, "[arena] try to get data from [{}] to [{}] but max count is [{}]", start, start + count, o, ); unsafe { let ptr = self.mem.as_ptr().add(start) as *const u8; Slice::new(ptr, count) } } #[inline] fn has_room_for(&self, size: usize) -> bool { self.size() - self.memory_used() >= size } #[inline] fn size(&self) -> usize { self.mem.capacity() } #[inline] fn memory_used(&self) -> usize { self.offset.load(Ordering::Acquire) } } #[cfg(test)] mod tests { use super::*; use std::sync::{Arc, Mutex}; use std::thread; fn new_default_arena() -> AggressiveArena { AggressiveArena::new(64 << 20) } #[test] fn test_new_arena() { let cap = 200; let arena = AggressiveArena::new(cap); assert_eq!(arena.memory_used(), 0); assert_eq!(arena.size(), cap); } #[test] fn test_alloc_single_node() { let arena = new_default_arena(); let node = arena.alloc_node(MAX_HEIGHT); unsafe { assert_eq!((*node).height, MAX_HEIGHT); assert_eq!((*node).next_nodes.len(), MAX_HEIGHT); assert_eq!((*node).key_size, 0); assert_eq!((*node).key_offset, 0); assert_eq!((*node).value_size, 0); assert_eq!((*node).value_offset, 0); // dereference and assigning should work let u8_ptr = node as *mut u8; (*node).key_offset = 1; let key_offset_ptr = u8_ptr.add(0); assert_eq!(*key_offset_ptr, 1); (*node).key_size = 2; let key_size_ptr = u8_ptr.add(8); assert_eq!(*key_size_ptr, 2); (*node).value_offset = 3; let value_offset_ptr = u8_ptr.add(16); assert_eq!(*value_offset_ptr, 3); (*node).value_size = 4; let value_size_ptr = u8_ptr.add(24); assert_eq!(*value_size_ptr, 4); // the value of data ptr in 'next_nodes' slice must be the beginning pointer of first element let next_nodes_ptr = u8_ptr .add(mem::size_of::<Node>() - mem::size_of::<Box<[AtomicPtr<Node>]>>()) as *mut u64; let first_element_ptr = u8_ptr.add(mem::size_of::<Node>()); assert_eq!( "0x".to_owned() + &format!("{:x}", *next_nodes_ptr), format!("{:?}", first_element_ptr) ); } } #[test] fn test_alloc_nodes() { let arena = new_default_arena(); let node1 = arena.alloc_node(4); let node2 = arena.alloc_node(MAX_HEIGHT); unsafe { // node1 and node2 should be neighbor in memory let struct_tail = node1.add(1) as *mut *mut Node; let nexts_tail = struct_tail.add(4); assert_eq!(nexts_tail as *mut Node, node2); }; } #[test] fn test_simple_alloc_bytes() { let mut arena = AggressiveArena::new(100); let input = vec![1u8, 2u8, 3u8, 4u8, 5u8]; let offset = arena.alloc_bytes(&Slice::from(&input)); unsafe { let ptr = arena.mem.as_mut_ptr().add(offset as usize) as *mut u8; for (i, b) in input.clone().iter().enumerate() { let p = ptr.add(i); assert_eq!(*p, *b); } } } #[test] fn test_alloc_bytes_concurrency() { let arena = Arc::new(AggressiveArena::new(500)); let results = Arc::new(Mutex::new(vec![])); let mut tests = vec![vec![1u8, 2, 3, 4, 5], vec![6u8, 7, 8, 9], vec![10u8, 11]]; for t in tests .drain(..) .map(|test| { let cloned_arena = arena.clone(); let cloned_results = results.clone(); thread::spawn(move || { let offset = cloned_arena.alloc_bytes(&Slice::from(test.as_slice())) as usize; // start position in arena, origin test data cloned_results.lock().unwrap().push((offset, test)); }) }) .collect::<Vec<_>>() { t.join().unwrap(); } let mem_ptr = arena.mem.as_ptr(); for (offset, expect) in results.lock().unwrap().drain(..) { // compare result and expect byte by byte unsafe { let ptr = mem_ptr.add(offset) as *mut u8; for (i, b) in expect.iter().enumerate() { let inmem_b = ptr.add(i); assert_eq!(*inmem_b, *b); } } } } #[test] fn test_get() { let arena = new_default_arena(); let input = vec![1u8, 2u8, 3u8, 4u8, 5u8]; let start = arena.alloc_bytes(&Slice::from(input.as_slice())); let result = arena.get(start as usize, 5); for (b1, b2) in input.iter().zip(result.to_slice()) { assert_eq!(*b1, *b2); } } #[test] fn test_memory_used() { let arena = new_default_arena();
#[test] fn test_has_room_for() { let arena = AggressiveArena::new(1); assert_eq!(arena.has_room_for(100), false); } }
arena.alloc_node(MAX_HEIGHT); // 152 arena.alloc_node(1); // 64 arena.alloc_bytes(&Slice::from(vec![1u8, 2u8, 3u8, 4u8].as_slice())); // 4 assert_eq!(152 + 64 + 4, arena.memory_used()) }
random_line_split
arena.rs
// Copyright 2019 Fullstop000 <[email protected]>. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use crate::util::slice::Slice; use std::mem; use std::slice; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use super::skiplist::{Node, MAX_HEIGHT, MAX_NODE_SIZE}; pub trait Arena { /// Allocate memory for a node by given height. /// This method allocates a Node size + height * ptr ( u64 ) memory area. // TODO: define the potential errors and return Result<Error, *mut Node> instead of raw pointer fn alloc_node(&self, height: usize) -> *mut Node; /// Copy bytes data of the Slice into arena directly and return the starting offset fn alloc_bytes(&self, data: &Slice) -> u32; /// Get in memory arena bytes as Slice from start point to start + offset fn get(&self, offset: usize, count: usize) -> Slice; /// Return bool to indicate whether there is enough room for given size /// If false, use a new arena for allocating and flush the old. fn has_room_for(&self, size: usize) -> bool; /// Return the size of memory that allocated fn size(&self) -> usize; /// Return the size of memory that has been allocated. fn memory_used(&self) -> usize; } // TODO: implement CommonArena: https://github.com/google/leveldb/blob/master/util/arena.cc /// AggressiveArena is a memory pool for allocating and handling Node memory dynamically. /// Unlike CommonArena, this simplify the memory handling by aggressively pre-allocating /// the total fixed memory so it's caller's responsibility to ensure the room before allocating. pub struct AggressiveArena { // indicates that how many memories has been allocated actually pub(super) offset: AtomicUsize, pub(super) mem: Vec<u8>, } impl AggressiveArena { /// Create an AggressiveArena with given cap. /// This function will allocate a cap size memory block directly for further usage pub fn new(cap: usize) -> AggressiveArena { AggressiveArena { offset: AtomicUsize::new(0), mem: Vec::<u8>::with_capacity(cap), } } /// For test pub(super) fn display_all(&self) -> Vec<u8> { let mut result = Vec::with_capacity(self.mem.capacity()); unsafe { let ptr = self.mem.as_ptr(); for i in 0..self.offset.load(Ordering::Acquire) { let p = ptr.add(i) as *mut u8; result.push(*p) } } result } } impl Arena for AggressiveArena { fn alloc_node(&self, height: usize) -> *mut Node { let ptr_size = mem::size_of::<*mut u8>(); // truncate node size to reduce waste let used_node_size = MAX_NODE_SIZE - (MAX_HEIGHT - height) * ptr_size; let n = self.offset.fetch_add(used_node_size, Ordering::SeqCst); unsafe { let node_ptr = self.mem.as_ptr().add(n) as *mut u8; // get the actually to-be-used memory of node and spilt it into 2 parts: // node part: the Node struct // nexts part: the pre allocated memory used by elements of next_nodes let (node_part, nexts_part) = slice::from_raw_parts_mut(node_ptr, used_node_size) .split_at_mut(used_node_size - height * ptr_size); #[allow(clippy::cast_ptr_alignment)] let node = node_part.as_mut_ptr() as *mut Node; // FIXME: Box::from_raw can be unsafe when releasing memory #[allow(clippy::cast_ptr_alignment)] let next_nodes = Box::from_raw(slice::from_raw_parts_mut( nexts_part.as_mut_ptr() as *mut AtomicPtr<Node>, height, )); (*node).height = height; (*node).next_nodes = next_nodes; node } } fn alloc_bytes(&self, data: &Slice) -> u32 { let start = self.offset.fetch_add(data.size(), Ordering::SeqCst); unsafe { let ptr = self.mem.as_ptr().add(start) as *mut u8; for (i, b) in data.to_slice().iter().enumerate() { let p = ptr.add(i) as *mut u8; (*p) = *b; } } start as u32 } fn get(&self, start: usize, count: usize) -> Slice { let o = self.offset.load(Ordering::Acquire); invarint!( start + count <= o, "[arena] try to get data from [{}] to [{}] but max count is [{}]", start, start + count, o, ); unsafe { let ptr = self.mem.as_ptr().add(start) as *const u8; Slice::new(ptr, count) } } #[inline] fn has_room_for(&self, size: usize) -> bool { self.size() - self.memory_used() >= size } #[inline] fn size(&self) -> usize { self.mem.capacity() } #[inline] fn memory_used(&self) -> usize { self.offset.load(Ordering::Acquire) } } #[cfg(test)] mod tests { use super::*; use std::sync::{Arc, Mutex}; use std::thread; fn new_default_arena() -> AggressiveArena { AggressiveArena::new(64 << 20) } #[test] fn test_new_arena() { let cap = 200; let arena = AggressiveArena::new(cap); assert_eq!(arena.memory_used(), 0); assert_eq!(arena.size(), cap); } #[test] fn test_alloc_single_node() { let arena = new_default_arena(); let node = arena.alloc_node(MAX_HEIGHT); unsafe { assert_eq!((*node).height, MAX_HEIGHT); assert_eq!((*node).next_nodes.len(), MAX_HEIGHT); assert_eq!((*node).key_size, 0); assert_eq!((*node).key_offset, 0); assert_eq!((*node).value_size, 0); assert_eq!((*node).value_offset, 0); // dereference and assigning should work let u8_ptr = node as *mut u8; (*node).key_offset = 1; let key_offset_ptr = u8_ptr.add(0); assert_eq!(*key_offset_ptr, 1); (*node).key_size = 2; let key_size_ptr = u8_ptr.add(8); assert_eq!(*key_size_ptr, 2); (*node).value_offset = 3; let value_offset_ptr = u8_ptr.add(16); assert_eq!(*value_offset_ptr, 3); (*node).value_size = 4; let value_size_ptr = u8_ptr.add(24); assert_eq!(*value_size_ptr, 4); // the value of data ptr in 'next_nodes' slice must be the beginning pointer of first element let next_nodes_ptr = u8_ptr .add(mem::size_of::<Node>() - mem::size_of::<Box<[AtomicPtr<Node>]>>()) as *mut u64; let first_element_ptr = u8_ptr.add(mem::size_of::<Node>()); assert_eq!( "0x".to_owned() + &format!("{:x}", *next_nodes_ptr), format!("{:?}", first_element_ptr) ); } } #[test] fn test_alloc_nodes() { let arena = new_default_arena(); let node1 = arena.alloc_node(4); let node2 = arena.alloc_node(MAX_HEIGHT); unsafe { // node1 and node2 should be neighbor in memory let struct_tail = node1.add(1) as *mut *mut Node; let nexts_tail = struct_tail.add(4); assert_eq!(nexts_tail as *mut Node, node2); }; } #[test] fn test_simple_alloc_bytes() { let mut arena = AggressiveArena::new(100); let input = vec![1u8, 2u8, 3u8, 4u8, 5u8]; let offset = arena.alloc_bytes(&Slice::from(&input)); unsafe { let ptr = arena.mem.as_mut_ptr().add(offset as usize) as *mut u8; for (i, b) in input.clone().iter().enumerate() { let p = ptr.add(i); assert_eq!(*p, *b); } } } #[test] fn
() { let arena = Arc::new(AggressiveArena::new(500)); let results = Arc::new(Mutex::new(vec![])); let mut tests = vec![vec![1u8, 2, 3, 4, 5], vec![6u8, 7, 8, 9], vec![10u8, 11]]; for t in tests .drain(..) .map(|test| { let cloned_arena = arena.clone(); let cloned_results = results.clone(); thread::spawn(move || { let offset = cloned_arena.alloc_bytes(&Slice::from(test.as_slice())) as usize; // start position in arena, origin test data cloned_results.lock().unwrap().push((offset, test)); }) }) .collect::<Vec<_>>() { t.join().unwrap(); } let mem_ptr = arena.mem.as_ptr(); for (offset, expect) in results.lock().unwrap().drain(..) { // compare result and expect byte by byte unsafe { let ptr = mem_ptr.add(offset) as *mut u8; for (i, b) in expect.iter().enumerate() { let inmem_b = ptr.add(i); assert_eq!(*inmem_b, *b); } } } } #[test] fn test_get() { let arena = new_default_arena(); let input = vec![1u8, 2u8, 3u8, 4u8, 5u8]; let start = arena.alloc_bytes(&Slice::from(input.as_slice())); let result = arena.get(start as usize, 5); for (b1, b2) in input.iter().zip(result.to_slice()) { assert_eq!(*b1, *b2); } } #[test] fn test_memory_used() { let arena = new_default_arena(); arena.alloc_node(MAX_HEIGHT); // 152 arena.alloc_node(1); // 64 arena.alloc_bytes(&Slice::from(vec![1u8, 2u8, 3u8, 4u8].as_slice())); // 4 assert_eq!(152 + 64 + 4, arena.memory_used()) } #[test] fn test_has_room_for() { let arena = AggressiveArena::new(1); assert_eq!(arena.has_room_for(100), false); } }
test_alloc_bytes_concurrency
identifier_name
arena.rs
// Copyright 2019 Fullstop000 <[email protected]>. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use crate::util::slice::Slice; use std::mem; use std::slice; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use super::skiplist::{Node, MAX_HEIGHT, MAX_NODE_SIZE}; pub trait Arena { /// Allocate memory for a node by given height. /// This method allocates a Node size + height * ptr ( u64 ) memory area. // TODO: define the potential errors and return Result<Error, *mut Node> instead of raw pointer fn alloc_node(&self, height: usize) -> *mut Node; /// Copy bytes data of the Slice into arena directly and return the starting offset fn alloc_bytes(&self, data: &Slice) -> u32; /// Get in memory arena bytes as Slice from start point to start + offset fn get(&self, offset: usize, count: usize) -> Slice; /// Return bool to indicate whether there is enough room for given size /// If false, use a new arena for allocating and flush the old. fn has_room_for(&self, size: usize) -> bool; /// Return the size of memory that allocated fn size(&self) -> usize; /// Return the size of memory that has been allocated. fn memory_used(&self) -> usize; } // TODO: implement CommonArena: https://github.com/google/leveldb/blob/master/util/arena.cc /// AggressiveArena is a memory pool for allocating and handling Node memory dynamically. /// Unlike CommonArena, this simplify the memory handling by aggressively pre-allocating /// the total fixed memory so it's caller's responsibility to ensure the room before allocating. pub struct AggressiveArena { // indicates that how many memories has been allocated actually pub(super) offset: AtomicUsize, pub(super) mem: Vec<u8>, } impl AggressiveArena { /// Create an AggressiveArena with given cap. /// This function will allocate a cap size memory block directly for further usage pub fn new(cap: usize) -> AggressiveArena { AggressiveArena { offset: AtomicUsize::new(0), mem: Vec::<u8>::with_capacity(cap), } } /// For test pub(super) fn display_all(&self) -> Vec<u8> { let mut result = Vec::with_capacity(self.mem.capacity()); unsafe { let ptr = self.mem.as_ptr(); for i in 0..self.offset.load(Ordering::Acquire) { let p = ptr.add(i) as *mut u8; result.push(*p) } } result } } impl Arena for AggressiveArena { fn alloc_node(&self, height: usize) -> *mut Node
(*node).height = height; (*node).next_nodes = next_nodes; node } } fn alloc_bytes(&self, data: &Slice) -> u32 { let start = self.offset.fetch_add(data.size(), Ordering::SeqCst); unsafe { let ptr = self.mem.as_ptr().add(start) as *mut u8; for (i, b) in data.to_slice().iter().enumerate() { let p = ptr.add(i) as *mut u8; (*p) = *b; } } start as u32 } fn get(&self, start: usize, count: usize) -> Slice { let o = self.offset.load(Ordering::Acquire); invarint!( start + count <= o, "[arena] try to get data from [{}] to [{}] but max count is [{}]", start, start + count, o, ); unsafe { let ptr = self.mem.as_ptr().add(start) as *const u8; Slice::new(ptr, count) } } #[inline] fn has_room_for(&self, size: usize) -> bool { self.size() - self.memory_used() >= size } #[inline] fn size(&self) -> usize { self.mem.capacity() } #[inline] fn memory_used(&self) -> usize { self.offset.load(Ordering::Acquire) } } #[cfg(test)] mod tests { use super::*; use std::sync::{Arc, Mutex}; use std::thread; fn new_default_arena() -> AggressiveArena { AggressiveArena::new(64 << 20) } #[test] fn test_new_arena() { let cap = 200; let arena = AggressiveArena::new(cap); assert_eq!(arena.memory_used(), 0); assert_eq!(arena.size(), cap); } #[test] fn test_alloc_single_node() { let arena = new_default_arena(); let node = arena.alloc_node(MAX_HEIGHT); unsafe { assert_eq!((*node).height, MAX_HEIGHT); assert_eq!((*node).next_nodes.len(), MAX_HEIGHT); assert_eq!((*node).key_size, 0); assert_eq!((*node).key_offset, 0); assert_eq!((*node).value_size, 0); assert_eq!((*node).value_offset, 0); // dereference and assigning should work let u8_ptr = node as *mut u8; (*node).key_offset = 1; let key_offset_ptr = u8_ptr.add(0); assert_eq!(*key_offset_ptr, 1); (*node).key_size = 2; let key_size_ptr = u8_ptr.add(8); assert_eq!(*key_size_ptr, 2); (*node).value_offset = 3; let value_offset_ptr = u8_ptr.add(16); assert_eq!(*value_offset_ptr, 3); (*node).value_size = 4; let value_size_ptr = u8_ptr.add(24); assert_eq!(*value_size_ptr, 4); // the value of data ptr in 'next_nodes' slice must be the beginning pointer of first element let next_nodes_ptr = u8_ptr .add(mem::size_of::<Node>() - mem::size_of::<Box<[AtomicPtr<Node>]>>()) as *mut u64; let first_element_ptr = u8_ptr.add(mem::size_of::<Node>()); assert_eq!( "0x".to_owned() + &format!("{:x}", *next_nodes_ptr), format!("{:?}", first_element_ptr) ); } } #[test] fn test_alloc_nodes() { let arena = new_default_arena(); let node1 = arena.alloc_node(4); let node2 = arena.alloc_node(MAX_HEIGHT); unsafe { // node1 and node2 should be neighbor in memory let struct_tail = node1.add(1) as *mut *mut Node; let nexts_tail = struct_tail.add(4); assert_eq!(nexts_tail as *mut Node, node2); }; } #[test] fn test_simple_alloc_bytes() { let mut arena = AggressiveArena::new(100); let input = vec![1u8, 2u8, 3u8, 4u8, 5u8]; let offset = arena.alloc_bytes(&Slice::from(&input)); unsafe { let ptr = arena.mem.as_mut_ptr().add(offset as usize) as *mut u8; for (i, b) in input.clone().iter().enumerate() { let p = ptr.add(i); assert_eq!(*p, *b); } } } #[test] fn test_alloc_bytes_concurrency() { let arena = Arc::new(AggressiveArena::new(500)); let results = Arc::new(Mutex::new(vec![])); let mut tests = vec![vec![1u8, 2, 3, 4, 5], vec![6u8, 7, 8, 9], vec![10u8, 11]]; for t in tests .drain(..) .map(|test| { let cloned_arena = arena.clone(); let cloned_results = results.clone(); thread::spawn(move || { let offset = cloned_arena.alloc_bytes(&Slice::from(test.as_slice())) as usize; // start position in arena, origin test data cloned_results.lock().unwrap().push((offset, test)); }) }) .collect::<Vec<_>>() { t.join().unwrap(); } let mem_ptr = arena.mem.as_ptr(); for (offset, expect) in results.lock().unwrap().drain(..) { // compare result and expect byte by byte unsafe { let ptr = mem_ptr.add(offset) as *mut u8; for (i, b) in expect.iter().enumerate() { let inmem_b = ptr.add(i); assert_eq!(*inmem_b, *b); } } } } #[test] fn test_get() { let arena = new_default_arena(); let input = vec![1u8, 2u8, 3u8, 4u8, 5u8]; let start = arena.alloc_bytes(&Slice::from(input.as_slice())); let result = arena.get(start as usize, 5); for (b1, b2) in input.iter().zip(result.to_slice()) { assert_eq!(*b1, *b2); } } #[test] fn test_memory_used() { let arena = new_default_arena(); arena.alloc_node(MAX_HEIGHT); // 152 arena.alloc_node(1); // 64 arena.alloc_bytes(&Slice::from(vec![1u8, 2u8, 3u8, 4u8].as_slice())); // 4 assert_eq!(152 + 64 + 4, arena.memory_used()) } #[test] fn test_has_room_for() { let arena = AggressiveArena::new(1); assert_eq!(arena.has_room_for(100), false); } }
{ let ptr_size = mem::size_of::<*mut u8>(); // truncate node size to reduce waste let used_node_size = MAX_NODE_SIZE - (MAX_HEIGHT - height) * ptr_size; let n = self.offset.fetch_add(used_node_size, Ordering::SeqCst); unsafe { let node_ptr = self.mem.as_ptr().add(n) as *mut u8; // get the actually to-be-used memory of node and spilt it into 2 parts: // node part: the Node struct // nexts part: the pre allocated memory used by elements of next_nodes let (node_part, nexts_part) = slice::from_raw_parts_mut(node_ptr, used_node_size) .split_at_mut(used_node_size - height * ptr_size); #[allow(clippy::cast_ptr_alignment)] let node = node_part.as_mut_ptr() as *mut Node; // FIXME: Box::from_raw can be unsafe when releasing memory #[allow(clippy::cast_ptr_alignment)] let next_nodes = Box::from_raw(slice::from_raw_parts_mut( nexts_part.as_mut_ptr() as *mut AtomicPtr<Node>, height, ));
identifier_body
keys.rs
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. use std::collections::{BTreeMap, HashMap}; use std::hash::BuildHasherDefault; use fnv::FnvHasher; use std::str; use info::{self, capability as cap}; #[derive(Debug)] pub struct Keys(BTreeMap<usize, HashMap<Vec<u8>, Key, BuildHasherDefault<FnvHasher>>>); #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Key { pub modifier: Modifier, pub value: Value, } bitflags! { pub struct Modifier: u8 { const NONE = 0; const ALT = 1 << 0; const CTRL = 1 << 1; const LOGO = 1 << 2; const SHIFT = 1 << 3; } } impl Default for Modifier { fn default() -> Self { Modifier::empty() } } #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum Value { Escape, Enter, Down, Up, Left, Right, PageUp, PageDown, BackSpace, BackTab, Tab, Delete, Insert, Home, End, Begin, F(u8), Char(char), } pub use self::Value::*; impl Keys { pub fn new(info: &info::Database) -> Self { let mut map = BTreeMap::default(); // Load terminfo bindings. { macro_rules! insert { ($name:ident => $($key:tt)*) => ( if let Some(cap) = info.get::<cap::$name>() { let value: &[u8] = cap.as_ref(); map.entry(value.len()).or_insert(HashMap::default()) .entry(value.into()).or_insert(Key { modifier: Modifier::empty(), value: Value::$($key)* }); } ) } insert!(KeyEnter => Enter); insert!(CarriageReturn => Enter); insert!(KeyDown => Down); insert!(KeyUp => Up); insert!(KeyLeft => Left); insert!(KeyRight => Right); insert!(KeyNPage => PageDown); insert!(KeyPPage => PageUp); insert!(KeyBackspace => BackSpace); insert!(KeyBTab => BackTab); insert!(Tab => Tab); insert!(KeyF1 => F(1)); insert!(KeyF2 => F(2)); insert!(KeyF3 => F(3)); insert!(KeyF4 => F(4)); insert!(KeyF5 => F(5)); insert!(KeyF6 => F(6)); insert!(KeyF7 => F(7)); insert!(KeyF8 => F(8)); insert!(KeyF9 => F(9)); insert!(KeyF10 => F(10)); insert!(KeyF11 => F(11)); insert!(KeyF12 => F(12)); insert!(KeyF13 => F(13)); insert!(KeyF14 => F(14)); insert!(KeyF15 => F(15)); insert!(KeyF16 => F(16)); insert!(KeyF17 => F(17)); insert!(KeyF18 => F(18)); insert!(KeyF19 => F(19)); insert!(KeyF20 => F(20)); insert!(KeyF21 => F(21)); insert!(KeyF22 => F(22)); insert!(KeyF23 => F(23)); insert!(KeyF24 => F(24)); insert!(KeyF25 => F(25)); insert!(KeyF26 => F(26)); insert!(KeyF27 => F(27)); insert!(KeyF28 => F(28)); insert!(KeyF29 => F(29)); insert!(KeyF30 => F(30)); insert!(KeyF31 => F(31)); insert!(KeyF32 => F(32)); insert!(KeyF33 => F(33)); insert!(KeyF34 => F(34)); insert!(KeyF35 => F(35)); insert!(KeyF36 => F(36)); insert!(KeyF37 => F(37)); insert!(KeyF38 => F(38)); insert!(KeyF39 => F(39)); insert!(KeyF40 => F(40)); insert!(KeyF41 => F(41)); insert!(KeyF42 => F(42)); insert!(KeyF43 => F(43)); insert!(KeyF44 => F(44)); insert!(KeyF45 => F(45)); insert!(KeyF46 => F(46)); insert!(KeyF47 => F(47)); insert!(KeyF48 => F(48)); insert!(KeyF49 => F(49)); insert!(KeyF50 => F(50)); insert!(KeyF51 => F(51)); insert!(KeyF52 => F(52)); insert!(KeyF53 => F(53)); insert!(KeyF54 => F(54)); insert!(KeyF55 => F(55)); insert!(KeyF56 => F(56)); insert!(KeyF57 => F(57)); insert!(KeyF58 => F(58)); insert!(KeyF59 => F(59)); insert!(KeyF60 => F(60)); insert!(KeyF61 => F(61)); insert!(KeyF62 => F(62)); insert!(KeyF63 => F(63)); } // Load default bindings. { macro_rules! insert { ($string:expr => $value:expr) => ( insert!($string => $value; NONE); ); ($string:expr => $value:expr; $($mods:ident)|+) => ( map.entry($string.len()).or_insert(HashMap::default()) .entry($string.to_vec()).or_insert(Key { modifier: $(Modifier::$mods)|+, value: $value, }); ); } insert!(b"\x1B[Z" => Tab; SHIFT); insert!(b"\x1B\x7F" => BackSpace; ALT); insert!(b"\x7F" => BackSpace); insert!(b"\x1B\r\n" => Enter; ALT); insert!(b"\x1B\r" => Enter; ALT); insert!(b"\x1B\n" => Enter; ALT); insert!(b"\r\n" => Enter); insert!(b"\r" => Enter); insert!(b"\n" => Enter); insert!(b"\x1B[3;5~" => Delete; CTRL); insert!(b"\x1B[3;2~" => Delete; SHIFT); insert!(b"\x1B[3~" => Delete); insert!(b"\x1B[2;5~" => Insert; CTRL); insert!(b"\x1B[2;2~" => Insert; SHIFT); insert!(b"\x1B[2~" => Insert); insert!(b"\x1B[1;2H" => Home; SHIFT); insert!(b"\x1B[H" => Home); insert!(b"\x1B[1;5F" => End; CTRL); insert!(b"\x1B[1;2F" => End; SHIFT); insert!(b"\x1B[8~" => End); insert!(b"\x1B[E" => Begin); insert!(b"\x1B[5;5~" => PageUp; CTRL); insert!(b"\x1B[5;2~" => PageUp; SHIFT); insert!(b"\x1B[5~" => PageUp); insert!(b"\x1B[6;5~" => PageDown; CTRL); insert!(b"\x1B[6;2~" => PageDown; SHIFT); insert!(b"\x1B[6~" => PageDown); insert!(b"\x1B[1;5A" => Up; CTRL); insert!(b"\x1B[1;3A" => Up; ALT); insert!(b"\x1B[1;2A" => Up; SHIFT); insert!(b"\x1BBOA" => Up); insert!(b"\x1B[1;5B" => Down; CTRL); insert!(b"\x1B[1;3B" => Down; ALT); insert!(b"\x1B[1;2B" => Down; SHIFT); insert!(b"\x1BBOB" => Down); insert!(b"\x1B[1;5C" => Right; CTRL); insert!(b"\x1B[1;3C" => Right; ALT); insert!(b"\x1B[1;2C" => Right; SHIFT); insert!(b"\x1BBOC" => Right); insert!(b"\x1B[1;5D" => Left; CTRL); insert!(b"\x1B[1;3D" => Left; ALT); insert!(b"\x1B[1;2D" => Left; SHIFT); insert!(b"\x1BBOD" => Left); insert!(b"\x1B[1;5P" => F(1); CTRL); insert!(b"\x1B[1;3P" => F(1); ALT); insert!(b"\x1B[1;6P" => F(1); LOGO); insert!(b"\x1B[1;2P" => F(1); SHIFT); insert!(b"\x1BOP" => F(1)); insert!(b"\x1B[1;5Q" => F(2); CTRL); insert!(b"\x1B[1;3Q" => F(2); ALT); insert!(b"\x1B[1;6Q" => F(2); LOGO); insert!(b"\x1B[1;2Q" => F(2); SHIFT); insert!(b"\x1BOQ" => F(2)); insert!(b"\x1B[1;5R" => F(3); CTRL); insert!(b"\x1B[1;3R" => F(3); ALT); insert!(b"\x1B[1;6R" => F(3); LOGO); insert!(b"\x1B[1;2R" => F(3); SHIFT); insert!(b"\x1BOR" => F(3)); insert!(b"\x1B[1;5S" => F(4); CTRL); insert!(b"\x1B[1;3S" => F(4); ALT); insert!(b"\x1B[1;6S" => F(4); LOGO); insert!(b"\x1B[1;2S" => F(4); SHIFT); insert!(b"\x1BOS" => F(4)); insert!(b"\x1B[15;5~" => F(5); CTRL); insert!(b"\x1B[15;3~" => F(5); ALT); insert!(b"\x1B[15;6~" => F(5); LOGO); insert!(b"\x1B[15;2~" => F(5); SHIFT); insert!(b"\x1B[15~" => F(5)); insert!(b"\x1B[17;5~" => F(6); CTRL); insert!(b"\x1B[17;3~" => F(6); ALT); insert!(b"\x1B[17;6~" => F(6); LOGO); insert!(b"\x1B[17;2~" => F(6); SHIFT); insert!(b"\x1B[17~" => F(6)); insert!(b"\x1B[18;5~" => F(7); CTRL); insert!(b"\x1B[18;3~" => F(7); ALT); insert!(b"\x1B[18;6~" => F(7); LOGO); insert!(b"\x1B[18;2~" => F(7); SHIFT); insert!(b"\x1B[18~" => F(7)); insert!(b"\x1B[19;5~" => F(8); CTRL); insert!(b"\x1B[19;3~" => F(8); ALT); insert!(b"\x1B[19;6~" => F(8); LOGO); insert!(b"\x1B[19;2~" => F(8); SHIFT); insert!(b"\x1B[19~" => F(8)); insert!(b"\x1B[20;5~" => F(9); CTRL); insert!(b"\x1B[20;3~" => F(9); ALT); insert!(b"\x1B[20;6~" => F(9); LOGO); insert!(b"\x1B[20;2~" => F(9); SHIFT); insert!(b"\x1B[20~" => F(9)); insert!(b"\x1B[21;5~" => F(10); CTRL); insert!(b"\x1B[21;3~" => F(10); ALT); insert!(b"\x1B[21;6~" => F(10); LOGO); insert!(b"\x1B[21;2~" => F(10); SHIFT); insert!(b"\x1B[21~" => F(10)); insert!(b"\x1B[23;5~" => F(11); CTRL); insert!(b"\x1B[23;3~" => F(11); ALT); insert!(b"\x1B[23;6~" => F(11); LOGO); insert!(b"\x1B[23;2~" => F(11); SHIFT); insert!(b"\x1B[23~" => F(11)); insert!(b"\x1B[24;5~" => F(12); CTRL); insert!(b"\x1B[24;3~" => F(12); ALT); insert!(b"\x1B[24;6~" => F(12); LOGO); insert!(b"\x1B[24;2~" => F(12); SHIFT); insert!(b"\x1B[24~" => F(12)); insert!(b"\x1B[1;2P" => F(13)); insert!(b"\x1B[1;2Q" => F(14)); insert!(b"\x1B[1;2R" => F(15)); insert!(b"\x1B[1;2S" => F(16)); insert!(b"\x1B[15;2~" => F(17)); insert!(b"\x1B[17;2~" => F(18)); insert!(b"\x1B[18;2~" => F(19)); insert!(b"\x1B[19;2~" => F(20)); insert!(b"\x1B[20;2~" => F(21)); insert!(b"\x1B[21;2~" => F(22)); insert!(b"\x1B[23;2~" => F(23)); insert!(b"\x1B[24;2~" => F(24)); insert!(b"\x1B[1;5P" => F(25)); insert!(b"\x1B[1;5Q" => F(26)); insert!(b"\x1B[1;5R" => F(27)); insert!(b"\x1B[1;5S" => F(28)); insert!(b"\x1B[15;5~" => F(29)); insert!(b"\x1B[17;5~" => F(30)); insert!(b"\x1B[18;5~" => F(31)); insert!(b"\x1B[19;5~" => F(32)); insert!(b"\x1B[20;5~" => F(33)); insert!(b"\x1B[21;5~" => F(34)); insert!(b"\x1B[23;5~" => F(35)); } Keys(map) } pub fn bind<T: Into<Vec<u8>>>(&mut self, value: T, key: Key) -> &mut Self { let value = value.into(); if!value.is_empty() { self.0.entry(value.len()).or_insert(HashMap::default()) .insert(value, key); } self } pub fn unbind<T: AsRef<[u8]>>(&mut self, value: T) -> &mut Self { let value = value.as_ref(); if let Some(map) = self.0.get_mut(&value.len()) { map.remove(value); } self } pub fn find<'a>(&self, mut input: &'a [u8]) -> (&'a [u8], Option<Key>) { // Check if it's a defined key. for (&length, map) in self.0.iter().rev() { if length > input.len() { continue; } if let Some(key) = map.get(&input[..length]) { return (&input[length..], Some(*key)); } } // Check if it's a single escape press. if input == &[0x1B] { return (&input[1..], Some(Key { modifier: Modifier::empty(), value: Escape, })); } let mut mods = Modifier::empty(); if input[0] == 0x1B { mods.insert(Modifier::ALT); input = &input[1..]; } // Check if it's a control character. if input[0] & 0b011_00000 == 0 { return (&input[1..], Some(Key { modifier: mods | Modifier::CTRL, value: Char((input[0] | 0b010_00000) as char), })); } // Check if it's a unicode character. const WIDTH: [u8; 256] = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7F 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, 0, 0, 0, 0, 0, 0, // 0x9F 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, 0, 0, 0, 0, 0, 0, // 0xBF 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF ]; let length = WIDTH[input[0] as usize] as usize; if length >= input.len() { if let Ok(string) = str::from_utf8(&input[..length]) {
} (&input[1..], None) } }
return (&input[length..], Some(Key { modifier: mods, value: Char(string.chars().next().unwrap()) })); }
conditional_block
keys.rs
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. use std::collections::{BTreeMap, HashMap}; use std::hash::BuildHasherDefault; use fnv::FnvHasher; use std::str; use info::{self, capability as cap}; #[derive(Debug)] pub struct Keys(BTreeMap<usize, HashMap<Vec<u8>, Key, BuildHasherDefault<FnvHasher>>>); #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Key { pub modifier: Modifier, pub value: Value, } bitflags! { pub struct Modifier: u8 { const NONE = 0; const ALT = 1 << 0; const CTRL = 1 << 1; const LOGO = 1 << 2; const SHIFT = 1 << 3; } } impl Default for Modifier { fn default() -> Self {
#[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum Value { Escape, Enter, Down, Up, Left, Right, PageUp, PageDown, BackSpace, BackTab, Tab, Delete, Insert, Home, End, Begin, F(u8), Char(char), } pub use self::Value::*; impl Keys { pub fn new(info: &info::Database) -> Self { let mut map = BTreeMap::default(); // Load terminfo bindings. { macro_rules! insert { ($name:ident => $($key:tt)*) => ( if let Some(cap) = info.get::<cap::$name>() { let value: &[u8] = cap.as_ref(); map.entry(value.len()).or_insert(HashMap::default()) .entry(value.into()).or_insert(Key { modifier: Modifier::empty(), value: Value::$($key)* }); } ) } insert!(KeyEnter => Enter); insert!(CarriageReturn => Enter); insert!(KeyDown => Down); insert!(KeyUp => Up); insert!(KeyLeft => Left); insert!(KeyRight => Right); insert!(KeyNPage => PageDown); insert!(KeyPPage => PageUp); insert!(KeyBackspace => BackSpace); insert!(KeyBTab => BackTab); insert!(Tab => Tab); insert!(KeyF1 => F(1)); insert!(KeyF2 => F(2)); insert!(KeyF3 => F(3)); insert!(KeyF4 => F(4)); insert!(KeyF5 => F(5)); insert!(KeyF6 => F(6)); insert!(KeyF7 => F(7)); insert!(KeyF8 => F(8)); insert!(KeyF9 => F(9)); insert!(KeyF10 => F(10)); insert!(KeyF11 => F(11)); insert!(KeyF12 => F(12)); insert!(KeyF13 => F(13)); insert!(KeyF14 => F(14)); insert!(KeyF15 => F(15)); insert!(KeyF16 => F(16)); insert!(KeyF17 => F(17)); insert!(KeyF18 => F(18)); insert!(KeyF19 => F(19)); insert!(KeyF20 => F(20)); insert!(KeyF21 => F(21)); insert!(KeyF22 => F(22)); insert!(KeyF23 => F(23)); insert!(KeyF24 => F(24)); insert!(KeyF25 => F(25)); insert!(KeyF26 => F(26)); insert!(KeyF27 => F(27)); insert!(KeyF28 => F(28)); insert!(KeyF29 => F(29)); insert!(KeyF30 => F(30)); insert!(KeyF31 => F(31)); insert!(KeyF32 => F(32)); insert!(KeyF33 => F(33)); insert!(KeyF34 => F(34)); insert!(KeyF35 => F(35)); insert!(KeyF36 => F(36)); insert!(KeyF37 => F(37)); insert!(KeyF38 => F(38)); insert!(KeyF39 => F(39)); insert!(KeyF40 => F(40)); insert!(KeyF41 => F(41)); insert!(KeyF42 => F(42)); insert!(KeyF43 => F(43)); insert!(KeyF44 => F(44)); insert!(KeyF45 => F(45)); insert!(KeyF46 => F(46)); insert!(KeyF47 => F(47)); insert!(KeyF48 => F(48)); insert!(KeyF49 => F(49)); insert!(KeyF50 => F(50)); insert!(KeyF51 => F(51)); insert!(KeyF52 => F(52)); insert!(KeyF53 => F(53)); insert!(KeyF54 => F(54)); insert!(KeyF55 => F(55)); insert!(KeyF56 => F(56)); insert!(KeyF57 => F(57)); insert!(KeyF58 => F(58)); insert!(KeyF59 => F(59)); insert!(KeyF60 => F(60)); insert!(KeyF61 => F(61)); insert!(KeyF62 => F(62)); insert!(KeyF63 => F(63)); } // Load default bindings. { macro_rules! insert { ($string:expr => $value:expr) => ( insert!($string => $value; NONE); ); ($string:expr => $value:expr; $($mods:ident)|+) => ( map.entry($string.len()).or_insert(HashMap::default()) .entry($string.to_vec()).or_insert(Key { modifier: $(Modifier::$mods)|+, value: $value, }); ); } insert!(b"\x1B[Z" => Tab; SHIFT); insert!(b"\x1B\x7F" => BackSpace; ALT); insert!(b"\x7F" => BackSpace); insert!(b"\x1B\r\n" => Enter; ALT); insert!(b"\x1B\r" => Enter; ALT); insert!(b"\x1B\n" => Enter; ALT); insert!(b"\r\n" => Enter); insert!(b"\r" => Enter); insert!(b"\n" => Enter); insert!(b"\x1B[3;5~" => Delete; CTRL); insert!(b"\x1B[3;2~" => Delete; SHIFT); insert!(b"\x1B[3~" => Delete); insert!(b"\x1B[2;5~" => Insert; CTRL); insert!(b"\x1B[2;2~" => Insert; SHIFT); insert!(b"\x1B[2~" => Insert); insert!(b"\x1B[1;2H" => Home; SHIFT); insert!(b"\x1B[H" => Home); insert!(b"\x1B[1;5F" => End; CTRL); insert!(b"\x1B[1;2F" => End; SHIFT); insert!(b"\x1B[8~" => End); insert!(b"\x1B[E" => Begin); insert!(b"\x1B[5;5~" => PageUp; CTRL); insert!(b"\x1B[5;2~" => PageUp; SHIFT); insert!(b"\x1B[5~" => PageUp); insert!(b"\x1B[6;5~" => PageDown; CTRL); insert!(b"\x1B[6;2~" => PageDown; SHIFT); insert!(b"\x1B[6~" => PageDown); insert!(b"\x1B[1;5A" => Up; CTRL); insert!(b"\x1B[1;3A" => Up; ALT); insert!(b"\x1B[1;2A" => Up; SHIFT); insert!(b"\x1BBOA" => Up); insert!(b"\x1B[1;5B" => Down; CTRL); insert!(b"\x1B[1;3B" => Down; ALT); insert!(b"\x1B[1;2B" => Down; SHIFT); insert!(b"\x1BBOB" => Down); insert!(b"\x1B[1;5C" => Right; CTRL); insert!(b"\x1B[1;3C" => Right; ALT); insert!(b"\x1B[1;2C" => Right; SHIFT); insert!(b"\x1BBOC" => Right); insert!(b"\x1B[1;5D" => Left; CTRL); insert!(b"\x1B[1;3D" => Left; ALT); insert!(b"\x1B[1;2D" => Left; SHIFT); insert!(b"\x1BBOD" => Left); insert!(b"\x1B[1;5P" => F(1); CTRL); insert!(b"\x1B[1;3P" => F(1); ALT); insert!(b"\x1B[1;6P" => F(1); LOGO); insert!(b"\x1B[1;2P" => F(1); SHIFT); insert!(b"\x1BOP" => F(1)); insert!(b"\x1B[1;5Q" => F(2); CTRL); insert!(b"\x1B[1;3Q" => F(2); ALT); insert!(b"\x1B[1;6Q" => F(2); LOGO); insert!(b"\x1B[1;2Q" => F(2); SHIFT); insert!(b"\x1BOQ" => F(2)); insert!(b"\x1B[1;5R" => F(3); CTRL); insert!(b"\x1B[1;3R" => F(3); ALT); insert!(b"\x1B[1;6R" => F(3); LOGO); insert!(b"\x1B[1;2R" => F(3); SHIFT); insert!(b"\x1BOR" => F(3)); insert!(b"\x1B[1;5S" => F(4); CTRL); insert!(b"\x1B[1;3S" => F(4); ALT); insert!(b"\x1B[1;6S" => F(4); LOGO); insert!(b"\x1B[1;2S" => F(4); SHIFT); insert!(b"\x1BOS" => F(4)); insert!(b"\x1B[15;5~" => F(5); CTRL); insert!(b"\x1B[15;3~" => F(5); ALT); insert!(b"\x1B[15;6~" => F(5); LOGO); insert!(b"\x1B[15;2~" => F(5); SHIFT); insert!(b"\x1B[15~" => F(5)); insert!(b"\x1B[17;5~" => F(6); CTRL); insert!(b"\x1B[17;3~" => F(6); ALT); insert!(b"\x1B[17;6~" => F(6); LOGO); insert!(b"\x1B[17;2~" => F(6); SHIFT); insert!(b"\x1B[17~" => F(6)); insert!(b"\x1B[18;5~" => F(7); CTRL); insert!(b"\x1B[18;3~" => F(7); ALT); insert!(b"\x1B[18;6~" => F(7); LOGO); insert!(b"\x1B[18;2~" => F(7); SHIFT); insert!(b"\x1B[18~" => F(7)); insert!(b"\x1B[19;5~" => F(8); CTRL); insert!(b"\x1B[19;3~" => F(8); ALT); insert!(b"\x1B[19;6~" => F(8); LOGO); insert!(b"\x1B[19;2~" => F(8); SHIFT); insert!(b"\x1B[19~" => F(8)); insert!(b"\x1B[20;5~" => F(9); CTRL); insert!(b"\x1B[20;3~" => F(9); ALT); insert!(b"\x1B[20;6~" => F(9); LOGO); insert!(b"\x1B[20;2~" => F(9); SHIFT); insert!(b"\x1B[20~" => F(9)); insert!(b"\x1B[21;5~" => F(10); CTRL); insert!(b"\x1B[21;3~" => F(10); ALT); insert!(b"\x1B[21;6~" => F(10); LOGO); insert!(b"\x1B[21;2~" => F(10); SHIFT); insert!(b"\x1B[21~" => F(10)); insert!(b"\x1B[23;5~" => F(11); CTRL); insert!(b"\x1B[23;3~" => F(11); ALT); insert!(b"\x1B[23;6~" => F(11); LOGO); insert!(b"\x1B[23;2~" => F(11); SHIFT); insert!(b"\x1B[23~" => F(11)); insert!(b"\x1B[24;5~" => F(12); CTRL); insert!(b"\x1B[24;3~" => F(12); ALT); insert!(b"\x1B[24;6~" => F(12); LOGO); insert!(b"\x1B[24;2~" => F(12); SHIFT); insert!(b"\x1B[24~" => F(12)); insert!(b"\x1B[1;2P" => F(13)); insert!(b"\x1B[1;2Q" => F(14)); insert!(b"\x1B[1;2R" => F(15)); insert!(b"\x1B[1;2S" => F(16)); insert!(b"\x1B[15;2~" => F(17)); insert!(b"\x1B[17;2~" => F(18)); insert!(b"\x1B[18;2~" => F(19)); insert!(b"\x1B[19;2~" => F(20)); insert!(b"\x1B[20;2~" => F(21)); insert!(b"\x1B[21;2~" => F(22)); insert!(b"\x1B[23;2~" => F(23)); insert!(b"\x1B[24;2~" => F(24)); insert!(b"\x1B[1;5P" => F(25)); insert!(b"\x1B[1;5Q" => F(26)); insert!(b"\x1B[1;5R" => F(27)); insert!(b"\x1B[1;5S" => F(28)); insert!(b"\x1B[15;5~" => F(29)); insert!(b"\x1B[17;5~" => F(30)); insert!(b"\x1B[18;5~" => F(31)); insert!(b"\x1B[19;5~" => F(32)); insert!(b"\x1B[20;5~" => F(33)); insert!(b"\x1B[21;5~" => F(34)); insert!(b"\x1B[23;5~" => F(35)); } Keys(map) } pub fn bind<T: Into<Vec<u8>>>(&mut self, value: T, key: Key) -> &mut Self { let value = value.into(); if!value.is_empty() { self.0.entry(value.len()).or_insert(HashMap::default()) .insert(value, key); } self } pub fn unbind<T: AsRef<[u8]>>(&mut self, value: T) -> &mut Self { let value = value.as_ref(); if let Some(map) = self.0.get_mut(&value.len()) { map.remove(value); } self } pub fn find<'a>(&self, mut input: &'a [u8]) -> (&'a [u8], Option<Key>) { // Check if it's a defined key. for (&length, map) in self.0.iter().rev() { if length > input.len() { continue; } if let Some(key) = map.get(&input[..length]) { return (&input[length..], Some(*key)); } } // Check if it's a single escape press. if input == &[0x1B] { return (&input[1..], Some(Key { modifier: Modifier::empty(), value: Escape, })); } let mut mods = Modifier::empty(); if input[0] == 0x1B { mods.insert(Modifier::ALT); input = &input[1..]; } // Check if it's a control character. if input[0] & 0b011_00000 == 0 { return (&input[1..], Some(Key { modifier: mods | Modifier::CTRL, value: Char((input[0] | 0b010_00000) as char), })); } // Check if it's a unicode character. const WIDTH: [u8; 256] = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7F 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, 0, 0, 0, 0, 0, 0, // 0x9F 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, 0, 0, 0, 0, 0, 0, // 0xBF 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF ]; let length = WIDTH[input[0] as usize] as usize; if length >= input.len() { if let Ok(string) = str::from_utf8(&input[..length]) { return (&input[length..], Some(Key { modifier: mods, value: Char(string.chars().next().unwrap()) })); } } (&input[1..], None) } }
Modifier::empty() } }
identifier_body
keys.rs
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. use std::collections::{BTreeMap, HashMap}; use std::hash::BuildHasherDefault; use fnv::FnvHasher; use std::str; use info::{self, capability as cap}; #[derive(Debug)] pub struct Keys(BTreeMap<usize, HashMap<Vec<u8>, Key, BuildHasherDefault<FnvHasher>>>); #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Ke
pub modifier: Modifier, pub value: Value, } bitflags! { pub struct Modifier: u8 { const NONE = 0; const ALT = 1 << 0; const CTRL = 1 << 1; const LOGO = 1 << 2; const SHIFT = 1 << 3; } } impl Default for Modifier { fn default() -> Self { Modifier::empty() } } #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum Value { Escape, Enter, Down, Up, Left, Right, PageUp, PageDown, BackSpace, BackTab, Tab, Delete, Insert, Home, End, Begin, F(u8), Char(char), } pub use self::Value::*; impl Keys { pub fn new(info: &info::Database) -> Self { let mut map = BTreeMap::default(); // Load terminfo bindings. { macro_rules! insert { ($name:ident => $($key:tt)*) => ( if let Some(cap) = info.get::<cap::$name>() { let value: &[u8] = cap.as_ref(); map.entry(value.len()).or_insert(HashMap::default()) .entry(value.into()).or_insert(Key { modifier: Modifier::empty(), value: Value::$($key)* }); } ) } insert!(KeyEnter => Enter); insert!(CarriageReturn => Enter); insert!(KeyDown => Down); insert!(KeyUp => Up); insert!(KeyLeft => Left); insert!(KeyRight => Right); insert!(KeyNPage => PageDown); insert!(KeyPPage => PageUp); insert!(KeyBackspace => BackSpace); insert!(KeyBTab => BackTab); insert!(Tab => Tab); insert!(KeyF1 => F(1)); insert!(KeyF2 => F(2)); insert!(KeyF3 => F(3)); insert!(KeyF4 => F(4)); insert!(KeyF5 => F(5)); insert!(KeyF6 => F(6)); insert!(KeyF7 => F(7)); insert!(KeyF8 => F(8)); insert!(KeyF9 => F(9)); insert!(KeyF10 => F(10)); insert!(KeyF11 => F(11)); insert!(KeyF12 => F(12)); insert!(KeyF13 => F(13)); insert!(KeyF14 => F(14)); insert!(KeyF15 => F(15)); insert!(KeyF16 => F(16)); insert!(KeyF17 => F(17)); insert!(KeyF18 => F(18)); insert!(KeyF19 => F(19)); insert!(KeyF20 => F(20)); insert!(KeyF21 => F(21)); insert!(KeyF22 => F(22)); insert!(KeyF23 => F(23)); insert!(KeyF24 => F(24)); insert!(KeyF25 => F(25)); insert!(KeyF26 => F(26)); insert!(KeyF27 => F(27)); insert!(KeyF28 => F(28)); insert!(KeyF29 => F(29)); insert!(KeyF30 => F(30)); insert!(KeyF31 => F(31)); insert!(KeyF32 => F(32)); insert!(KeyF33 => F(33)); insert!(KeyF34 => F(34)); insert!(KeyF35 => F(35)); insert!(KeyF36 => F(36)); insert!(KeyF37 => F(37)); insert!(KeyF38 => F(38)); insert!(KeyF39 => F(39)); insert!(KeyF40 => F(40)); insert!(KeyF41 => F(41)); insert!(KeyF42 => F(42)); insert!(KeyF43 => F(43)); insert!(KeyF44 => F(44)); insert!(KeyF45 => F(45)); insert!(KeyF46 => F(46)); insert!(KeyF47 => F(47)); insert!(KeyF48 => F(48)); insert!(KeyF49 => F(49)); insert!(KeyF50 => F(50)); insert!(KeyF51 => F(51)); insert!(KeyF52 => F(52)); insert!(KeyF53 => F(53)); insert!(KeyF54 => F(54)); insert!(KeyF55 => F(55)); insert!(KeyF56 => F(56)); insert!(KeyF57 => F(57)); insert!(KeyF58 => F(58)); insert!(KeyF59 => F(59)); insert!(KeyF60 => F(60)); insert!(KeyF61 => F(61)); insert!(KeyF62 => F(62)); insert!(KeyF63 => F(63)); } // Load default bindings. { macro_rules! insert { ($string:expr => $value:expr) => ( insert!($string => $value; NONE); ); ($string:expr => $value:expr; $($mods:ident)|+) => ( map.entry($string.len()).or_insert(HashMap::default()) .entry($string.to_vec()).or_insert(Key { modifier: $(Modifier::$mods)|+, value: $value, }); ); } insert!(b"\x1B[Z" => Tab; SHIFT); insert!(b"\x1B\x7F" => BackSpace; ALT); insert!(b"\x7F" => BackSpace); insert!(b"\x1B\r\n" => Enter; ALT); insert!(b"\x1B\r" => Enter; ALT); insert!(b"\x1B\n" => Enter; ALT); insert!(b"\r\n" => Enter); insert!(b"\r" => Enter); insert!(b"\n" => Enter); insert!(b"\x1B[3;5~" => Delete; CTRL); insert!(b"\x1B[3;2~" => Delete; SHIFT); insert!(b"\x1B[3~" => Delete); insert!(b"\x1B[2;5~" => Insert; CTRL); insert!(b"\x1B[2;2~" => Insert; SHIFT); insert!(b"\x1B[2~" => Insert); insert!(b"\x1B[1;2H" => Home; SHIFT); insert!(b"\x1B[H" => Home); insert!(b"\x1B[1;5F" => End; CTRL); insert!(b"\x1B[1;2F" => End; SHIFT); insert!(b"\x1B[8~" => End); insert!(b"\x1B[E" => Begin); insert!(b"\x1B[5;5~" => PageUp; CTRL); insert!(b"\x1B[5;2~" => PageUp; SHIFT); insert!(b"\x1B[5~" => PageUp); insert!(b"\x1B[6;5~" => PageDown; CTRL); insert!(b"\x1B[6;2~" => PageDown; SHIFT); insert!(b"\x1B[6~" => PageDown); insert!(b"\x1B[1;5A" => Up; CTRL); insert!(b"\x1B[1;3A" => Up; ALT); insert!(b"\x1B[1;2A" => Up; SHIFT); insert!(b"\x1BBOA" => Up); insert!(b"\x1B[1;5B" => Down; CTRL); insert!(b"\x1B[1;3B" => Down; ALT); insert!(b"\x1B[1;2B" => Down; SHIFT); insert!(b"\x1BBOB" => Down); insert!(b"\x1B[1;5C" => Right; CTRL); insert!(b"\x1B[1;3C" => Right; ALT); insert!(b"\x1B[1;2C" => Right; SHIFT); insert!(b"\x1BBOC" => Right); insert!(b"\x1B[1;5D" => Left; CTRL); insert!(b"\x1B[1;3D" => Left; ALT); insert!(b"\x1B[1;2D" => Left; SHIFT); insert!(b"\x1BBOD" => Left); insert!(b"\x1B[1;5P" => F(1); CTRL); insert!(b"\x1B[1;3P" => F(1); ALT); insert!(b"\x1B[1;6P" => F(1); LOGO); insert!(b"\x1B[1;2P" => F(1); SHIFT); insert!(b"\x1BOP" => F(1)); insert!(b"\x1B[1;5Q" => F(2); CTRL); insert!(b"\x1B[1;3Q" => F(2); ALT); insert!(b"\x1B[1;6Q" => F(2); LOGO); insert!(b"\x1B[1;2Q" => F(2); SHIFT); insert!(b"\x1BOQ" => F(2)); insert!(b"\x1B[1;5R" => F(3); CTRL); insert!(b"\x1B[1;3R" => F(3); ALT); insert!(b"\x1B[1;6R" => F(3); LOGO); insert!(b"\x1B[1;2R" => F(3); SHIFT); insert!(b"\x1BOR" => F(3)); insert!(b"\x1B[1;5S" => F(4); CTRL); insert!(b"\x1B[1;3S" => F(4); ALT); insert!(b"\x1B[1;6S" => F(4); LOGO); insert!(b"\x1B[1;2S" => F(4); SHIFT); insert!(b"\x1BOS" => F(4)); insert!(b"\x1B[15;5~" => F(5); CTRL); insert!(b"\x1B[15;3~" => F(5); ALT); insert!(b"\x1B[15;6~" => F(5); LOGO); insert!(b"\x1B[15;2~" => F(5); SHIFT); insert!(b"\x1B[15~" => F(5)); insert!(b"\x1B[17;5~" => F(6); CTRL); insert!(b"\x1B[17;3~" => F(6); ALT); insert!(b"\x1B[17;6~" => F(6); LOGO); insert!(b"\x1B[17;2~" => F(6); SHIFT); insert!(b"\x1B[17~" => F(6)); insert!(b"\x1B[18;5~" => F(7); CTRL); insert!(b"\x1B[18;3~" => F(7); ALT); insert!(b"\x1B[18;6~" => F(7); LOGO); insert!(b"\x1B[18;2~" => F(7); SHIFT); insert!(b"\x1B[18~" => F(7)); insert!(b"\x1B[19;5~" => F(8); CTRL); insert!(b"\x1B[19;3~" => F(8); ALT); insert!(b"\x1B[19;6~" => F(8); LOGO); insert!(b"\x1B[19;2~" => F(8); SHIFT); insert!(b"\x1B[19~" => F(8)); insert!(b"\x1B[20;5~" => F(9); CTRL); insert!(b"\x1B[20;3~" => F(9); ALT); insert!(b"\x1B[20;6~" => F(9); LOGO); insert!(b"\x1B[20;2~" => F(9); SHIFT); insert!(b"\x1B[20~" => F(9)); insert!(b"\x1B[21;5~" => F(10); CTRL); insert!(b"\x1B[21;3~" => F(10); ALT); insert!(b"\x1B[21;6~" => F(10); LOGO); insert!(b"\x1B[21;2~" => F(10); SHIFT); insert!(b"\x1B[21~" => F(10)); insert!(b"\x1B[23;5~" => F(11); CTRL); insert!(b"\x1B[23;3~" => F(11); ALT); insert!(b"\x1B[23;6~" => F(11); LOGO); insert!(b"\x1B[23;2~" => F(11); SHIFT); insert!(b"\x1B[23~" => F(11)); insert!(b"\x1B[24;5~" => F(12); CTRL); insert!(b"\x1B[24;3~" => F(12); ALT); insert!(b"\x1B[24;6~" => F(12); LOGO); insert!(b"\x1B[24;2~" => F(12); SHIFT); insert!(b"\x1B[24~" => F(12)); insert!(b"\x1B[1;2P" => F(13)); insert!(b"\x1B[1;2Q" => F(14)); insert!(b"\x1B[1;2R" => F(15)); insert!(b"\x1B[1;2S" => F(16)); insert!(b"\x1B[15;2~" => F(17)); insert!(b"\x1B[17;2~" => F(18)); insert!(b"\x1B[18;2~" => F(19)); insert!(b"\x1B[19;2~" => F(20)); insert!(b"\x1B[20;2~" => F(21)); insert!(b"\x1B[21;2~" => F(22)); insert!(b"\x1B[23;2~" => F(23)); insert!(b"\x1B[24;2~" => F(24)); insert!(b"\x1B[1;5P" => F(25)); insert!(b"\x1B[1;5Q" => F(26)); insert!(b"\x1B[1;5R" => F(27)); insert!(b"\x1B[1;5S" => F(28)); insert!(b"\x1B[15;5~" => F(29)); insert!(b"\x1B[17;5~" => F(30)); insert!(b"\x1B[18;5~" => F(31)); insert!(b"\x1B[19;5~" => F(32)); insert!(b"\x1B[20;5~" => F(33)); insert!(b"\x1B[21;5~" => F(34)); insert!(b"\x1B[23;5~" => F(35)); } Keys(map) } pub fn bind<T: Into<Vec<u8>>>(&mut self, value: T, key: Key) -> &mut Self { let value = value.into(); if!value.is_empty() { self.0.entry(value.len()).or_insert(HashMap::default()) .insert(value, key); } self } pub fn unbind<T: AsRef<[u8]>>(&mut self, value: T) -> &mut Self { let value = value.as_ref(); if let Some(map) = self.0.get_mut(&value.len()) { map.remove(value); } self } pub fn find<'a>(&self, mut input: &'a [u8]) -> (&'a [u8], Option<Key>) { // Check if it's a defined key. for (&length, map) in self.0.iter().rev() { if length > input.len() { continue; } if let Some(key) = map.get(&input[..length]) { return (&input[length..], Some(*key)); } } // Check if it's a single escape press. if input == &[0x1B] { return (&input[1..], Some(Key { modifier: Modifier::empty(), value: Escape, })); } let mut mods = Modifier::empty(); if input[0] == 0x1B { mods.insert(Modifier::ALT); input = &input[1..]; } // Check if it's a control character. if input[0] & 0b011_00000 == 0 { return (&input[1..], Some(Key { modifier: mods | Modifier::CTRL, value: Char((input[0] | 0b010_00000) as char), })); } // Check if it's a unicode character. const WIDTH: [u8; 256] = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7F 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, 0, 0, 0, 0, 0, 0, // 0x9F 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, 0, 0, 0, 0, 0, 0, // 0xBF 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF ]; let length = WIDTH[input[0] as usize] as usize; if length >= input.len() { if let Ok(string) = str::from_utf8(&input[..length]) { return (&input[length..], Some(Key { modifier: mods, value: Char(string.chars().next().unwrap()) })); } } (&input[1..], None) } }
y {
identifier_name
keys.rs
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. use std::collections::{BTreeMap, HashMap}; use std::hash::BuildHasherDefault; use fnv::FnvHasher; use std::str; use info::{self, capability as cap}; #[derive(Debug)] pub struct Keys(BTreeMap<usize, HashMap<Vec<u8>, Key, BuildHasherDefault<FnvHasher>>>); #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Key { pub modifier: Modifier, pub value: Value, } bitflags! { pub struct Modifier: u8 { const NONE = 0; const ALT = 1 << 0; const CTRL = 1 << 1; const LOGO = 1 << 2; const SHIFT = 1 << 3; } } impl Default for Modifier { fn default() -> Self { Modifier::empty() } } #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum Value { Escape, Enter, Down, Up, Left, Right, PageUp, PageDown, BackSpace, BackTab, Tab, Delete, Insert, Home, End, Begin, F(u8), Char(char), } pub use self::Value::*; impl Keys { pub fn new(info: &info::Database) -> Self { let mut map = BTreeMap::default(); // Load terminfo bindings. { macro_rules! insert { ($name:ident => $($key:tt)*) => ( if let Some(cap) = info.get::<cap::$name>() { let value: &[u8] = cap.as_ref(); map.entry(value.len()).or_insert(HashMap::default()) .entry(value.into()).or_insert(Key { modifier: Modifier::empty(), value: Value::$($key)* }); } ) } insert!(KeyEnter => Enter); insert!(CarriageReturn => Enter); insert!(KeyDown => Down); insert!(KeyUp => Up); insert!(KeyLeft => Left); insert!(KeyRight => Right); insert!(KeyNPage => PageDown); insert!(KeyPPage => PageUp); insert!(KeyBackspace => BackSpace); insert!(KeyBTab => BackTab); insert!(Tab => Tab); insert!(KeyF1 => F(1)); insert!(KeyF2 => F(2)); insert!(KeyF3 => F(3)); insert!(KeyF4 => F(4)); insert!(KeyF5 => F(5)); insert!(KeyF6 => F(6)); insert!(KeyF7 => F(7)); insert!(KeyF8 => F(8)); insert!(KeyF9 => F(9)); insert!(KeyF10 => F(10)); insert!(KeyF11 => F(11)); insert!(KeyF12 => F(12)); insert!(KeyF13 => F(13)); insert!(KeyF14 => F(14)); insert!(KeyF15 => F(15)); insert!(KeyF16 => F(16)); insert!(KeyF17 => F(17)); insert!(KeyF18 => F(18)); insert!(KeyF19 => F(19)); insert!(KeyF20 => F(20)); insert!(KeyF21 => F(21)); insert!(KeyF22 => F(22)); insert!(KeyF23 => F(23)); insert!(KeyF24 => F(24)); insert!(KeyF25 => F(25)); insert!(KeyF26 => F(26)); insert!(KeyF27 => F(27)); insert!(KeyF28 => F(28)); insert!(KeyF29 => F(29)); insert!(KeyF30 => F(30)); insert!(KeyF31 => F(31)); insert!(KeyF32 => F(32)); insert!(KeyF33 => F(33)); insert!(KeyF34 => F(34)); insert!(KeyF35 => F(35)); insert!(KeyF36 => F(36)); insert!(KeyF37 => F(37)); insert!(KeyF38 => F(38)); insert!(KeyF39 => F(39)); insert!(KeyF40 => F(40)); insert!(KeyF41 => F(41)); insert!(KeyF42 => F(42)); insert!(KeyF43 => F(43)); insert!(KeyF44 => F(44)); insert!(KeyF45 => F(45)); insert!(KeyF46 => F(46)); insert!(KeyF47 => F(47)); insert!(KeyF48 => F(48)); insert!(KeyF49 => F(49)); insert!(KeyF50 => F(50)); insert!(KeyF51 => F(51)); insert!(KeyF52 => F(52)); insert!(KeyF53 => F(53)); insert!(KeyF54 => F(54)); insert!(KeyF55 => F(55)); insert!(KeyF56 => F(56)); insert!(KeyF57 => F(57)); insert!(KeyF58 => F(58)); insert!(KeyF59 => F(59)); insert!(KeyF60 => F(60)); insert!(KeyF61 => F(61)); insert!(KeyF62 => F(62)); insert!(KeyF63 => F(63)); } // Load default bindings. { macro_rules! insert { ($string:expr => $value:expr) => ( insert!($string => $value; NONE); ); ($string:expr => $value:expr; $($mods:ident)|+) => ( map.entry($string.len()).or_insert(HashMap::default()) .entry($string.to_vec()).or_insert(Key { modifier: $(Modifier::$mods)|+, value: $value, }); ); } insert!(b"\x1B[Z" => Tab; SHIFT); insert!(b"\x1B\x7F" => BackSpace; ALT); insert!(b"\x7F" => BackSpace); insert!(b"\x1B\r\n" => Enter; ALT); insert!(b"\x1B\r" => Enter; ALT); insert!(b"\x1B\n" => Enter; ALT); insert!(b"\r\n" => Enter); insert!(b"\r" => Enter); insert!(b"\n" => Enter); insert!(b"\x1B[3;5~" => Delete; CTRL); insert!(b"\x1B[3;2~" => Delete; SHIFT); insert!(b"\x1B[3~" => Delete); insert!(b"\x1B[2;5~" => Insert; CTRL); insert!(b"\x1B[2;2~" => Insert; SHIFT); insert!(b"\x1B[2~" => Insert); insert!(b"\x1B[1;2H" => Home; SHIFT); insert!(b"\x1B[H" => Home); insert!(b"\x1B[1;5F" => End; CTRL); insert!(b"\x1B[1;2F" => End; SHIFT); insert!(b"\x1B[8~" => End); insert!(b"\x1B[E" => Begin); insert!(b"\x1B[5;5~" => PageUp; CTRL); insert!(b"\x1B[5;2~" => PageUp; SHIFT); insert!(b"\x1B[5~" => PageUp); insert!(b"\x1B[6;5~" => PageDown; CTRL); insert!(b"\x1B[6;2~" => PageDown; SHIFT); insert!(b"\x1B[6~" => PageDown); insert!(b"\x1B[1;5A" => Up; CTRL); insert!(b"\x1B[1;3A" => Up; ALT); insert!(b"\x1B[1;2A" => Up; SHIFT); insert!(b"\x1BBOA" => Up); insert!(b"\x1B[1;5B" => Down; CTRL); insert!(b"\x1B[1;3B" => Down; ALT); insert!(b"\x1B[1;2B" => Down; SHIFT); insert!(b"\x1BBOB" => Down); insert!(b"\x1B[1;5C" => Right; CTRL); insert!(b"\x1B[1;3C" => Right; ALT); insert!(b"\x1B[1;2C" => Right; SHIFT); insert!(b"\x1BBOC" => Right); insert!(b"\x1B[1;5D" => Left; CTRL); insert!(b"\x1B[1;3D" => Left; ALT); insert!(b"\x1B[1;2D" => Left; SHIFT); insert!(b"\x1BBOD" => Left); insert!(b"\x1B[1;5P" => F(1); CTRL); insert!(b"\x1B[1;3P" => F(1); ALT); insert!(b"\x1B[1;6P" => F(1); LOGO); insert!(b"\x1B[1;2P" => F(1); SHIFT); insert!(b"\x1BOP" => F(1)); insert!(b"\x1B[1;5Q" => F(2); CTRL); insert!(b"\x1B[1;3Q" => F(2); ALT); insert!(b"\x1B[1;6Q" => F(2); LOGO); insert!(b"\x1B[1;2Q" => F(2); SHIFT); insert!(b"\x1BOQ" => F(2)); insert!(b"\x1B[1;5R" => F(3); CTRL); insert!(b"\x1B[1;3R" => F(3); ALT); insert!(b"\x1B[1;6R" => F(3); LOGO); insert!(b"\x1B[1;2R" => F(3); SHIFT); insert!(b"\x1BOR" => F(3)); insert!(b"\x1B[1;5S" => F(4); CTRL); insert!(b"\x1B[1;3S" => F(4); ALT); insert!(b"\x1B[1;6S" => F(4); LOGO); insert!(b"\x1B[1;2S" => F(4); SHIFT); insert!(b"\x1BOS" => F(4)); insert!(b"\x1B[15;5~" => F(5); CTRL); insert!(b"\x1B[15;3~" => F(5); ALT); insert!(b"\x1B[15;6~" => F(5); LOGO); insert!(b"\x1B[15;2~" => F(5); SHIFT); insert!(b"\x1B[15~" => F(5)); insert!(b"\x1B[17;5~" => F(6); CTRL); insert!(b"\x1B[17;3~" => F(6); ALT); insert!(b"\x1B[17;6~" => F(6); LOGO); insert!(b"\x1B[17;2~" => F(6); SHIFT); insert!(b"\x1B[17~" => F(6)); insert!(b"\x1B[18;5~" => F(7); CTRL); insert!(b"\x1B[18;3~" => F(7); ALT); insert!(b"\x1B[18;6~" => F(7); LOGO); insert!(b"\x1B[18;2~" => F(7); SHIFT); insert!(b"\x1B[18~" => F(7)); insert!(b"\x1B[19;5~" => F(8); CTRL); insert!(b"\x1B[19;3~" => F(8); ALT); insert!(b"\x1B[19;6~" => F(8); LOGO); insert!(b"\x1B[19;2~" => F(8); SHIFT); insert!(b"\x1B[19~" => F(8)); insert!(b"\x1B[20;5~" => F(9); CTRL); insert!(b"\x1B[20;3~" => F(9); ALT); insert!(b"\x1B[20;6~" => F(9); LOGO); insert!(b"\x1B[20;2~" => F(9); SHIFT); insert!(b"\x1B[20~" => F(9)); insert!(b"\x1B[21;5~" => F(10); CTRL); insert!(b"\x1B[21;3~" => F(10); ALT); insert!(b"\x1B[21;6~" => F(10); LOGO); insert!(b"\x1B[21;2~" => F(10); SHIFT); insert!(b"\x1B[21~" => F(10)); insert!(b"\x1B[23;5~" => F(11); CTRL); insert!(b"\x1B[23;3~" => F(11); ALT); insert!(b"\x1B[23;6~" => F(11); LOGO); insert!(b"\x1B[23;2~" => F(11); SHIFT); insert!(b"\x1B[23~" => F(11)); insert!(b"\x1B[24;5~" => F(12); CTRL); insert!(b"\x1B[24;3~" => F(12); ALT); insert!(b"\x1B[24;6~" => F(12); LOGO); insert!(b"\x1B[24;2~" => F(12); SHIFT); insert!(b"\x1B[24~" => F(12)); insert!(b"\x1B[1;2P" => F(13)); insert!(b"\x1B[1;2Q" => F(14)); insert!(b"\x1B[1;2R" => F(15)); insert!(b"\x1B[1;2S" => F(16)); insert!(b"\x1B[15;2~" => F(17)); insert!(b"\x1B[17;2~" => F(18)); insert!(b"\x1B[18;2~" => F(19)); insert!(b"\x1B[19;2~" => F(20)); insert!(b"\x1B[20;2~" => F(21)); insert!(b"\x1B[21;2~" => F(22)); insert!(b"\x1B[23;2~" => F(23)); insert!(b"\x1B[24;2~" => F(24)); insert!(b"\x1B[1;5P" => F(25)); insert!(b"\x1B[1;5Q" => F(26)); insert!(b"\x1B[1;5R" => F(27)); insert!(b"\x1B[1;5S" => F(28)); insert!(b"\x1B[15;5~" => F(29)); insert!(b"\x1B[17;5~" => F(30)); insert!(b"\x1B[18;5~" => F(31)); insert!(b"\x1B[19;5~" => F(32)); insert!(b"\x1B[20;5~" => F(33)); insert!(b"\x1B[21;5~" => F(34)); insert!(b"\x1B[23;5~" => F(35)); } Keys(map) } pub fn bind<T: Into<Vec<u8>>>(&mut self, value: T, key: Key) -> &mut Self { let value = value.into(); if!value.is_empty() { self.0.entry(value.len()).or_insert(HashMap::default()) .insert(value, key); } self } pub fn unbind<T: AsRef<[u8]>>(&mut self, value: T) -> &mut Self { let value = value.as_ref(); if let Some(map) = self.0.get_mut(&value.len()) { map.remove(value); } self } pub fn find<'a>(&self, mut input: &'a [u8]) -> (&'a [u8], Option<Key>) { // Check if it's a defined key. for (&length, map) in self.0.iter().rev() { if length > input.len() { continue; } if let Some(key) = map.get(&input[..length]) { return (&input[length..], Some(*key)); } }
})); } let mut mods = Modifier::empty(); if input[0] == 0x1B { mods.insert(Modifier::ALT); input = &input[1..]; } // Check if it's a control character. if input[0] & 0b011_00000 == 0 { return (&input[1..], Some(Key { modifier: mods | Modifier::CTRL, value: Char((input[0] | 0b010_00000) as char), })); } // Check if it's a unicode character. const WIDTH: [u8; 256] = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7F 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, 0, 0, 0, 0, 0, 0, // 0x9F 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, 0, 0, 0, 0, 0, 0, // 0xBF 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF ]; let length = WIDTH[input[0] as usize] as usize; if length >= input.len() { if let Ok(string) = str::from_utf8(&input[..length]) { return (&input[length..], Some(Key { modifier: mods, value: Char(string.chars().next().unwrap()) })); } } (&input[1..], None) } }
// Check if it's a single escape press. if input == &[0x1B] { return (&input[1..], Some(Key { modifier: Modifier::empty(), value: Escape,
random_line_split
lib.rs
//! This crate provides an implementation of Chan-Vese level-sets //! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/) //! by T. Chan and L. Vese. //! It is a port of the Python implementation by Kevin Keraudren on //! [Github](https://github.com/kevin-keraudren/chanvese) //! and of the Matlab implementation by [Shawn Lankton](http://www.shawnlankton.com). //! //! # Examples //! To use the functions inside module `chanvese::utils` you need to //! compile this crate with the feature image-utils. //! //! ``` //! extern crate image; //! extern crate rand; //! extern crate chanvese; //! //! use std::f64; //! use std::fs::File; //! use image::ImageBuffer; //! use rand::distributions::{Sample, Range}; //! use chanvese::{FloatGrid, BoolGrid, chanvese}; //! //! use chanvese::utils; //! //! fn main() { //! // create an input image (blurred and noisy ellipses) //! let img = { //! let mut img = ImageBuffer::new(256, 128); //! for (x, y, pixel) in img.enumerate_pixels_mut() { //! if (x-100)*(x-100)+(y-70)*(y-70) <= 35*35 { //! *pixel = image::Luma([200u8]); //! } //! if (x-128)*(x-128)/2+(y-50)*(y-50) <= 30*30 { //! *pixel = image::Luma([150u8]); //! } //! } //! img = image::imageops::blur(&img, 5.); //! let mut noiserange = Range::new(0.0f32, 30.); //! let mut rng = rand::thread_rng(); //! for (_, _, pixel) in img.enumerate_pixels_mut() { //! *pixel = image::Luma([pixel.data[0] + noiserange.sample(&mut rng) as u8]); //! } //! let ref mut imgout = File::create("image.png").unwrap(); //! image::ImageLuma8(img.clone()).save(imgout, image::PNG).unwrap(); //! let mut result = FloatGrid::new(256, 128); //! //! for (x, y, pixel) in img.enumerate_pixels() { //! result.set(x as usize, y as usize, pixel.data[0] as f64); //! } //! result //! }; //! //! // create a rough mask //! let mask = { //! let mut result = BoolGrid::new(img.width(), img.height()); //! for (x, y, value) in result.iter_mut() { //! if (x >= 65 && x <= 180) && (y >= 20 && y <= 100) { //! *value = true; //! } //! } //! result //! }; //! utils::save_boolgrid(&mask, "mask.png"); //! //! // level-set segmentation by Chan-Vese //! let (seg, phi, _) = chanvese(&img, &mask, 500, 1.0, 0); //! utils::save_boolgrid(&seg, "out.png"); //! utils::save_floatgrid(&phi, "phi.png"); //! } //! ``` extern crate distance_transform; use distance_transform::dt2d; use std::f64; pub use distance_transform::{FloatGrid, BoolGrid}; #[cfg(feature = "image-utils")] pub mod utils; #[cfg(feature = "image-utils")] mod viridis; /// Runs the chanvese algorithm /// /// Returns the resulting mask (`true` = foreground, `false` = background), /// the level-set function and the number of iterations. /// /// # Arguments /// /// * `img` - the input image /// * `init_mask` - in initial mask (`true` = foreground, `false` = background) /// * `max_its` - number of iterations /// * `alpha` - weight of smoothing term (default: 0.2) /// * `thresh` - number of different pixels in masks of successive steps (default: 0) pub fn chanvese(img: &FloatGrid, init_mask: &BoolGrid, max_its: u32, alpha: f64, thresh: u32) -> (BoolGrid, FloatGrid, u32) { // create a signed distance map (SDF) from mask let mut phi = mask2phi(init_mask); // main loop let mut its = 0u32; let mut stop = false; let mut prev_mask = init_mask.clone(); let mut c = 0u32; while its < max_its &&!stop { // get the curve's narrow band let idx = { let mut result = Vec::new(); for (x, y, &val) in phi.iter() { if val >= -1.2 && val <= 1.2 { result.push((x, y)); } } result }; if idx.len() > 0 { // intermediate output if its % 50 == 0 { println!("iteration: {}", its); } // find interior and exterior mean let (upts, vpts) = { let mut res1 = Vec::new(); let mut res2 = Vec::new(); for (x, y, value) in phi.iter() { if *value <= 0. { res1.push((x, y)); } else { res2.push((x, y)); } } (res1, res2) }; let u = upts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (upts.len() as f64 + f64::EPSILON); let v = vpts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (vpts.len() as f64 + f64::EPSILON); // force from image information let f: Vec<f64> = idx.iter().map(|&(x, y)| { (*img.get(x, y).unwrap() - u)*(*img.get(x, y).unwrap() - u) -(*img.get(x, y).unwrap() - v)*(*img.get(x, y).unwrap() - v) }).collect(); // force from curvature penalty let curvature = get_curvature(&phi, &idx); // gradient descent to minimize energy let dphidt: Vec<f64> = { let maxabs = f.iter().fold(0.0f64, |acc, &x| { acc.max(x.abs()) }); f.iter().zip(curvature.iter()).map(|(f, c)| { f/maxabs + alpha*c }).collect() }; // maintain the CFL condition let dt = 0.45/(dphidt.iter().fold(0.0f64, |acc, &x| acc.max(x.abs())) + f64::EPSILON); // evolve the curve for i in 0..idx.len() { let (x, y) = idx[i]; let val = *phi.get(x, y).unwrap(); phi.set(x, y, val + dt*dphidt[i]); } // keep SDF smooth phi = sussman(&phi, &0.5); let new_mask = { let mut result = BoolGrid::new(phi.width(), phi.height()); for (x, y, value) in phi.iter() { result.set(x, y, *value <= 0.); } result }; c = convergence(&prev_mask, &new_mask, thresh, c); if c <= 5 { its += 1; prev_mask = new_mask.clone(); } else { stop = true; } } else { break; } } // make mask from SDF, get mask from levelset let seg = { let mut res = BoolGrid::new(phi.width(), phi.height()); for (x, y, &value) in phi.iter() { res.set(x, y, value <= 0.); } res }; (seg, phi, its) } fn bwdist(a: &BoolGrid) -> FloatGrid { let mut res = dt2d(&a); for (_, _, value) in res.iter_mut() { let newval = value.sqrt(); *value = newval; } res } // Converts a mask to a SDF fn mask2phi(init_a: &BoolGrid) -> FloatGrid { let inv_init_a = { let mut result = init_a.clone(); for (_, _, value) in result.iter_mut() { *value =!*value; } result }; let phi = { let dist_a = bwdist(&init_a); let dist_inv_a = bwdist(&inv_init_a); let mut result = FloatGrid::new(init_a.width(), init_a.height()); for (x, y, value) in result.iter_mut() { *value = dist_a.get(x, y).unwrap() - dist_inv_a.get(x, y).unwrap() + if *init_a.get(x, y).unwrap() {1.} else {0.} - 0.5; } result }; phi } // Compute curvature along SDF fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> { // get central derivatives of SDF at x,y let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = { let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy) : (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) = ( Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len())); for &(x, y) in idx.iter() { let left = if x > 0 { x - 1 } else { 0 }; let right = if x < phi.width() - 1 { x + 1 } else { phi.width() - 1 }; let up = if y > 0 { y - 1 } else { 0 }; let down = if y < phi.height() - 1 { y + 1 } else { phi.height() - 1 }; res_x.push(-*phi.get(left, y).unwrap() + *phi.get(right, y).unwrap()); res_y.push(-*phi.get(x, down).unwrap() + *phi.get(x, up).unwrap()); res_xx.push( *phi.get(left, y).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(right, y).unwrap()); res_yy.push( *phi.get(x, up).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(x, down).unwrap()); res_xy.push(0.25*( -*phi.get(left, down).unwrap() - *phi.get(right, up).unwrap() +*phi.get(right, down).unwrap() + *phi.get(left, up).unwrap() )); } (res_x, res_y, res_xx, res_yy, res_xy) }; let phi_x2: Vec<f64> = phi_x.iter().map(|x| x*x).collect(); let phi_y2: Vec<f64> = phi_y.iter().map(|x| x*x).collect(); // compute curvature (Kappa) let curvature: Vec<f64> = (0..idx.len()).map(|i| { ((phi_x2[i]*phi_yy[i] + phi_y2[i]*phi_xx[i] - 2.*phi_x[i]*phi_y[i]*phi_xy[i])/ (phi_x2[i] + phi_y2[i] + f64::EPSILON).powf(1.5))*(phi_x2[i] + phi_y2[i]).powf(0.5) }).collect(); curvature } // Level set re-initialization by the sussman method fn sussman(grid: &FloatGrid, dt: &f64) -> FloatGrid { // forward/backward differences let (a, b, c, d) = { let mut a_res = FloatGrid::new(grid.width(), grid.height()); let mut b_res = FloatGrid::new(grid.width(), grid.height()); let mut c_res = FloatGrid::new(grid.width(), grid.height()); let mut d_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { a_res.set(x, y, grid.get(x, y).unwrap() - grid.get((x + grid.width() - 1) % grid.width(), y).unwrap()); b_res.set(x, y, grid.get((x + 1) % grid.width(), y).unwrap() - grid.get(x, y).unwrap()); c_res.set(x, y, grid.get(x, y).unwrap() - grid.get(x, (y + 1) % grid.height()).unwrap()); d_res.set(x, y, grid.get(x, (y + grid.height() - 1) % grid.height()).unwrap() - grid.get(x, y).unwrap()); } } (a_res, b_res, c_res, d_res) }; let (a_p, a_n, b_p, b_n, c_p, c_n, d_p, d_n) = { let mut a_p_res = FloatGrid::new(grid.width(), grid.height()); let mut a_n_res = FloatGrid::new(grid.width(), grid.height()); let mut b_p_res = FloatGrid::new(grid.width(), grid.height()); let mut b_n_res = FloatGrid::new(grid.width(), grid.height()); let mut c_p_res = FloatGrid::new(grid.width(), grid.height()); let mut c_n_res = FloatGrid::new(grid.width(), grid.height()); let mut d_p_res = FloatGrid::new(grid.width(), grid.height()); let mut d_n_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { let a_p_dval = *a.get(x, y).unwrap(); let a_n_dval = *a.get(x, y).unwrap(); let b_p_dval = *b.get(x, y).unwrap(); let b_n_dval = *b.get(x, y).unwrap(); let c_p_dval = *c.get(x, y).unwrap(); let c_n_dval = *c.get(x, y).unwrap(); let d_p_dval = *d.get(x, y).unwrap(); let d_n_dval = *d.get(x, y).unwrap(); a_p_res.set(x, y, if a_p_dval >= 0.0 { a_p_dval } else { 0.0 }); a_n_res.set(x, y, if a_n_dval <= 0.0 { a_n_dval } else { 0.0 }); b_p_res.set(x, y, if b_p_dval >= 0.0 { b_p_dval } else { 0.0 }); b_n_res.set(x, y, if b_n_dval <= 0.0 { b_n_dval } else { 0.0 }); c_p_res.set(x, y, if c_p_dval >= 0.0 { c_p_dval } else { 0.0 }); c_n_res.set(x, y, if c_n_dval <= 0.0 { c_n_dval } else { 0.0 }); d_p_res.set(x, y, if d_p_dval >= 0.0 { d_p_dval } else { 0.0 }); d_n_res.set(x, y, if d_n_dval <= 0.0 { d_n_dval } else { 0.0 }); } } (a_p_res, a_n_res, b_p_res, b_n_res, c_p_res, c_n_res, d_p_res, d_n_res) }; let mut d_d = FloatGrid::new(grid.width(), grid.height()); let (d_neg_ind, d_pos_ind) = { let mut res = (Vec::new(), Vec::new()); for (x, y, &value) in grid.iter() { if value < 0.0 { res.0.push((x, y)); } else if value > 0.0 { res.1.push((x,y)); } } res }; for index in d_pos_ind { let mut ap = *a_p.get(index.0, index.1).unwrap(); let mut bn = *b_n.get(index.0, index.1).unwrap(); let mut cp = *c_p.get(index.0, index.1).unwrap(); let mut dn = *d_n.get(index.0, index.1).unwrap(); ap *= ap; bn *= bn; cp *= cp; dn *= dn; d_d.set(index.0, index.1, (ap.max(bn) + cp.max(dn)).sqrt() - 1.); } for index in d_neg_ind { let mut an = *a_n.get(index.0, index.1).unwrap(); let mut bp = *b_p.get(index.0, index.1).unwrap(); let mut cn = *c_n.get(index.0, index.1).unwrap(); let mut dp = *d_p.get(index.0, index.1).unwrap(); an *= an; bp *= bp; cn *= cn; dp *= dp; d_d.set(index.0, index.1, (an.max(bp) + cn.max(dp)).sqrt() - 1.); } let ss_d = sussman_sign(&grid); let mut res = FloatGrid::new(grid.width(), grid.height()); for (x, y, value) in res.iter_mut() { let dval = grid.get(x, y).unwrap(); let ss_dval = ss_d.get(x, y).unwrap(); let d_dval = d_d.get(x, y).unwrap(); *value = dval - dt*ss_dval*d_dval; } res } fn sussman_sign(d: &FloatGrid) -> FloatGrid { let mut res = FloatGrid::new(d.width(), d.height()); for (x, y, value) in res.iter_mut() { let v = d.get(x, y).unwrap(); *value = v/(v*v + 1.).sqrt(); } res } // Convergence test fn convergence(p_mask: &BoolGrid, n_mask: &BoolGrid, thresh: u32, c: u32) -> u32 { let n_diff = p_mask.iter().zip(n_mask.iter()).fold(0u32, |acc, ((_,_,p),(_,_,n))| { acc + if *p == *n { 1 } else { 0 } }); if n_diff < thresh
else { 0 } }
{ c + 1 }
conditional_block
lib.rs
//! This crate provides an implementation of Chan-Vese level-sets //! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/) //! by T. Chan and L. Vese. //! It is a port of the Python implementation by Kevin Keraudren on //! [Github](https://github.com/kevin-keraudren/chanvese) //! and of the Matlab implementation by [Shawn Lankton](http://www.shawnlankton.com). //! //! # Examples //! To use the functions inside module `chanvese::utils` you need to //! compile this crate with the feature image-utils. //! //! ``` //! extern crate image; //! extern crate rand; //! extern crate chanvese; //! //! use std::f64; //! use std::fs::File; //! use image::ImageBuffer; //! use rand::distributions::{Sample, Range}; //! use chanvese::{FloatGrid, BoolGrid, chanvese}; //! //! use chanvese::utils; //! //! fn main() { //! // create an input image (blurred and noisy ellipses) //! let img = { //! let mut img = ImageBuffer::new(256, 128); //! for (x, y, pixel) in img.enumerate_pixels_mut() { //! if (x-100)*(x-100)+(y-70)*(y-70) <= 35*35 { //! *pixel = image::Luma([200u8]); //! } //! if (x-128)*(x-128)/2+(y-50)*(y-50) <= 30*30 { //! *pixel = image::Luma([150u8]); //! } //! } //! img = image::imageops::blur(&img, 5.); //! let mut noiserange = Range::new(0.0f32, 30.); //! let mut rng = rand::thread_rng(); //! for (_, _, pixel) in img.enumerate_pixels_mut() { //! *pixel = image::Luma([pixel.data[0] + noiserange.sample(&mut rng) as u8]); //! } //! let ref mut imgout = File::create("image.png").unwrap(); //! image::ImageLuma8(img.clone()).save(imgout, image::PNG).unwrap(); //! let mut result = FloatGrid::new(256, 128); //! //! for (x, y, pixel) in img.enumerate_pixels() { //! result.set(x as usize, y as usize, pixel.data[0] as f64); //! } //! result //! }; //! //! // create a rough mask //! let mask = { //! let mut result = BoolGrid::new(img.width(), img.height()); //! for (x, y, value) in result.iter_mut() { //! if (x >= 65 && x <= 180) && (y >= 20 && y <= 100) { //! *value = true; //! } //! } //! result //! }; //! utils::save_boolgrid(&mask, "mask.png"); //! //! // level-set segmentation by Chan-Vese //! let (seg, phi, _) = chanvese(&img, &mask, 500, 1.0, 0); //! utils::save_boolgrid(&seg, "out.png"); //! utils::save_floatgrid(&phi, "phi.png"); //! } //! ``` extern crate distance_transform; use distance_transform::dt2d; use std::f64; pub use distance_transform::{FloatGrid, BoolGrid}; #[cfg(feature = "image-utils")] pub mod utils; #[cfg(feature = "image-utils")] mod viridis; /// Runs the chanvese algorithm /// /// Returns the resulting mask (`true` = foreground, `false` = background), /// the level-set function and the number of iterations. /// /// # Arguments /// /// * `img` - the input image /// * `init_mask` - in initial mask (`true` = foreground, `false` = background) /// * `max_its` - number of iterations /// * `alpha` - weight of smoothing term (default: 0.2) /// * `thresh` - number of different pixels in masks of successive steps (default: 0) pub fn chanvese(img: &FloatGrid, init_mask: &BoolGrid, max_its: u32, alpha: f64, thresh: u32) -> (BoolGrid, FloatGrid, u32) { // create a signed distance map (SDF) from mask let mut phi = mask2phi(init_mask); // main loop let mut its = 0u32; let mut stop = false; let mut prev_mask = init_mask.clone(); let mut c = 0u32; while its < max_its &&!stop { // get the curve's narrow band let idx = { let mut result = Vec::new(); for (x, y, &val) in phi.iter() { if val >= -1.2 && val <= 1.2 { result.push((x, y)); } } result }; if idx.len() > 0 { // intermediate output if its % 50 == 0 { println!("iteration: {}", its); } // find interior and exterior mean let (upts, vpts) = { let mut res1 = Vec::new(); let mut res2 = Vec::new(); for (x, y, value) in phi.iter() { if *value <= 0. { res1.push((x, y)); } else { res2.push((x, y)); } } (res1, res2) }; let u = upts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (upts.len() as f64 + f64::EPSILON); let v = vpts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (vpts.len() as f64 + f64::EPSILON); // force from image information let f: Vec<f64> = idx.iter().map(|&(x, y)| { (*img.get(x, y).unwrap() - u)*(*img.get(x, y).unwrap() - u) -(*img.get(x, y).unwrap() - v)*(*img.get(x, y).unwrap() - v) }).collect(); // force from curvature penalty let curvature = get_curvature(&phi, &idx); // gradient descent to minimize energy let dphidt: Vec<f64> = { let maxabs = f.iter().fold(0.0f64, |acc, &x| { acc.max(x.abs()) }); f.iter().zip(curvature.iter()).map(|(f, c)| { f/maxabs + alpha*c }).collect() }; // maintain the CFL condition let dt = 0.45/(dphidt.iter().fold(0.0f64, |acc, &x| acc.max(x.abs())) + f64::EPSILON); // evolve the curve for i in 0..idx.len() { let (x, y) = idx[i]; let val = *phi.get(x, y).unwrap(); phi.set(x, y, val + dt*dphidt[i]); } // keep SDF smooth phi = sussman(&phi, &0.5); let new_mask = { let mut result = BoolGrid::new(phi.width(), phi.height()); for (x, y, value) in phi.iter() { result.set(x, y, *value <= 0.); } result }; c = convergence(&prev_mask, &new_mask, thresh, c); if c <= 5 { its += 1; prev_mask = new_mask.clone(); } else { stop = true; } } else { break; } } // make mask from SDF, get mask from levelset let seg = { let mut res = BoolGrid::new(phi.width(), phi.height()); for (x, y, &value) in phi.iter() { res.set(x, y, value <= 0.); } res }; (seg, phi, its) } fn bwdist(a: &BoolGrid) -> FloatGrid { let mut res = dt2d(&a); for (_, _, value) in res.iter_mut() { let newval = value.sqrt(); *value = newval; } res } // Converts a mask to a SDF fn mask2phi(init_a: &BoolGrid) -> FloatGrid
}; phi } // Compute curvature along SDF fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> { // get central derivatives of SDF at x,y let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = { let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy) : (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) = ( Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len())); for &(x, y) in idx.iter() { let left = if x > 0 { x - 1 } else { 0 }; let right = if x < phi.width() - 1 { x + 1 } else { phi.width() - 1 }; let up = if y > 0 { y - 1 } else { 0 }; let down = if y < phi.height() - 1 { y + 1 } else { phi.height() - 1 }; res_x.push(-*phi.get(left, y).unwrap() + *phi.get(right, y).unwrap()); res_y.push(-*phi.get(x, down).unwrap() + *phi.get(x, up).unwrap()); res_xx.push( *phi.get(left, y).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(right, y).unwrap()); res_yy.push( *phi.get(x, up).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(x, down).unwrap()); res_xy.push(0.25*( -*phi.get(left, down).unwrap() - *phi.get(right, up).unwrap() +*phi.get(right, down).unwrap() + *phi.get(left, up).unwrap() )); } (res_x, res_y, res_xx, res_yy, res_xy) }; let phi_x2: Vec<f64> = phi_x.iter().map(|x| x*x).collect(); let phi_y2: Vec<f64> = phi_y.iter().map(|x| x*x).collect(); // compute curvature (Kappa) let curvature: Vec<f64> = (0..idx.len()).map(|i| { ((phi_x2[i]*phi_yy[i] + phi_y2[i]*phi_xx[i] - 2.*phi_x[i]*phi_y[i]*phi_xy[i])/ (phi_x2[i] + phi_y2[i] + f64::EPSILON).powf(1.5))*(phi_x2[i] + phi_y2[i]).powf(0.5) }).collect(); curvature } // Level set re-initialization by the sussman method fn sussman(grid: &FloatGrid, dt: &f64) -> FloatGrid { // forward/backward differences let (a, b, c, d) = { let mut a_res = FloatGrid::new(grid.width(), grid.height()); let mut b_res = FloatGrid::new(grid.width(), grid.height()); let mut c_res = FloatGrid::new(grid.width(), grid.height()); let mut d_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { a_res.set(x, y, grid.get(x, y).unwrap() - grid.get((x + grid.width() - 1) % grid.width(), y).unwrap()); b_res.set(x, y, grid.get((x + 1) % grid.width(), y).unwrap() - grid.get(x, y).unwrap()); c_res.set(x, y, grid.get(x, y).unwrap() - grid.get(x, (y + 1) % grid.height()).unwrap()); d_res.set(x, y, grid.get(x, (y + grid.height() - 1) % grid.height()).unwrap() - grid.get(x, y).unwrap()); } } (a_res, b_res, c_res, d_res) }; let (a_p, a_n, b_p, b_n, c_p, c_n, d_p, d_n) = { let mut a_p_res = FloatGrid::new(grid.width(), grid.height()); let mut a_n_res = FloatGrid::new(grid.width(), grid.height()); let mut b_p_res = FloatGrid::new(grid.width(), grid.height()); let mut b_n_res = FloatGrid::new(grid.width(), grid.height()); let mut c_p_res = FloatGrid::new(grid.width(), grid.height()); let mut c_n_res = FloatGrid::new(grid.width(), grid.height()); let mut d_p_res = FloatGrid::new(grid.width(), grid.height()); let mut d_n_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { let a_p_dval = *a.get(x, y).unwrap(); let a_n_dval = *a.get(x, y).unwrap(); let b_p_dval = *b.get(x, y).unwrap(); let b_n_dval = *b.get(x, y).unwrap(); let c_p_dval = *c.get(x, y).unwrap(); let c_n_dval = *c.get(x, y).unwrap(); let d_p_dval = *d.get(x, y).unwrap(); let d_n_dval = *d.get(x, y).unwrap(); a_p_res.set(x, y, if a_p_dval >= 0.0 { a_p_dval } else { 0.0 }); a_n_res.set(x, y, if a_n_dval <= 0.0 { a_n_dval } else { 0.0 }); b_p_res.set(x, y, if b_p_dval >= 0.0 { b_p_dval } else { 0.0 }); b_n_res.set(x, y, if b_n_dval <= 0.0 { b_n_dval } else { 0.0 }); c_p_res.set(x, y, if c_p_dval >= 0.0 { c_p_dval } else { 0.0 }); c_n_res.set(x, y, if c_n_dval <= 0.0 { c_n_dval } else { 0.0 }); d_p_res.set(x, y, if d_p_dval >= 0.0 { d_p_dval } else { 0.0 }); d_n_res.set(x, y, if d_n_dval <= 0.0 { d_n_dval } else { 0.0 }); } } (a_p_res, a_n_res, b_p_res, b_n_res, c_p_res, c_n_res, d_p_res, d_n_res) }; let mut d_d = FloatGrid::new(grid.width(), grid.height()); let (d_neg_ind, d_pos_ind) = { let mut res = (Vec::new(), Vec::new()); for (x, y, &value) in grid.iter() { if value < 0.0 { res.0.push((x, y)); } else if value > 0.0 { res.1.push((x,y)); } } res }; for index in d_pos_ind { let mut ap = *a_p.get(index.0, index.1).unwrap(); let mut bn = *b_n.get(index.0, index.1).unwrap(); let mut cp = *c_p.get(index.0, index.1).unwrap(); let mut dn = *d_n.get(index.0, index.1).unwrap(); ap *= ap; bn *= bn; cp *= cp; dn *= dn; d_d.set(index.0, index.1, (ap.max(bn) + cp.max(dn)).sqrt() - 1.); } for index in d_neg_ind { let mut an = *a_n.get(index.0, index.1).unwrap(); let mut bp = *b_p.get(index.0, index.1).unwrap(); let mut cn = *c_n.get(index.0, index.1).unwrap(); let mut dp = *d_p.get(index.0, index.1).unwrap(); an *= an; bp *= bp; cn *= cn; dp *= dp; d_d.set(index.0, index.1, (an.max(bp) + cn.max(dp)).sqrt() - 1.); } let ss_d = sussman_sign(&grid); let mut res = FloatGrid::new(grid.width(), grid.height()); for (x, y, value) in res.iter_mut() { let dval = grid.get(x, y).unwrap(); let ss_dval = ss_d.get(x, y).unwrap(); let d_dval = d_d.get(x, y).unwrap(); *value = dval - dt*ss_dval*d_dval; } res } fn sussman_sign(d: &FloatGrid) -> FloatGrid { let mut res = FloatGrid::new(d.width(), d.height()); for (x, y, value) in res.iter_mut() { let v = d.get(x, y).unwrap(); *value = v/(v*v + 1.).sqrt(); } res } // Convergence test fn convergence(p_mask: &BoolGrid, n_mask: &BoolGrid, thresh: u32, c: u32) -> u32 { let n_diff = p_mask.iter().zip(n_mask.iter()).fold(0u32, |acc, ((_,_,p),(_,_,n))| { acc + if *p == *n { 1 } else { 0 } }); if n_diff < thresh { c + 1 } else { 0 } }
{ let inv_init_a = { let mut result = init_a.clone(); for (_, _, value) in result.iter_mut() { *value = !*value; } result }; let phi = { let dist_a = bwdist(&init_a); let dist_inv_a = bwdist(&inv_init_a); let mut result = FloatGrid::new(init_a.width(), init_a.height()); for (x, y, value) in result.iter_mut() { *value = dist_a.get(x, y).unwrap() - dist_inv_a.get(x, y).unwrap() + if *init_a.get(x, y).unwrap() {1.} else {0.} - 0.5; } result
identifier_body
lib.rs
//! This crate provides an implementation of Chan-Vese level-sets //! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/) //! by T. Chan and L. Vese. //! It is a port of the Python implementation by Kevin Keraudren on //! [Github](https://github.com/kevin-keraudren/chanvese) //! and of the Matlab implementation by [Shawn Lankton](http://www.shawnlankton.com). //! //! # Examples //! To use the functions inside module `chanvese::utils` you need to //! compile this crate with the feature image-utils. //! //! ``` //! extern crate image; //! extern crate rand; //! extern crate chanvese; //! //! use std::f64; //! use std::fs::File; //! use image::ImageBuffer; //! use rand::distributions::{Sample, Range}; //! use chanvese::{FloatGrid, BoolGrid, chanvese}; //! //! use chanvese::utils; //! //! fn main() { //! // create an input image (blurred and noisy ellipses) //! let img = { //! let mut img = ImageBuffer::new(256, 128); //! for (x, y, pixel) in img.enumerate_pixels_mut() { //! if (x-100)*(x-100)+(y-70)*(y-70) <= 35*35 { //! *pixel = image::Luma([200u8]); //! } //! if (x-128)*(x-128)/2+(y-50)*(y-50) <= 30*30 { //! *pixel = image::Luma([150u8]); //! } //! } //! img = image::imageops::blur(&img, 5.); //! let mut noiserange = Range::new(0.0f32, 30.); //! let mut rng = rand::thread_rng(); //! for (_, _, pixel) in img.enumerate_pixels_mut() { //! *pixel = image::Luma([pixel.data[0] + noiserange.sample(&mut rng) as u8]); //! } //! let ref mut imgout = File::create("image.png").unwrap(); //! image::ImageLuma8(img.clone()).save(imgout, image::PNG).unwrap(); //! let mut result = FloatGrid::new(256, 128); //! //! for (x, y, pixel) in img.enumerate_pixels() { //! result.set(x as usize, y as usize, pixel.data[0] as f64); //! } //! result //! }; //! //! // create a rough mask //! let mask = { //! let mut result = BoolGrid::new(img.width(), img.height()); //! for (x, y, value) in result.iter_mut() { //! if (x >= 65 && x <= 180) && (y >= 20 && y <= 100) { //! *value = true; //! } //! } //! result //! }; //! utils::save_boolgrid(&mask, "mask.png"); //! //! // level-set segmentation by Chan-Vese //! let (seg, phi, _) = chanvese(&img, &mask, 500, 1.0, 0); //! utils::save_boolgrid(&seg, "out.png"); //! utils::save_floatgrid(&phi, "phi.png"); //! } //! ``` extern crate distance_transform; use distance_transform::dt2d; use std::f64; pub use distance_transform::{FloatGrid, BoolGrid}; #[cfg(feature = "image-utils")] pub mod utils; #[cfg(feature = "image-utils")] mod viridis; /// Runs the chanvese algorithm /// /// Returns the resulting mask (`true` = foreground, `false` = background), /// the level-set function and the number of iterations. /// /// # Arguments /// /// * `img` - the input image /// * `init_mask` - in initial mask (`true` = foreground, `false` = background) /// * `max_its` - number of iterations /// * `alpha` - weight of smoothing term (default: 0.2) /// * `thresh` - number of different pixels in masks of successive steps (default: 0) pub fn chanvese(img: &FloatGrid, init_mask: &BoolGrid, max_its: u32, alpha: f64, thresh: u32) -> (BoolGrid, FloatGrid, u32) { // create a signed distance map (SDF) from mask let mut phi = mask2phi(init_mask); // main loop let mut its = 0u32; let mut stop = false; let mut prev_mask = init_mask.clone(); let mut c = 0u32; while its < max_its &&!stop { // get the curve's narrow band let idx = { let mut result = Vec::new(); for (x, y, &val) in phi.iter() { if val >= -1.2 && val <= 1.2 { result.push((x, y)); } } result }; if idx.len() > 0 { // intermediate output if its % 50 == 0 { println!("iteration: {}", its); } // find interior and exterior mean let (upts, vpts) = { let mut res1 = Vec::new(); let mut res2 = Vec::new(); for (x, y, value) in phi.iter() { if *value <= 0. { res1.push((x, y)); } else { res2.push((x, y)); } } (res1, res2) }; let u = upts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (upts.len() as f64 + f64::EPSILON); let v = vpts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (vpts.len() as f64 + f64::EPSILON); // force from image information let f: Vec<f64> = idx.iter().map(|&(x, y)| { (*img.get(x, y).unwrap() - u)*(*img.get(x, y).unwrap() - u) -(*img.get(x, y).unwrap() - v)*(*img.get(x, y).unwrap() - v) }).collect(); // force from curvature penalty let curvature = get_curvature(&phi, &idx); // gradient descent to minimize energy let dphidt: Vec<f64> = { let maxabs = f.iter().fold(0.0f64, |acc, &x| { acc.max(x.abs()) }); f.iter().zip(curvature.iter()).map(|(f, c)| { f/maxabs + alpha*c }).collect() }; // maintain the CFL condition let dt = 0.45/(dphidt.iter().fold(0.0f64, |acc, &x| acc.max(x.abs())) + f64::EPSILON); // evolve the curve for i in 0..idx.len() { let (x, y) = idx[i]; let val = *phi.get(x, y).unwrap(); phi.set(x, y, val + dt*dphidt[i]); } // keep SDF smooth phi = sussman(&phi, &0.5); let new_mask = { let mut result = BoolGrid::new(phi.width(), phi.height()); for (x, y, value) in phi.iter() { result.set(x, y, *value <= 0.); } result }; c = convergence(&prev_mask, &new_mask, thresh, c); if c <= 5 { its += 1; prev_mask = new_mask.clone(); } else { stop = true; } } else { break; } } // make mask from SDF, get mask from levelset let seg = { let mut res = BoolGrid::new(phi.width(), phi.height()); for (x, y, &value) in phi.iter() { res.set(x, y, value <= 0.); } res }; (seg, phi, its) } fn bwdist(a: &BoolGrid) -> FloatGrid { let mut res = dt2d(&a); for (_, _, value) in res.iter_mut() { let newval = value.sqrt(); *value = newval; } res } // Converts a mask to a SDF fn mask2phi(init_a: &BoolGrid) -> FloatGrid { let inv_init_a = { let mut result = init_a.clone(); for (_, _, value) in result.iter_mut() { *value =!*value; } result }; let phi = { let dist_a = bwdist(&init_a); let dist_inv_a = bwdist(&inv_init_a); let mut result = FloatGrid::new(init_a.width(), init_a.height()); for (x, y, value) in result.iter_mut() { *value = dist_a.get(x, y).unwrap() - dist_inv_a.get(x, y).unwrap() + if *init_a.get(x, y).unwrap() {1.} else {0.} - 0.5; } result }; phi } // Compute curvature along SDF fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> { // get central derivatives of SDF at x,y let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = { let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy) : (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) = ( Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len())); for &(x, y) in idx.iter() { let left = if x > 0 { x - 1 } else { 0 }; let right = if x < phi.width() - 1 { x + 1 } else { phi.width() - 1 }; let up = if y > 0 { y - 1 } else { 0 }; let down = if y < phi.height() - 1 { y + 1 } else { phi.height() - 1 }; res_x.push(-*phi.get(left, y).unwrap() + *phi.get(right, y).unwrap()); res_y.push(-*phi.get(x, down).unwrap() + *phi.get(x, up).unwrap()); res_xx.push( *phi.get(left, y).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(right, y).unwrap()); res_yy.push( *phi.get(x, up).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(x, down).unwrap()); res_xy.push(0.25*( -*phi.get(left, down).unwrap() - *phi.get(right, up).unwrap() +*phi.get(right, down).unwrap() + *phi.get(left, up).unwrap() )); } (res_x, res_y, res_xx, res_yy, res_xy) }; let phi_x2: Vec<f64> = phi_x.iter().map(|x| x*x).collect(); let phi_y2: Vec<f64> = phi_y.iter().map(|x| x*x).collect(); // compute curvature (Kappa) let curvature: Vec<f64> = (0..idx.len()).map(|i| { ((phi_x2[i]*phi_yy[i] + phi_y2[i]*phi_xx[i] - 2.*phi_x[i]*phi_y[i]*phi_xy[i])/ (phi_x2[i] + phi_y2[i] + f64::EPSILON).powf(1.5))*(phi_x2[i] + phi_y2[i]).powf(0.5) }).collect(); curvature } // Level set re-initialization by the sussman method fn sussman(grid: &FloatGrid, dt: &f64) -> FloatGrid { // forward/backward differences let (a, b, c, d) = { let mut a_res = FloatGrid::new(grid.width(), grid.height()); let mut b_res = FloatGrid::new(grid.width(), grid.height()); let mut c_res = FloatGrid::new(grid.width(), grid.height()); let mut d_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { a_res.set(x, y, grid.get(x, y).unwrap() - grid.get((x + grid.width() - 1) % grid.width(), y).unwrap()); b_res.set(x, y, grid.get((x + 1) % grid.width(), y).unwrap() - grid.get(x, y).unwrap()); c_res.set(x, y, grid.get(x, y).unwrap() - grid.get(x, (y + 1) % grid.height()).unwrap()); d_res.set(x, y, grid.get(x, (y + grid.height() - 1) % grid.height()).unwrap() - grid.get(x, y).unwrap()); } } (a_res, b_res, c_res, d_res) }; let (a_p, a_n, b_p, b_n, c_p, c_n, d_p, d_n) = { let mut a_p_res = FloatGrid::new(grid.width(), grid.height()); let mut a_n_res = FloatGrid::new(grid.width(), grid.height()); let mut b_p_res = FloatGrid::new(grid.width(), grid.height()); let mut b_n_res = FloatGrid::new(grid.width(), grid.height()); let mut c_p_res = FloatGrid::new(grid.width(), grid.height()); let mut c_n_res = FloatGrid::new(grid.width(), grid.height()); let mut d_p_res = FloatGrid::new(grid.width(), grid.height());
for y in 0..grid.height() { for x in 0..grid.width() { let a_p_dval = *a.get(x, y).unwrap(); let a_n_dval = *a.get(x, y).unwrap(); let b_p_dval = *b.get(x, y).unwrap(); let b_n_dval = *b.get(x, y).unwrap(); let c_p_dval = *c.get(x, y).unwrap(); let c_n_dval = *c.get(x, y).unwrap(); let d_p_dval = *d.get(x, y).unwrap(); let d_n_dval = *d.get(x, y).unwrap(); a_p_res.set(x, y, if a_p_dval >= 0.0 { a_p_dval } else { 0.0 }); a_n_res.set(x, y, if a_n_dval <= 0.0 { a_n_dval } else { 0.0 }); b_p_res.set(x, y, if b_p_dval >= 0.0 { b_p_dval } else { 0.0 }); b_n_res.set(x, y, if b_n_dval <= 0.0 { b_n_dval } else { 0.0 }); c_p_res.set(x, y, if c_p_dval >= 0.0 { c_p_dval } else { 0.0 }); c_n_res.set(x, y, if c_n_dval <= 0.0 { c_n_dval } else { 0.0 }); d_p_res.set(x, y, if d_p_dval >= 0.0 { d_p_dval } else { 0.0 }); d_n_res.set(x, y, if d_n_dval <= 0.0 { d_n_dval } else { 0.0 }); } } (a_p_res, a_n_res, b_p_res, b_n_res, c_p_res, c_n_res, d_p_res, d_n_res) }; let mut d_d = FloatGrid::new(grid.width(), grid.height()); let (d_neg_ind, d_pos_ind) = { let mut res = (Vec::new(), Vec::new()); for (x, y, &value) in grid.iter() { if value < 0.0 { res.0.push((x, y)); } else if value > 0.0 { res.1.push((x,y)); } } res }; for index in d_pos_ind { let mut ap = *a_p.get(index.0, index.1).unwrap(); let mut bn = *b_n.get(index.0, index.1).unwrap(); let mut cp = *c_p.get(index.0, index.1).unwrap(); let mut dn = *d_n.get(index.0, index.1).unwrap(); ap *= ap; bn *= bn; cp *= cp; dn *= dn; d_d.set(index.0, index.1, (ap.max(bn) + cp.max(dn)).sqrt() - 1.); } for index in d_neg_ind { let mut an = *a_n.get(index.0, index.1).unwrap(); let mut bp = *b_p.get(index.0, index.1).unwrap(); let mut cn = *c_n.get(index.0, index.1).unwrap(); let mut dp = *d_p.get(index.0, index.1).unwrap(); an *= an; bp *= bp; cn *= cn; dp *= dp; d_d.set(index.0, index.1, (an.max(bp) + cn.max(dp)).sqrt() - 1.); } let ss_d = sussman_sign(&grid); let mut res = FloatGrid::new(grid.width(), grid.height()); for (x, y, value) in res.iter_mut() { let dval = grid.get(x, y).unwrap(); let ss_dval = ss_d.get(x, y).unwrap(); let d_dval = d_d.get(x, y).unwrap(); *value = dval - dt*ss_dval*d_dval; } res } fn sussman_sign(d: &FloatGrid) -> FloatGrid { let mut res = FloatGrid::new(d.width(), d.height()); for (x, y, value) in res.iter_mut() { let v = d.get(x, y).unwrap(); *value = v/(v*v + 1.).sqrt(); } res } // Convergence test fn convergence(p_mask: &BoolGrid, n_mask: &BoolGrid, thresh: u32, c: u32) -> u32 { let n_diff = p_mask.iter().zip(n_mask.iter()).fold(0u32, |acc, ((_,_,p),(_,_,n))| { acc + if *p == *n { 1 } else { 0 } }); if n_diff < thresh { c + 1 } else { 0 } }
let mut d_n_res = FloatGrid::new(grid.width(), grid.height());
random_line_split
lib.rs
//! This crate provides an implementation of Chan-Vese level-sets //! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/) //! by T. Chan and L. Vese. //! It is a port of the Python implementation by Kevin Keraudren on //! [Github](https://github.com/kevin-keraudren/chanvese) //! and of the Matlab implementation by [Shawn Lankton](http://www.shawnlankton.com). //! //! # Examples //! To use the functions inside module `chanvese::utils` you need to //! compile this crate with the feature image-utils. //! //! ``` //! extern crate image; //! extern crate rand; //! extern crate chanvese; //! //! use std::f64; //! use std::fs::File; //! use image::ImageBuffer; //! use rand::distributions::{Sample, Range}; //! use chanvese::{FloatGrid, BoolGrid, chanvese}; //! //! use chanvese::utils; //! //! fn main() { //! // create an input image (blurred and noisy ellipses) //! let img = { //! let mut img = ImageBuffer::new(256, 128); //! for (x, y, pixel) in img.enumerate_pixels_mut() { //! if (x-100)*(x-100)+(y-70)*(y-70) <= 35*35 { //! *pixel = image::Luma([200u8]); //! } //! if (x-128)*(x-128)/2+(y-50)*(y-50) <= 30*30 { //! *pixel = image::Luma([150u8]); //! } //! } //! img = image::imageops::blur(&img, 5.); //! let mut noiserange = Range::new(0.0f32, 30.); //! let mut rng = rand::thread_rng(); //! for (_, _, pixel) in img.enumerate_pixels_mut() { //! *pixel = image::Luma([pixel.data[0] + noiserange.sample(&mut rng) as u8]); //! } //! let ref mut imgout = File::create("image.png").unwrap(); //! image::ImageLuma8(img.clone()).save(imgout, image::PNG).unwrap(); //! let mut result = FloatGrid::new(256, 128); //! //! for (x, y, pixel) in img.enumerate_pixels() { //! result.set(x as usize, y as usize, pixel.data[0] as f64); //! } //! result //! }; //! //! // create a rough mask //! let mask = { //! let mut result = BoolGrid::new(img.width(), img.height()); //! for (x, y, value) in result.iter_mut() { //! if (x >= 65 && x <= 180) && (y >= 20 && y <= 100) { //! *value = true; //! } //! } //! result //! }; //! utils::save_boolgrid(&mask, "mask.png"); //! //! // level-set segmentation by Chan-Vese //! let (seg, phi, _) = chanvese(&img, &mask, 500, 1.0, 0); //! utils::save_boolgrid(&seg, "out.png"); //! utils::save_floatgrid(&phi, "phi.png"); //! } //! ``` extern crate distance_transform; use distance_transform::dt2d; use std::f64; pub use distance_transform::{FloatGrid, BoolGrid}; #[cfg(feature = "image-utils")] pub mod utils; #[cfg(feature = "image-utils")] mod viridis; /// Runs the chanvese algorithm /// /// Returns the resulting mask (`true` = foreground, `false` = background), /// the level-set function and the number of iterations. /// /// # Arguments /// /// * `img` - the input image /// * `init_mask` - in initial mask (`true` = foreground, `false` = background) /// * `max_its` - number of iterations /// * `alpha` - weight of smoothing term (default: 0.2) /// * `thresh` - number of different pixels in masks of successive steps (default: 0) pub fn chanvese(img: &FloatGrid, init_mask: &BoolGrid, max_its: u32, alpha: f64, thresh: u32) -> (BoolGrid, FloatGrid, u32) { // create a signed distance map (SDF) from mask let mut phi = mask2phi(init_mask); // main loop let mut its = 0u32; let mut stop = false; let mut prev_mask = init_mask.clone(); let mut c = 0u32; while its < max_its &&!stop { // get the curve's narrow band let idx = { let mut result = Vec::new(); for (x, y, &val) in phi.iter() { if val >= -1.2 && val <= 1.2 { result.push((x, y)); } } result }; if idx.len() > 0 { // intermediate output if its % 50 == 0 { println!("iteration: {}", its); } // find interior and exterior mean let (upts, vpts) = { let mut res1 = Vec::new(); let mut res2 = Vec::new(); for (x, y, value) in phi.iter() { if *value <= 0. { res1.push((x, y)); } else { res2.push((x, y)); } } (res1, res2) }; let u = upts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (upts.len() as f64 + f64::EPSILON); let v = vpts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (vpts.len() as f64 + f64::EPSILON); // force from image information let f: Vec<f64> = idx.iter().map(|&(x, y)| { (*img.get(x, y).unwrap() - u)*(*img.get(x, y).unwrap() - u) -(*img.get(x, y).unwrap() - v)*(*img.get(x, y).unwrap() - v) }).collect(); // force from curvature penalty let curvature = get_curvature(&phi, &idx); // gradient descent to minimize energy let dphidt: Vec<f64> = { let maxabs = f.iter().fold(0.0f64, |acc, &x| { acc.max(x.abs()) }); f.iter().zip(curvature.iter()).map(|(f, c)| { f/maxabs + alpha*c }).collect() }; // maintain the CFL condition let dt = 0.45/(dphidt.iter().fold(0.0f64, |acc, &x| acc.max(x.abs())) + f64::EPSILON); // evolve the curve for i in 0..idx.len() { let (x, y) = idx[i]; let val = *phi.get(x, y).unwrap(); phi.set(x, y, val + dt*dphidt[i]); } // keep SDF smooth phi = sussman(&phi, &0.5); let new_mask = { let mut result = BoolGrid::new(phi.width(), phi.height()); for (x, y, value) in phi.iter() { result.set(x, y, *value <= 0.); } result }; c = convergence(&prev_mask, &new_mask, thresh, c); if c <= 5 { its += 1; prev_mask = new_mask.clone(); } else { stop = true; } } else { break; } } // make mask from SDF, get mask from levelset let seg = { let mut res = BoolGrid::new(phi.width(), phi.height()); for (x, y, &value) in phi.iter() { res.set(x, y, value <= 0.); } res }; (seg, phi, its) } fn bwdist(a: &BoolGrid) -> FloatGrid { let mut res = dt2d(&a); for (_, _, value) in res.iter_mut() { let newval = value.sqrt(); *value = newval; } res } // Converts a mask to a SDF fn mask2phi(init_a: &BoolGrid) -> FloatGrid { let inv_init_a = { let mut result = init_a.clone(); for (_, _, value) in result.iter_mut() { *value =!*value; } result }; let phi = { let dist_a = bwdist(&init_a); let dist_inv_a = bwdist(&inv_init_a); let mut result = FloatGrid::new(init_a.width(), init_a.height()); for (x, y, value) in result.iter_mut() { *value = dist_a.get(x, y).unwrap() - dist_inv_a.get(x, y).unwrap() + if *init_a.get(x, y).unwrap() {1.} else {0.} - 0.5; } result }; phi } // Compute curvature along SDF fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> { // get central derivatives of SDF at x,y let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = { let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy) : (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) = ( Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len())); for &(x, y) in idx.iter() { let left = if x > 0 { x - 1 } else { 0 }; let right = if x < phi.width() - 1 { x + 1 } else { phi.width() - 1 }; let up = if y > 0 { y - 1 } else { 0 }; let down = if y < phi.height() - 1 { y + 1 } else { phi.height() - 1 }; res_x.push(-*phi.get(left, y).unwrap() + *phi.get(right, y).unwrap()); res_y.push(-*phi.get(x, down).unwrap() + *phi.get(x, up).unwrap()); res_xx.push( *phi.get(left, y).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(right, y).unwrap()); res_yy.push( *phi.get(x, up).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(x, down).unwrap()); res_xy.push(0.25*( -*phi.get(left, down).unwrap() - *phi.get(right, up).unwrap() +*phi.get(right, down).unwrap() + *phi.get(left, up).unwrap() )); } (res_x, res_y, res_xx, res_yy, res_xy) }; let phi_x2: Vec<f64> = phi_x.iter().map(|x| x*x).collect(); let phi_y2: Vec<f64> = phi_y.iter().map(|x| x*x).collect(); // compute curvature (Kappa) let curvature: Vec<f64> = (0..idx.len()).map(|i| { ((phi_x2[i]*phi_yy[i] + phi_y2[i]*phi_xx[i] - 2.*phi_x[i]*phi_y[i]*phi_xy[i])/ (phi_x2[i] + phi_y2[i] + f64::EPSILON).powf(1.5))*(phi_x2[i] + phi_y2[i]).powf(0.5) }).collect(); curvature } // Level set re-initialization by the sussman method fn sussman(grid: &FloatGrid, dt: &f64) -> FloatGrid { // forward/backward differences let (a, b, c, d) = { let mut a_res = FloatGrid::new(grid.width(), grid.height()); let mut b_res = FloatGrid::new(grid.width(), grid.height()); let mut c_res = FloatGrid::new(grid.width(), grid.height()); let mut d_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { a_res.set(x, y, grid.get(x, y).unwrap() - grid.get((x + grid.width() - 1) % grid.width(), y).unwrap()); b_res.set(x, y, grid.get((x + 1) % grid.width(), y).unwrap() - grid.get(x, y).unwrap()); c_res.set(x, y, grid.get(x, y).unwrap() - grid.get(x, (y + 1) % grid.height()).unwrap()); d_res.set(x, y, grid.get(x, (y + grid.height() - 1) % grid.height()).unwrap() - grid.get(x, y).unwrap()); } } (a_res, b_res, c_res, d_res) }; let (a_p, a_n, b_p, b_n, c_p, c_n, d_p, d_n) = { let mut a_p_res = FloatGrid::new(grid.width(), grid.height()); let mut a_n_res = FloatGrid::new(grid.width(), grid.height()); let mut b_p_res = FloatGrid::new(grid.width(), grid.height()); let mut b_n_res = FloatGrid::new(grid.width(), grid.height()); let mut c_p_res = FloatGrid::new(grid.width(), grid.height()); let mut c_n_res = FloatGrid::new(grid.width(), grid.height()); let mut d_p_res = FloatGrid::new(grid.width(), grid.height()); let mut d_n_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { let a_p_dval = *a.get(x, y).unwrap(); let a_n_dval = *a.get(x, y).unwrap(); let b_p_dval = *b.get(x, y).unwrap(); let b_n_dval = *b.get(x, y).unwrap(); let c_p_dval = *c.get(x, y).unwrap(); let c_n_dval = *c.get(x, y).unwrap(); let d_p_dval = *d.get(x, y).unwrap(); let d_n_dval = *d.get(x, y).unwrap(); a_p_res.set(x, y, if a_p_dval >= 0.0 { a_p_dval } else { 0.0 }); a_n_res.set(x, y, if a_n_dval <= 0.0 { a_n_dval } else { 0.0 }); b_p_res.set(x, y, if b_p_dval >= 0.0 { b_p_dval } else { 0.0 }); b_n_res.set(x, y, if b_n_dval <= 0.0 { b_n_dval } else { 0.0 }); c_p_res.set(x, y, if c_p_dval >= 0.0 { c_p_dval } else { 0.0 }); c_n_res.set(x, y, if c_n_dval <= 0.0 { c_n_dval } else { 0.0 }); d_p_res.set(x, y, if d_p_dval >= 0.0 { d_p_dval } else { 0.0 }); d_n_res.set(x, y, if d_n_dval <= 0.0 { d_n_dval } else { 0.0 }); } } (a_p_res, a_n_res, b_p_res, b_n_res, c_p_res, c_n_res, d_p_res, d_n_res) }; let mut d_d = FloatGrid::new(grid.width(), grid.height()); let (d_neg_ind, d_pos_ind) = { let mut res = (Vec::new(), Vec::new()); for (x, y, &value) in grid.iter() { if value < 0.0 { res.0.push((x, y)); } else if value > 0.0 { res.1.push((x,y)); } } res }; for index in d_pos_ind { let mut ap = *a_p.get(index.0, index.1).unwrap(); let mut bn = *b_n.get(index.0, index.1).unwrap(); let mut cp = *c_p.get(index.0, index.1).unwrap(); let mut dn = *d_n.get(index.0, index.1).unwrap(); ap *= ap; bn *= bn; cp *= cp; dn *= dn; d_d.set(index.0, index.1, (ap.max(bn) + cp.max(dn)).sqrt() - 1.); } for index in d_neg_ind { let mut an = *a_n.get(index.0, index.1).unwrap(); let mut bp = *b_p.get(index.0, index.1).unwrap(); let mut cn = *c_n.get(index.0, index.1).unwrap(); let mut dp = *d_p.get(index.0, index.1).unwrap(); an *= an; bp *= bp; cn *= cn; dp *= dp; d_d.set(index.0, index.1, (an.max(bp) + cn.max(dp)).sqrt() - 1.); } let ss_d = sussman_sign(&grid); let mut res = FloatGrid::new(grid.width(), grid.height()); for (x, y, value) in res.iter_mut() { let dval = grid.get(x, y).unwrap(); let ss_dval = ss_d.get(x, y).unwrap(); let d_dval = d_d.get(x, y).unwrap(); *value = dval - dt*ss_dval*d_dval; } res } fn
(d: &FloatGrid) -> FloatGrid { let mut res = FloatGrid::new(d.width(), d.height()); for (x, y, value) in res.iter_mut() { let v = d.get(x, y).unwrap(); *value = v/(v*v + 1.).sqrt(); } res } // Convergence test fn convergence(p_mask: &BoolGrid, n_mask: &BoolGrid, thresh: u32, c: u32) -> u32 { let n_diff = p_mask.iter().zip(n_mask.iter()).fold(0u32, |acc, ((_,_,p),(_,_,n))| { acc + if *p == *n { 1 } else { 0 } }); if n_diff < thresh { c + 1 } else { 0 } }
sussman_sign
identifier_name
controller.rs
//! Contains ZX Spectrum System contrller (like ula or so) of emulator use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; // use almost everything :D use utils::{split_word, Clocks}; use utils::screen::*; use utils::events::*; use utils::InstantFlag; use z80::Z80Bus; use zx::{ZXMemory, RomType, RamType}; use zx::memory::{Page, PAGE_SIZE}; use zx::machine::ZXMachine; use zx::tape::*; use zx::ZXKey; use zx::screen::canvas::ZXCanvas; use zx::screen::border::ZXBorder; use zx::screen::colors::{ZXColor, ZXPalette}; use zx::roms::*; use zx::constants::*; use zx::sound::mixer::ZXMixer; use settings::RustzxSettings; use zx::joy::kempston::*; /// ZX System controller pub struct ZXController { // parts of ZX Spectum. pub machine: ZXMachine, pub memory: ZXMemory, pub canvas: ZXCanvas, pub tape: Box<ZXTape>, pub border: ZXBorder, pub kempston: Option<KempstonJoy>, //pub beeper: ZXBeeper, pub mixer: ZXMixer, pub keyboard: [u8; 8], // current border color border_color: u8, // clocls count from frame start frame_clocks: Clocks, // frames count, which passed during emulation invokation passed_frames: usize, // main event queue events: EventQueue, // flag, which signals emulator to break emulation and process last event immediately instant_event: InstantFlag, // audio in mic: bool, // audio out ear: bool, paging_enabled: bool, screen_bank: u8, } impl ZXController { /// Returns new ZXController from settings pub fn new(settings: &RustzxSettings) -> ZXController { let (memory, paging, screen_bank); match settings.machine { ZXMachine::Sinclair48K => { memory = ZXMemory::new(RomType::K16, RamType::K48); paging = false; screen_bank = 0; } ZXMachine::Sinclair128K => { memory = ZXMemory::new(RomType::K32, RamType::K128); paging = true; screen_bank = 5; } }; let kempston = if settings.kempston { Some(KempstonJoy::new()) } else { None }; let mut out = ZXController { machine: settings.machine, memory: memory, canvas: ZXCanvas::new(settings.machine), border: ZXBorder::new(settings.machine, ZXPalette::default()), kempston: kempston, mixer: ZXMixer::new(settings.beeper_enabled, settings.ay_enabled), keyboard: [0xFF; 8], border_color: 0x00, frame_clocks: Clocks(0), passed_frames: 0, tape: Box::new(Tap::new()), events: EventQueue::new(), instant_event: InstantFlag::new(false), mic: false, ear: false, paging_enabled: paging, screen_bank: screen_bank, }; out.mixer.ay.mode(settings.ay_mode); out.mixer.volume(settings.volume as f64 / 200.0);
fn frame_pos(&self) -> f64 { let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64; if val > 1.0 { 1.0 } else { val } } /// loads rom from file /// for 128-K machines path must contain ".0" in the tail /// and second rom bank will be loaded automatically pub fn load_rom(&mut self, path: impl AsRef<Path>) { match self.machine { // Single ROM file ZXMachine::Sinclair48K => { let mut rom = Vec::new(); File::open(path).ok().expect("[ERROR] ROM not found").read_to_end(&mut rom) .unwrap(); self.memory.load_rom(0, &rom); } // Two ROM's ZXMachine::Sinclair128K => { let mut rom0 = Vec::new(); let mut rom1 = Vec::new(); if!path.as_ref().extension().map_or(false, |e| e == "0") { println!("[Warning] ROM0 filename should end with.0"); } File::open(path.as_ref()).ok().expect("[ERROR] ROM0 not found").read_to_end(&mut rom0) .unwrap(); let mut second_path: PathBuf = path.as_ref().to_path_buf(); second_path.set_extension("1"); File::open(second_path).ok().expect("[ERROR] ROM1 not found").read_to_end(&mut rom1) .unwrap(); self.memory.load_rom(0, &rom0) .load_rom(1, &rom1); println!("ROM's Loaded"); } } } /// loads builted-in ROM pub fn load_default_rom(&mut self) { match self.machine { ZXMachine::Sinclair48K => { self.memory.load_rom(0, ROM_48K); } ZXMachine::Sinclair128K => { self.memory.load_rom(0, ROM_128K_0) .load_rom(1, ROM_128K_1); } } } /// Changes key state in controller pub fn send_key(&mut self, key: ZXKey, pressed: bool) { // TODO: Move row detection to ZXKey type let rownum = match key.half_port { 0xFE => Some(0), 0xFD => Some(1), 0xFB => Some(2), 0xF7 => Some(3), 0xEF => Some(4), 0xDF => Some(5), 0xBF => Some(6), 0x7F => Some(7), _ => None, }; if let Some(rownum) = rownum { self.keyboard[rownum] = self.keyboard[rownum] & (!key.mask); if!pressed { self.keyboard[rownum] |= key.mask; } } } /// Dumps memory space pub fn dump(&self) -> Vec<u8> { self.memory.dump() } /// Returns current bus floating value fn floating_bus_value(&self) -> u8 { let specs = self.machine.specs(); let clocks = self.frame_clocks; if clocks.count() < specs.clocks_first_pixel + 2 { return 0xFF; } let clocks = clocks.count() - (specs.clocks_first_pixel + 2); let row = clocks / specs.clocks_line; let clocks = clocks % specs.clocks_line; let col = (clocks / 8) * 2 + (clocks % 8) / 2; if row < CANVAS_HEIGHT && clocks < specs.clocks_screen_row - CLOCKS_PER_COL && ((clocks & 0x04) == 0) { if clocks % 2 == 0 { return self.memory.read(bitmap_line_addr(row) + col as u16); } else { let byte = (row / 8) * 32 + col; return self.memory.read(0x5800 + byte as u16); }; } return 0xFF; } /// make contention fn do_contention(&mut self) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention); } ///make contention + wait some clocks fn do_contention_and_wait(&mut self, wait_time: Clocks) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention + wait_time); } // check addr contention fn addr_is_contended(&self, addr: u16) -> bool { return if let Page::Ram(bank) = self.memory.get_page(addr) { self.machine.bank_is_contended(bank as usize) } else { false } } /// Returns early IO contention clocks fn io_contention_first(&mut self, port: u16) { if self.addr_is_contended(port) { self.do_contention(); }; self.wait_internal(Clocks(1)); } /// Returns late IO contention clocks fn io_contention_last(&mut self, port: u16) { if self.machine.port_is_contended(port) { self.do_contention_and_wait(Clocks(2)); } else { if self.addr_is_contended(port) { self.do_contention_and_wait(Clocks(1)); self.do_contention_and_wait(Clocks(1)); self.do_contention(); } else { self.wait_internal(Clocks(2)); } } } /// Starts a new frame fn new_frame(&mut self) { self.frame_clocks -= self.machine.specs().clocks_frame; self.canvas.new_frame(); self.border.new_frame(); self.mixer.new_frame(); } /// force clears all events pub fn clear_events(&mut self) { self.events.clear(); } /// check events count pub fn no_events(&self) -> bool { self.events.is_empty() } /// Returns last event pub fn pop_event(&mut self) -> Option<Event> { self.events.receive_event() } /// Returns true if all frame clocks has been passed pub fn frames_count(&self) -> usize { self.passed_frames } pub fn reset_frame_counter(&mut self) { self.passed_frames = 0; } /// Returns current clocks from frame start pub fn clocks(&self) -> Clocks { self.frame_clocks } fn write_7ffd(&mut self, val: u8) { if!self.paging_enabled { return; } // remap top 16K of the ram self.memory.remap(3, Page::Ram(val & 0x07)); // third block is not pageable // second block is screen buffer, not pageable. but we need to change active buffer let new_screen_bank = if val & 0x08 == 0 { 5 } else { 7 }; self.canvas.switch_bank(new_screen_bank as usize); self.screen_bank = new_screen_bank; // remap ROM self.memory.remap(0, Page::Rom((val >> 4) & 0x01)); // check paging allow bit if val & 0x20!= 0 { self.paging_enabled = false; } } } impl Z80Bus for ZXController { /// we need to check different breakpoints like tape /// loading detection breakpoint fn pc_callback(&mut self, addr: u16) { // check mapped memory page at 0x0000.. 0x3FFF let check_fast_load = match self.machine { ZXMachine::Sinclair48K if self.memory.get_bank_type(0) == Page::Rom(0) => true, ZXMachine::Sinclair128K if self.memory.get_bank_type(0) == Page::Rom(1) => true, _ => false, }; if check_fast_load { // Tape LOAD/VERIFY if addr == ADDR_LD_BREAK { // Add event (Fast tape loading request) it must be executed // by emulator immediately self.events.send_event(Event::new(EventKind::FastTapeLoad, self.frame_clocks)); self.instant_event.set(); } } } /// read data without taking onto account contention fn read_internal(&mut self, addr: u16) -> u8 { self.memory.read(addr) } /// write data without taking onto account contention fn write_internal(&mut self, addr: u16, data: u8) { self.memory.write(addr, data); // if ram then compare bank to screen bank if let Page::Ram(bank) = self.memory.get_page(addr) { self.canvas.update(addr % PAGE_SIZE as u16, bank as usize, data); } } /// Cahnges internal state on clocks count change (emualtion processing) fn wait_internal(&mut self, clk: Clocks) { self.frame_clocks += clk; (*self.tape).process_clocks(clk); let mic = (*self.tape).current_bit(); self.mic = mic; let pos = self.frame_pos(); self.mixer.beeper.change_bit(self.mic | self.ear); self.mixer.process(pos); self.canvas.process_clocks(self.frame_clocks); if self.frame_clocks.count() >= self.machine.specs().clocks_frame { self.new_frame(); self.passed_frames += 1; } } // wait with memory request pin active fn wait_mreq(&mut self, addr: u16, clk: Clocks) { match self.machine { ZXMachine::Sinclair48K | ZXMachine::Sinclair128K=> { // contention in low 16k RAM if self.addr_is_contended(addr) { self.do_contention(); } } } self.wait_internal(clk); } /// wait without memory request pin active fn wait_no_mreq(&mut self, addr: u16, clk: Clocks) { // only for 48 K! self.wait_mreq(addr, clk); } /// read io from hardware fn read_io(&mut self, port: u16) -> u8 { // all contentions check self.io_contention_first(port); self.io_contention_last(port); // find out what we need to do let (h, _) = split_word(port); let output = if port & 0x0001 == 0 { // ULA port let mut tmp: u8 = 0xFF; for n in 0..8 { // if bit of row reset if ((h >> n) & 0x01) == 0 { tmp &= self.keyboard[n]; } } // invert bit 6 if mic_hw active; if self.mic { tmp ^= 0x40; } // 5 and 7 unused tmp } else if port & 0xC002 == 0xC000 { // AY regs self.mixer.ay.read() } else if self.kempston.is_some() && (port & 0x0020 == 0) { if let Some(ref joy) = self.kempston { joy.read() } else { unreachable!() } } else { self.floating_bus_value() }; // add one clock after operation self.wait_internal(Clocks(1)); output } /// write value to hardware port fn write_io(&mut self, port: u16, data: u8) { // first contention self.io_contention_first(port); // find active port if port & 0xC002 == 0xC000 { self.mixer.ay.select_reg(data); } else if port & 0xC002 == 0x8000 { self.mixer.ay.write(data); } else if port & 0x0001 == 0 { self.border_color = data & 0x07; self.border.set_border(self.frame_clocks, ZXColor::from_bits(data & 0x07)); self.mic = data & 0x08!= 0; self.ear = data & 0x10!= 0; self.mixer.beeper.change_bit(self.mic | self.ear); } else if (port & 0x8002 == 0) && (self.machine == ZXMachine::Sinclair128K) { self.write_7ffd(data); } // last contention after byte write self.io_contention_last(port); // add one clock after operation self.wait_internal(Clocks(1)); } /// value, requested during `INT0` interrupt fn read_interrupt(&mut self) -> u8 { 0xFF } /// checks system maskable interrupt pin state fn int_active(&self) -> bool { self.frame_clocks.count() % self.machine.specs().clocks_frame < self.machine.specs().interrupt_length } /// checks non-maskable interrupt pin state fn nmi_active(&self) -> bool { false } /// CPU calls it when RETI instruction was processed fn reti(&mut self) {} /// CPU calls when was being halted fn halt(&mut self, _: bool) {} /// checks instant events fn instant_event(&self) -> bool { self.instant_event.pick() } }
out } /// returns current frame emulation pos in percents
random_line_split
controller.rs
//! Contains ZX Spectrum System contrller (like ula or so) of emulator use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; // use almost everything :D use utils::{split_word, Clocks}; use utils::screen::*; use utils::events::*; use utils::InstantFlag; use z80::Z80Bus; use zx::{ZXMemory, RomType, RamType}; use zx::memory::{Page, PAGE_SIZE}; use zx::machine::ZXMachine; use zx::tape::*; use zx::ZXKey; use zx::screen::canvas::ZXCanvas; use zx::screen::border::ZXBorder; use zx::screen::colors::{ZXColor, ZXPalette}; use zx::roms::*; use zx::constants::*; use zx::sound::mixer::ZXMixer; use settings::RustzxSettings; use zx::joy::kempston::*; /// ZX System controller pub struct ZXController { // parts of ZX Spectum. pub machine: ZXMachine, pub memory: ZXMemory, pub canvas: ZXCanvas, pub tape: Box<ZXTape>, pub border: ZXBorder, pub kempston: Option<KempstonJoy>, //pub beeper: ZXBeeper, pub mixer: ZXMixer, pub keyboard: [u8; 8], // current border color border_color: u8, // clocls count from frame start frame_clocks: Clocks, // frames count, which passed during emulation invokation passed_frames: usize, // main event queue events: EventQueue, // flag, which signals emulator to break emulation and process last event immediately instant_event: InstantFlag, // audio in mic: bool, // audio out ear: bool, paging_enabled: bool, screen_bank: u8, } impl ZXController { /// Returns new ZXController from settings pub fn new(settings: &RustzxSettings) -> ZXController { let (memory, paging, screen_bank); match settings.machine { ZXMachine::Sinclair48K => { memory = ZXMemory::new(RomType::K16, RamType::K48); paging = false; screen_bank = 0; } ZXMachine::Sinclair128K => { memory = ZXMemory::new(RomType::K32, RamType::K128); paging = true; screen_bank = 5; } }; let kempston = if settings.kempston { Some(KempstonJoy::new()) } else { None }; let mut out = ZXController { machine: settings.machine, memory: memory, canvas: ZXCanvas::new(settings.machine), border: ZXBorder::new(settings.machine, ZXPalette::default()), kempston: kempston, mixer: ZXMixer::new(settings.beeper_enabled, settings.ay_enabled), keyboard: [0xFF; 8], border_color: 0x00, frame_clocks: Clocks(0), passed_frames: 0, tape: Box::new(Tap::new()), events: EventQueue::new(), instant_event: InstantFlag::new(false), mic: false, ear: false, paging_enabled: paging, screen_bank: screen_bank, }; out.mixer.ay.mode(settings.ay_mode); out.mixer.volume(settings.volume as f64 / 200.0); out } /// returns current frame emulation pos in percents fn frame_pos(&self) -> f64 { let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64; if val > 1.0 { 1.0 } else { val } } /// loads rom from file /// for 128-K machines path must contain ".0" in the tail /// and second rom bank will be loaded automatically pub fn load_rom(&mut self, path: impl AsRef<Path>) { match self.machine { // Single ROM file ZXMachine::Sinclair48K => { let mut rom = Vec::new(); File::open(path).ok().expect("[ERROR] ROM not found").read_to_end(&mut rom) .unwrap(); self.memory.load_rom(0, &rom); } // Two ROM's ZXMachine::Sinclair128K => { let mut rom0 = Vec::new(); let mut rom1 = Vec::new(); if!path.as_ref().extension().map_or(false, |e| e == "0") { println!("[Warning] ROM0 filename should end with.0"); } File::open(path.as_ref()).ok().expect("[ERROR] ROM0 not found").read_to_end(&mut rom0) .unwrap(); let mut second_path: PathBuf = path.as_ref().to_path_buf(); second_path.set_extension("1"); File::open(second_path).ok().expect("[ERROR] ROM1 not found").read_to_end(&mut rom1) .unwrap(); self.memory.load_rom(0, &rom0) .load_rom(1, &rom1); println!("ROM's Loaded"); } } } /// loads builted-in ROM pub fn load_default_rom(&mut self) { match self.machine { ZXMachine::Sinclair48K => { self.memory.load_rom(0, ROM_48K); } ZXMachine::Sinclair128K => { self.memory.load_rom(0, ROM_128K_0) .load_rom(1, ROM_128K_1); } } } /// Changes key state in controller pub fn send_key(&mut self, key: ZXKey, pressed: bool) { // TODO: Move row detection to ZXKey type let rownum = match key.half_port { 0xFE => Some(0), 0xFD => Some(1), 0xFB => Some(2), 0xF7 => Some(3), 0xEF => Some(4), 0xDF => Some(5), 0xBF => Some(6), 0x7F => Some(7), _ => None, }; if let Some(rownum) = rownum { self.keyboard[rownum] = self.keyboard[rownum] & (!key.mask); if!pressed { self.keyboard[rownum] |= key.mask; } } } /// Dumps memory space pub fn dump(&self) -> Vec<u8> { self.memory.dump() } /// Returns current bus floating value fn floating_bus_value(&self) -> u8 { let specs = self.machine.specs(); let clocks = self.frame_clocks; if clocks.count() < specs.clocks_first_pixel + 2 { return 0xFF; } let clocks = clocks.count() - (specs.clocks_first_pixel + 2); let row = clocks / specs.clocks_line; let clocks = clocks % specs.clocks_line; let col = (clocks / 8) * 2 + (clocks % 8) / 2; if row < CANVAS_HEIGHT && clocks < specs.clocks_screen_row - CLOCKS_PER_COL && ((clocks & 0x04) == 0) { if clocks % 2 == 0 { return self.memory.read(bitmap_line_addr(row) + col as u16); } else { let byte = (row / 8) * 32 + col; return self.memory.read(0x5800 + byte as u16); }; } return 0xFF; } /// make contention fn do_contention(&mut self) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention); } ///make contention + wait some clocks fn do_contention_and_wait(&mut self, wait_time: Clocks) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention + wait_time); } // check addr contention fn addr_is_contended(&self, addr: u16) -> bool { return if let Page::Ram(bank) = self.memory.get_page(addr) { self.machine.bank_is_contended(bank as usize) } else { false } } /// Returns early IO contention clocks fn io_contention_first(&mut self, port: u16) { if self.addr_is_contended(port) { self.do_contention(); }; self.wait_internal(Clocks(1)); } /// Returns late IO contention clocks fn io_contention_last(&mut self, port: u16) { if self.machine.port_is_contended(port) { self.do_contention_and_wait(Clocks(2)); } else { if self.addr_is_contended(port) { self.do_contention_and_wait(Clocks(1)); self.do_contention_and_wait(Clocks(1)); self.do_contention(); } else { self.wait_internal(Clocks(2)); } } } /// Starts a new frame fn new_frame(&mut self) { self.frame_clocks -= self.machine.specs().clocks_frame; self.canvas.new_frame(); self.border.new_frame(); self.mixer.new_frame(); } /// force clears all events pub fn clear_events(&mut self)
/// check events count pub fn no_events(&self) -> bool { self.events.is_empty() } /// Returns last event pub fn pop_event(&mut self) -> Option<Event> { self.events.receive_event() } /// Returns true if all frame clocks has been passed pub fn frames_count(&self) -> usize { self.passed_frames } pub fn reset_frame_counter(&mut self) { self.passed_frames = 0; } /// Returns current clocks from frame start pub fn clocks(&self) -> Clocks { self.frame_clocks } fn write_7ffd(&mut self, val: u8) { if!self.paging_enabled { return; } // remap top 16K of the ram self.memory.remap(3, Page::Ram(val & 0x07)); // third block is not pageable // second block is screen buffer, not pageable. but we need to change active buffer let new_screen_bank = if val & 0x08 == 0 { 5 } else { 7 }; self.canvas.switch_bank(new_screen_bank as usize); self.screen_bank = new_screen_bank; // remap ROM self.memory.remap(0, Page::Rom((val >> 4) & 0x01)); // check paging allow bit if val & 0x20!= 0 { self.paging_enabled = false; } } } impl Z80Bus for ZXController { /// we need to check different breakpoints like tape /// loading detection breakpoint fn pc_callback(&mut self, addr: u16) { // check mapped memory page at 0x0000.. 0x3FFF let check_fast_load = match self.machine { ZXMachine::Sinclair48K if self.memory.get_bank_type(0) == Page::Rom(0) => true, ZXMachine::Sinclair128K if self.memory.get_bank_type(0) == Page::Rom(1) => true, _ => false, }; if check_fast_load { // Tape LOAD/VERIFY if addr == ADDR_LD_BREAK { // Add event (Fast tape loading request) it must be executed // by emulator immediately self.events.send_event(Event::new(EventKind::FastTapeLoad, self.frame_clocks)); self.instant_event.set(); } } } /// read data without taking onto account contention fn read_internal(&mut self, addr: u16) -> u8 { self.memory.read(addr) } /// write data without taking onto account contention fn write_internal(&mut self, addr: u16, data: u8) { self.memory.write(addr, data); // if ram then compare bank to screen bank if let Page::Ram(bank) = self.memory.get_page(addr) { self.canvas.update(addr % PAGE_SIZE as u16, bank as usize, data); } } /// Cahnges internal state on clocks count change (emualtion processing) fn wait_internal(&mut self, clk: Clocks) { self.frame_clocks += clk; (*self.tape).process_clocks(clk); let mic = (*self.tape).current_bit(); self.mic = mic; let pos = self.frame_pos(); self.mixer.beeper.change_bit(self.mic | self.ear); self.mixer.process(pos); self.canvas.process_clocks(self.frame_clocks); if self.frame_clocks.count() >= self.machine.specs().clocks_frame { self.new_frame(); self.passed_frames += 1; } } // wait with memory request pin active fn wait_mreq(&mut self, addr: u16, clk: Clocks) { match self.machine { ZXMachine::Sinclair48K | ZXMachine::Sinclair128K=> { // contention in low 16k RAM if self.addr_is_contended(addr) { self.do_contention(); } } } self.wait_internal(clk); } /// wait without memory request pin active fn wait_no_mreq(&mut self, addr: u16, clk: Clocks) { // only for 48 K! self.wait_mreq(addr, clk); } /// read io from hardware fn read_io(&mut self, port: u16) -> u8 { // all contentions check self.io_contention_first(port); self.io_contention_last(port); // find out what we need to do let (h, _) = split_word(port); let output = if port & 0x0001 == 0 { // ULA port let mut tmp: u8 = 0xFF; for n in 0..8 { // if bit of row reset if ((h >> n) & 0x01) == 0 { tmp &= self.keyboard[n]; } } // invert bit 6 if mic_hw active; if self.mic { tmp ^= 0x40; } // 5 and 7 unused tmp } else if port & 0xC002 == 0xC000 { // AY regs self.mixer.ay.read() } else if self.kempston.is_some() && (port & 0x0020 == 0) { if let Some(ref joy) = self.kempston { joy.read() } else { unreachable!() } } else { self.floating_bus_value() }; // add one clock after operation self.wait_internal(Clocks(1)); output } /// write value to hardware port fn write_io(&mut self, port: u16, data: u8) { // first contention self.io_contention_first(port); // find active port if port & 0xC002 == 0xC000 { self.mixer.ay.select_reg(data); } else if port & 0xC002 == 0x8000 { self.mixer.ay.write(data); } else if port & 0x0001 == 0 { self.border_color = data & 0x07; self.border.set_border(self.frame_clocks, ZXColor::from_bits(data & 0x07)); self.mic = data & 0x08!= 0; self.ear = data & 0x10!= 0; self.mixer.beeper.change_bit(self.mic | self.ear); } else if (port & 0x8002 == 0) && (self.machine == ZXMachine::Sinclair128K) { self.write_7ffd(data); } // last contention after byte write self.io_contention_last(port); // add one clock after operation self.wait_internal(Clocks(1)); } /// value, requested during `INT0` interrupt fn read_interrupt(&mut self) -> u8 { 0xFF } /// checks system maskable interrupt pin state fn int_active(&self) -> bool { self.frame_clocks.count() % self.machine.specs().clocks_frame < self.machine.specs().interrupt_length } /// checks non-maskable interrupt pin state fn nmi_active(&self) -> bool { false } /// CPU calls it when RETI instruction was processed fn reti(&mut self) {} /// CPU calls when was being halted fn halt(&mut self, _: bool) {} /// checks instant events fn instant_event(&self) -> bool { self.instant_event.pick() } }
{ self.events.clear(); }
identifier_body
controller.rs
//! Contains ZX Spectrum System contrller (like ula or so) of emulator use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; // use almost everything :D use utils::{split_word, Clocks}; use utils::screen::*; use utils::events::*; use utils::InstantFlag; use z80::Z80Bus; use zx::{ZXMemory, RomType, RamType}; use zx::memory::{Page, PAGE_SIZE}; use zx::machine::ZXMachine; use zx::tape::*; use zx::ZXKey; use zx::screen::canvas::ZXCanvas; use zx::screen::border::ZXBorder; use zx::screen::colors::{ZXColor, ZXPalette}; use zx::roms::*; use zx::constants::*; use zx::sound::mixer::ZXMixer; use settings::RustzxSettings; use zx::joy::kempston::*; /// ZX System controller pub struct ZXController { // parts of ZX Spectum. pub machine: ZXMachine, pub memory: ZXMemory, pub canvas: ZXCanvas, pub tape: Box<ZXTape>, pub border: ZXBorder, pub kempston: Option<KempstonJoy>, //pub beeper: ZXBeeper, pub mixer: ZXMixer, pub keyboard: [u8; 8], // current border color border_color: u8, // clocls count from frame start frame_clocks: Clocks, // frames count, which passed during emulation invokation passed_frames: usize, // main event queue events: EventQueue, // flag, which signals emulator to break emulation and process last event immediately instant_event: InstantFlag, // audio in mic: bool, // audio out ear: bool, paging_enabled: bool, screen_bank: u8, } impl ZXController { /// Returns new ZXController from settings pub fn new(settings: &RustzxSettings) -> ZXController { let (memory, paging, screen_bank); match settings.machine { ZXMachine::Sinclair48K => { memory = ZXMemory::new(RomType::K16, RamType::K48); paging = false; screen_bank = 0; } ZXMachine::Sinclair128K => { memory = ZXMemory::new(RomType::K32, RamType::K128); paging = true; screen_bank = 5; } }; let kempston = if settings.kempston { Some(KempstonJoy::new()) } else { None }; let mut out = ZXController { machine: settings.machine, memory: memory, canvas: ZXCanvas::new(settings.machine), border: ZXBorder::new(settings.machine, ZXPalette::default()), kempston: kempston, mixer: ZXMixer::new(settings.beeper_enabled, settings.ay_enabled), keyboard: [0xFF; 8], border_color: 0x00, frame_clocks: Clocks(0), passed_frames: 0, tape: Box::new(Tap::new()), events: EventQueue::new(), instant_event: InstantFlag::new(false), mic: false, ear: false, paging_enabled: paging, screen_bank: screen_bank, }; out.mixer.ay.mode(settings.ay_mode); out.mixer.volume(settings.volume as f64 / 200.0); out } /// returns current frame emulation pos in percents fn frame_pos(&self) -> f64 { let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64; if val > 1.0 { 1.0 } else { val } } /// loads rom from file /// for 128-K machines path must contain ".0" in the tail /// and second rom bank will be loaded automatically pub fn load_rom(&mut self, path: impl AsRef<Path>) { match self.machine { // Single ROM file ZXMachine::Sinclair48K => { let mut rom = Vec::new(); File::open(path).ok().expect("[ERROR] ROM not found").read_to_end(&mut rom) .unwrap(); self.memory.load_rom(0, &rom); } // Two ROM's ZXMachine::Sinclair128K => { let mut rom0 = Vec::new(); let mut rom1 = Vec::new(); if!path.as_ref().extension().map_or(false, |e| e == "0") { println!("[Warning] ROM0 filename should end with.0"); } File::open(path.as_ref()).ok().expect("[ERROR] ROM0 not found").read_to_end(&mut rom0) .unwrap(); let mut second_path: PathBuf = path.as_ref().to_path_buf(); second_path.set_extension("1"); File::open(second_path).ok().expect("[ERROR] ROM1 not found").read_to_end(&mut rom1) .unwrap(); self.memory.load_rom(0, &rom0) .load_rom(1, &rom1); println!("ROM's Loaded"); } } } /// loads builted-in ROM pub fn load_default_rom(&mut self) { match self.machine { ZXMachine::Sinclair48K => { self.memory.load_rom(0, ROM_48K); } ZXMachine::Sinclair128K => { self.memory.load_rom(0, ROM_128K_0) .load_rom(1, ROM_128K_1); } } } /// Changes key state in controller pub fn send_key(&mut self, key: ZXKey, pressed: bool) { // TODO: Move row detection to ZXKey type let rownum = match key.half_port { 0xFE => Some(0), 0xFD => Some(1), 0xFB => Some(2), 0xF7 => Some(3), 0xEF => Some(4), 0xDF => Some(5), 0xBF => Some(6), 0x7F => Some(7), _ => None, }; if let Some(rownum) = rownum { self.keyboard[rownum] = self.keyboard[rownum] & (!key.mask); if!pressed { self.keyboard[rownum] |= key.mask; } } } /// Dumps memory space pub fn dump(&self) -> Vec<u8> { self.memory.dump() } /// Returns current bus floating value fn floating_bus_value(&self) -> u8 { let specs = self.machine.specs(); let clocks = self.frame_clocks; if clocks.count() < specs.clocks_first_pixel + 2 { return 0xFF; } let clocks = clocks.count() - (specs.clocks_first_pixel + 2); let row = clocks / specs.clocks_line; let clocks = clocks % specs.clocks_line; let col = (clocks / 8) * 2 + (clocks % 8) / 2; if row < CANVAS_HEIGHT && clocks < specs.clocks_screen_row - CLOCKS_PER_COL && ((clocks & 0x04) == 0)
return 0xFF; } /// make contention fn do_contention(&mut self) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention); } ///make contention + wait some clocks fn do_contention_and_wait(&mut self, wait_time: Clocks) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention + wait_time); } // check addr contention fn addr_is_contended(&self, addr: u16) -> bool { return if let Page::Ram(bank) = self.memory.get_page(addr) { self.machine.bank_is_contended(bank as usize) } else { false } } /// Returns early IO contention clocks fn io_contention_first(&mut self, port: u16) { if self.addr_is_contended(port) { self.do_contention(); }; self.wait_internal(Clocks(1)); } /// Returns late IO contention clocks fn io_contention_last(&mut self, port: u16) { if self.machine.port_is_contended(port) { self.do_contention_and_wait(Clocks(2)); } else { if self.addr_is_contended(port) { self.do_contention_and_wait(Clocks(1)); self.do_contention_and_wait(Clocks(1)); self.do_contention(); } else { self.wait_internal(Clocks(2)); } } } /// Starts a new frame fn new_frame(&mut self) { self.frame_clocks -= self.machine.specs().clocks_frame; self.canvas.new_frame(); self.border.new_frame(); self.mixer.new_frame(); } /// force clears all events pub fn clear_events(&mut self) { self.events.clear(); } /// check events count pub fn no_events(&self) -> bool { self.events.is_empty() } /// Returns last event pub fn pop_event(&mut self) -> Option<Event> { self.events.receive_event() } /// Returns true if all frame clocks has been passed pub fn frames_count(&self) -> usize { self.passed_frames } pub fn reset_frame_counter(&mut self) { self.passed_frames = 0; } /// Returns current clocks from frame start pub fn clocks(&self) -> Clocks { self.frame_clocks } fn write_7ffd(&mut self, val: u8) { if!self.paging_enabled { return; } // remap top 16K of the ram self.memory.remap(3, Page::Ram(val & 0x07)); // third block is not pageable // second block is screen buffer, not pageable. but we need to change active buffer let new_screen_bank = if val & 0x08 == 0 { 5 } else { 7 }; self.canvas.switch_bank(new_screen_bank as usize); self.screen_bank = new_screen_bank; // remap ROM self.memory.remap(0, Page::Rom((val >> 4) & 0x01)); // check paging allow bit if val & 0x20!= 0 { self.paging_enabled = false; } } } impl Z80Bus for ZXController { /// we need to check different breakpoints like tape /// loading detection breakpoint fn pc_callback(&mut self, addr: u16) { // check mapped memory page at 0x0000.. 0x3FFF let check_fast_load = match self.machine { ZXMachine::Sinclair48K if self.memory.get_bank_type(0) == Page::Rom(0) => true, ZXMachine::Sinclair128K if self.memory.get_bank_type(0) == Page::Rom(1) => true, _ => false, }; if check_fast_load { // Tape LOAD/VERIFY if addr == ADDR_LD_BREAK { // Add event (Fast tape loading request) it must be executed // by emulator immediately self.events.send_event(Event::new(EventKind::FastTapeLoad, self.frame_clocks)); self.instant_event.set(); } } } /// read data without taking onto account contention fn read_internal(&mut self, addr: u16) -> u8 { self.memory.read(addr) } /// write data without taking onto account contention fn write_internal(&mut self, addr: u16, data: u8) { self.memory.write(addr, data); // if ram then compare bank to screen bank if let Page::Ram(bank) = self.memory.get_page(addr) { self.canvas.update(addr % PAGE_SIZE as u16, bank as usize, data); } } /// Cahnges internal state on clocks count change (emualtion processing) fn wait_internal(&mut self, clk: Clocks) { self.frame_clocks += clk; (*self.tape).process_clocks(clk); let mic = (*self.tape).current_bit(); self.mic = mic; let pos = self.frame_pos(); self.mixer.beeper.change_bit(self.mic | self.ear); self.mixer.process(pos); self.canvas.process_clocks(self.frame_clocks); if self.frame_clocks.count() >= self.machine.specs().clocks_frame { self.new_frame(); self.passed_frames += 1; } } // wait with memory request pin active fn wait_mreq(&mut self, addr: u16, clk: Clocks) { match self.machine { ZXMachine::Sinclair48K | ZXMachine::Sinclair128K=> { // contention in low 16k RAM if self.addr_is_contended(addr) { self.do_contention(); } } } self.wait_internal(clk); } /// wait without memory request pin active fn wait_no_mreq(&mut self, addr: u16, clk: Clocks) { // only for 48 K! self.wait_mreq(addr, clk); } /// read io from hardware fn read_io(&mut self, port: u16) -> u8 { // all contentions check self.io_contention_first(port); self.io_contention_last(port); // find out what we need to do let (h, _) = split_word(port); let output = if port & 0x0001 == 0 { // ULA port let mut tmp: u8 = 0xFF; for n in 0..8 { // if bit of row reset if ((h >> n) & 0x01) == 0 { tmp &= self.keyboard[n]; } } // invert bit 6 if mic_hw active; if self.mic { tmp ^= 0x40; } // 5 and 7 unused tmp } else if port & 0xC002 == 0xC000 { // AY regs self.mixer.ay.read() } else if self.kempston.is_some() && (port & 0x0020 == 0) { if let Some(ref joy) = self.kempston { joy.read() } else { unreachable!() } } else { self.floating_bus_value() }; // add one clock after operation self.wait_internal(Clocks(1)); output } /// write value to hardware port fn write_io(&mut self, port: u16, data: u8) { // first contention self.io_contention_first(port); // find active port if port & 0xC002 == 0xC000 { self.mixer.ay.select_reg(data); } else if port & 0xC002 == 0x8000 { self.mixer.ay.write(data); } else if port & 0x0001 == 0 { self.border_color = data & 0x07; self.border.set_border(self.frame_clocks, ZXColor::from_bits(data & 0x07)); self.mic = data & 0x08!= 0; self.ear = data & 0x10!= 0; self.mixer.beeper.change_bit(self.mic | self.ear); } else if (port & 0x8002 == 0) && (self.machine == ZXMachine::Sinclair128K) { self.write_7ffd(data); } // last contention after byte write self.io_contention_last(port); // add one clock after operation self.wait_internal(Clocks(1)); } /// value, requested during `INT0` interrupt fn read_interrupt(&mut self) -> u8 { 0xFF } /// checks system maskable interrupt pin state fn int_active(&self) -> bool { self.frame_clocks.count() % self.machine.specs().clocks_frame < self.machine.specs().interrupt_length } /// checks non-maskable interrupt pin state fn nmi_active(&self) -> bool { false } /// CPU calls it when RETI instruction was processed fn reti(&mut self) {} /// CPU calls when was being halted fn halt(&mut self, _: bool) {} /// checks instant events fn instant_event(&self) -> bool { self.instant_event.pick() } }
{ if clocks % 2 == 0 { return self.memory.read(bitmap_line_addr(row) + col as u16); } else { let byte = (row / 8) * 32 + col; return self.memory.read(0x5800 + byte as u16); }; }
conditional_block
controller.rs
//! Contains ZX Spectrum System contrller (like ula or so) of emulator use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; // use almost everything :D use utils::{split_word, Clocks}; use utils::screen::*; use utils::events::*; use utils::InstantFlag; use z80::Z80Bus; use zx::{ZXMemory, RomType, RamType}; use zx::memory::{Page, PAGE_SIZE}; use zx::machine::ZXMachine; use zx::tape::*; use zx::ZXKey; use zx::screen::canvas::ZXCanvas; use zx::screen::border::ZXBorder; use zx::screen::colors::{ZXColor, ZXPalette}; use zx::roms::*; use zx::constants::*; use zx::sound::mixer::ZXMixer; use settings::RustzxSettings; use zx::joy::kempston::*; /// ZX System controller pub struct ZXController { // parts of ZX Spectum. pub machine: ZXMachine, pub memory: ZXMemory, pub canvas: ZXCanvas, pub tape: Box<ZXTape>, pub border: ZXBorder, pub kempston: Option<KempstonJoy>, //pub beeper: ZXBeeper, pub mixer: ZXMixer, pub keyboard: [u8; 8], // current border color border_color: u8, // clocls count from frame start frame_clocks: Clocks, // frames count, which passed during emulation invokation passed_frames: usize, // main event queue events: EventQueue, // flag, which signals emulator to break emulation and process last event immediately instant_event: InstantFlag, // audio in mic: bool, // audio out ear: bool, paging_enabled: bool, screen_bank: u8, } impl ZXController { /// Returns new ZXController from settings pub fn new(settings: &RustzxSettings) -> ZXController { let (memory, paging, screen_bank); match settings.machine { ZXMachine::Sinclair48K => { memory = ZXMemory::new(RomType::K16, RamType::K48); paging = false; screen_bank = 0; } ZXMachine::Sinclair128K => { memory = ZXMemory::new(RomType::K32, RamType::K128); paging = true; screen_bank = 5; } }; let kempston = if settings.kempston { Some(KempstonJoy::new()) } else { None }; let mut out = ZXController { machine: settings.machine, memory: memory, canvas: ZXCanvas::new(settings.machine), border: ZXBorder::new(settings.machine, ZXPalette::default()), kempston: kempston, mixer: ZXMixer::new(settings.beeper_enabled, settings.ay_enabled), keyboard: [0xFF; 8], border_color: 0x00, frame_clocks: Clocks(0), passed_frames: 0, tape: Box::new(Tap::new()), events: EventQueue::new(), instant_event: InstantFlag::new(false), mic: false, ear: false, paging_enabled: paging, screen_bank: screen_bank, }; out.mixer.ay.mode(settings.ay_mode); out.mixer.volume(settings.volume as f64 / 200.0); out } /// returns current frame emulation pos in percents fn frame_pos(&self) -> f64 { let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64; if val > 1.0 { 1.0 } else { val } } /// loads rom from file /// for 128-K machines path must contain ".0" in the tail /// and second rom bank will be loaded automatically pub fn load_rom(&mut self, path: impl AsRef<Path>) { match self.machine { // Single ROM file ZXMachine::Sinclair48K => { let mut rom = Vec::new(); File::open(path).ok().expect("[ERROR] ROM not found").read_to_end(&mut rom) .unwrap(); self.memory.load_rom(0, &rom); } // Two ROM's ZXMachine::Sinclair128K => { let mut rom0 = Vec::new(); let mut rom1 = Vec::new(); if!path.as_ref().extension().map_or(false, |e| e == "0") { println!("[Warning] ROM0 filename should end with.0"); } File::open(path.as_ref()).ok().expect("[ERROR] ROM0 not found").read_to_end(&mut rom0) .unwrap(); let mut second_path: PathBuf = path.as_ref().to_path_buf(); second_path.set_extension("1"); File::open(second_path).ok().expect("[ERROR] ROM1 not found").read_to_end(&mut rom1) .unwrap(); self.memory.load_rom(0, &rom0) .load_rom(1, &rom1); println!("ROM's Loaded"); } } } /// loads builted-in ROM pub fn load_default_rom(&mut self) { match self.machine { ZXMachine::Sinclair48K => { self.memory.load_rom(0, ROM_48K); } ZXMachine::Sinclair128K => { self.memory.load_rom(0, ROM_128K_0) .load_rom(1, ROM_128K_1); } } } /// Changes key state in controller pub fn send_key(&mut self, key: ZXKey, pressed: bool) { // TODO: Move row detection to ZXKey type let rownum = match key.half_port { 0xFE => Some(0), 0xFD => Some(1), 0xFB => Some(2), 0xF7 => Some(3), 0xEF => Some(4), 0xDF => Some(5), 0xBF => Some(6), 0x7F => Some(7), _ => None, }; if let Some(rownum) = rownum { self.keyboard[rownum] = self.keyboard[rownum] & (!key.mask); if!pressed { self.keyboard[rownum] |= key.mask; } } } /// Dumps memory space pub fn dump(&self) -> Vec<u8> { self.memory.dump() } /// Returns current bus floating value fn floating_bus_value(&self) -> u8 { let specs = self.machine.specs(); let clocks = self.frame_clocks; if clocks.count() < specs.clocks_first_pixel + 2 { return 0xFF; } let clocks = clocks.count() - (specs.clocks_first_pixel + 2); let row = clocks / specs.clocks_line; let clocks = clocks % specs.clocks_line; let col = (clocks / 8) * 2 + (clocks % 8) / 2; if row < CANVAS_HEIGHT && clocks < specs.clocks_screen_row - CLOCKS_PER_COL && ((clocks & 0x04) == 0) { if clocks % 2 == 0 { return self.memory.read(bitmap_line_addr(row) + col as u16); } else { let byte = (row / 8) * 32 + col; return self.memory.read(0x5800 + byte as u16); }; } return 0xFF; } /// make contention fn do_contention(&mut self) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention); } ///make contention + wait some clocks fn do_contention_and_wait(&mut self, wait_time: Clocks) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention + wait_time); } // check addr contention fn addr_is_contended(&self, addr: u16) -> bool { return if let Page::Ram(bank) = self.memory.get_page(addr) { self.machine.bank_is_contended(bank as usize) } else { false } } /// Returns early IO contention clocks fn
(&mut self, port: u16) { if self.addr_is_contended(port) { self.do_contention(); }; self.wait_internal(Clocks(1)); } /// Returns late IO contention clocks fn io_contention_last(&mut self, port: u16) { if self.machine.port_is_contended(port) { self.do_contention_and_wait(Clocks(2)); } else { if self.addr_is_contended(port) { self.do_contention_and_wait(Clocks(1)); self.do_contention_and_wait(Clocks(1)); self.do_contention(); } else { self.wait_internal(Clocks(2)); } } } /// Starts a new frame fn new_frame(&mut self) { self.frame_clocks -= self.machine.specs().clocks_frame; self.canvas.new_frame(); self.border.new_frame(); self.mixer.new_frame(); } /// force clears all events pub fn clear_events(&mut self) { self.events.clear(); } /// check events count pub fn no_events(&self) -> bool { self.events.is_empty() } /// Returns last event pub fn pop_event(&mut self) -> Option<Event> { self.events.receive_event() } /// Returns true if all frame clocks has been passed pub fn frames_count(&self) -> usize { self.passed_frames } pub fn reset_frame_counter(&mut self) { self.passed_frames = 0; } /// Returns current clocks from frame start pub fn clocks(&self) -> Clocks { self.frame_clocks } fn write_7ffd(&mut self, val: u8) { if!self.paging_enabled { return; } // remap top 16K of the ram self.memory.remap(3, Page::Ram(val & 0x07)); // third block is not pageable // second block is screen buffer, not pageable. but we need to change active buffer let new_screen_bank = if val & 0x08 == 0 { 5 } else { 7 }; self.canvas.switch_bank(new_screen_bank as usize); self.screen_bank = new_screen_bank; // remap ROM self.memory.remap(0, Page::Rom((val >> 4) & 0x01)); // check paging allow bit if val & 0x20!= 0 { self.paging_enabled = false; } } } impl Z80Bus for ZXController { /// we need to check different breakpoints like tape /// loading detection breakpoint fn pc_callback(&mut self, addr: u16) { // check mapped memory page at 0x0000.. 0x3FFF let check_fast_load = match self.machine { ZXMachine::Sinclair48K if self.memory.get_bank_type(0) == Page::Rom(0) => true, ZXMachine::Sinclair128K if self.memory.get_bank_type(0) == Page::Rom(1) => true, _ => false, }; if check_fast_load { // Tape LOAD/VERIFY if addr == ADDR_LD_BREAK { // Add event (Fast tape loading request) it must be executed // by emulator immediately self.events.send_event(Event::new(EventKind::FastTapeLoad, self.frame_clocks)); self.instant_event.set(); } } } /// read data without taking onto account contention fn read_internal(&mut self, addr: u16) -> u8 { self.memory.read(addr) } /// write data without taking onto account contention fn write_internal(&mut self, addr: u16, data: u8) { self.memory.write(addr, data); // if ram then compare bank to screen bank if let Page::Ram(bank) = self.memory.get_page(addr) { self.canvas.update(addr % PAGE_SIZE as u16, bank as usize, data); } } /// Cahnges internal state on clocks count change (emualtion processing) fn wait_internal(&mut self, clk: Clocks) { self.frame_clocks += clk; (*self.tape).process_clocks(clk); let mic = (*self.tape).current_bit(); self.mic = mic; let pos = self.frame_pos(); self.mixer.beeper.change_bit(self.mic | self.ear); self.mixer.process(pos); self.canvas.process_clocks(self.frame_clocks); if self.frame_clocks.count() >= self.machine.specs().clocks_frame { self.new_frame(); self.passed_frames += 1; } } // wait with memory request pin active fn wait_mreq(&mut self, addr: u16, clk: Clocks) { match self.machine { ZXMachine::Sinclair48K | ZXMachine::Sinclair128K=> { // contention in low 16k RAM if self.addr_is_contended(addr) { self.do_contention(); } } } self.wait_internal(clk); } /// wait without memory request pin active fn wait_no_mreq(&mut self, addr: u16, clk: Clocks) { // only for 48 K! self.wait_mreq(addr, clk); } /// read io from hardware fn read_io(&mut self, port: u16) -> u8 { // all contentions check self.io_contention_first(port); self.io_contention_last(port); // find out what we need to do let (h, _) = split_word(port); let output = if port & 0x0001 == 0 { // ULA port let mut tmp: u8 = 0xFF; for n in 0..8 { // if bit of row reset if ((h >> n) & 0x01) == 0 { tmp &= self.keyboard[n]; } } // invert bit 6 if mic_hw active; if self.mic { tmp ^= 0x40; } // 5 and 7 unused tmp } else if port & 0xC002 == 0xC000 { // AY regs self.mixer.ay.read() } else if self.kempston.is_some() && (port & 0x0020 == 0) { if let Some(ref joy) = self.kempston { joy.read() } else { unreachable!() } } else { self.floating_bus_value() }; // add one clock after operation self.wait_internal(Clocks(1)); output } /// write value to hardware port fn write_io(&mut self, port: u16, data: u8) { // first contention self.io_contention_first(port); // find active port if port & 0xC002 == 0xC000 { self.mixer.ay.select_reg(data); } else if port & 0xC002 == 0x8000 { self.mixer.ay.write(data); } else if port & 0x0001 == 0 { self.border_color = data & 0x07; self.border.set_border(self.frame_clocks, ZXColor::from_bits(data & 0x07)); self.mic = data & 0x08!= 0; self.ear = data & 0x10!= 0; self.mixer.beeper.change_bit(self.mic | self.ear); } else if (port & 0x8002 == 0) && (self.machine == ZXMachine::Sinclair128K) { self.write_7ffd(data); } // last contention after byte write self.io_contention_last(port); // add one clock after operation self.wait_internal(Clocks(1)); } /// value, requested during `INT0` interrupt fn read_interrupt(&mut self) -> u8 { 0xFF } /// checks system maskable interrupt pin state fn int_active(&self) -> bool { self.frame_clocks.count() % self.machine.specs().clocks_frame < self.machine.specs().interrupt_length } /// checks non-maskable interrupt pin state fn nmi_active(&self) -> bool { false } /// CPU calls it when RETI instruction was processed fn reti(&mut self) {} /// CPU calls when was being halted fn halt(&mut self, _: bool) {} /// checks instant events fn instant_event(&self) -> bool { self.instant_event.pick() } }
io_contention_first
identifier_name
storage.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, workspace_builder, workspace_builder::workspace_root, }; use anyhow::{bail, Result}; use backup_cli::metadata::view::BackupStorageState; use diem_sdk::{ client::BlockingClient, transaction_builder::TransactionFactory, types::LocalAccount, }; use diem_temppath::TempPath; use diem_types::{transaction::Version, waypoint::Waypoint}; use forge::{NodeExt, Swarm, SwarmExt}; use rand::random; use std::{ fs, path::Path, process::Command, time::{Duration, Instant}, }; #[test] fn test_db_restore() { // pre-build tools workspace_builder::get_bin("db-backup"); workspace_builder::get_bin("db-restore"); workspace_builder::get_bin("db-backup-verify"); let mut swarm = new_local_swarm(4); let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>(); let client_1 = swarm .validator(validator_peer_ids[1]) .unwrap() .json_rpc_client(); let transaction_factory = swarm.chain_info().transaction_factory(); // set up: two accounts, a lot of money let mut account_0 = create_and_fund_account(&mut swarm, 1000000); let account_1 = create_and_fund_account(&mut swarm, 1000000); transfer_coins( &client_1, &transaction_factory, &mut account_0, &account_1, 1, ); let mut expected_balance_0 = 999999; let mut expected_balance_1 = 1000001; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); // make a backup from node 1 let node1_config = swarm.validator(validator_peer_ids[1]).unwrap().config(); let backup_path = db_backup( node1_config.storage.backup_service_address.port(), 1, 50, 20, 40, &[], ); // take down node 0 let node_to_restart = validator_peer_ids[0]; swarm.validator_mut(node_to_restart).unwrap().stop(); // nuke db let node0_config_path = swarm.validator(node_to_restart).unwrap().config_path(); let mut node0_config = swarm.validator(node_to_restart).unwrap().config().clone(); let genesis_waypoint = node0_config.base.waypoint.genesis_waypoint(); insert_waypoint(&mut node0_config, genesis_waypoint); node0_config.save(node0_config_path).unwrap(); let db_dir = node0_config.storage.dir(); fs::remove_dir_all(db_dir.join("diemdb")).unwrap(); fs::remove_dir_all(db_dir.join("consensusdb")).unwrap(); // restore db from backup db_restore(backup_path.path(), db_dir.as_path(), &[]); { transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); } // start node 0 on top of restored db swarm .validator_mut(node_to_restart) .unwrap() .start() .unwrap(); swarm .validator_mut(node_to_restart) .unwrap() .wait_until_healthy(Instant::now() + Duration::from_secs(10)) .unwrap(); // verify it's caught up swarm .wait_for_all_nodes_to_catchup(Instant::now() + Duration::from_secs(60)) .unwrap(); let client_0 = swarm.validator(node_to_restart).unwrap().json_rpc_client(); assert_balance(&client_0, &account_0, expected_balance_0); assert_balance(&client_0, &account_1, expected_balance_1); } fn db_backup_verify(backup_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup-verify"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if!output.status.success() { panic!("db-backup-verify failed, output: {:?}", output); } println!("Backup verified in {} seconds.", now.elapsed().as_secs()); } fn wait_for_backups( target_epoch: u64, target_version: u64, now: Instant, bin_path: &Path, metadata_cache_path: &Path, backup_path: &Path, trusted_waypoints: &[Waypoint], ) -> Result<()> { for _ in 0..60 { // the verify should always succeed. db_backup_verify(backup_path, trusted_waypoints); let output = Command::new(bin_path) .current_dir(workspace_root()) .args(&[ "one-shot", "query", "backup-storage-state", "--metadata-cache-dir", metadata_cache_path.to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .output()? .stdout; let state: BackupStorageState = std::str::from_utf8(&output)?.parse()?; if state.latest_epoch_ending_epoch.is_some() && state.latest_transaction_version.is_some() && state.latest_state_snapshot_version.is_some() && state.latest_epoch_ending_epoch.unwrap() >= target_epoch && state.latest_transaction_version.unwrap() >= target_version { println!("Backup created in {} seconds.", now.elapsed().as_secs()); return Ok(()); } println!("Backup storage state: {}", state); std::thread::sleep(Duration::from_secs(1)); } bail!("Failed to create backup."); } pub(crate) fn db_backup( backup_service_port: u16, target_epoch: u64, target_version: Version, transaction_batch_size: usize, state_snapshot_interval: usize, trusted_waypoints: &[Waypoint], ) -> TempPath { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup"); let metadata_cache_path1 = TempPath::new(); let metadata_cache_path2 = TempPath::new(); let backup_path = TempPath::new(); metadata_cache_path1.create_as_dir().unwrap(); metadata_cache_path2.create_as_dir().unwrap(); backup_path.create_as_dir().unwrap(); // spawn the backup coordinator let mut backup_coordinator = Command::new(bin_path.as_path()) .current_dir(workspace_root()) .args(&[ "coordinator", "run", "--backup-service-address", &format!("http://localhost:{}", backup_service_port), "--transaction-batch-size", &transaction_batch_size.to_string(), "--state-snapshot-interval", &state_snapshot_interval.to_string(), "--metadata-cache-dir", metadata_cache_path1.path().to_str().unwrap(), "local-fs", "--dir", backup_path.path().to_str().unwrap(), ]) .spawn() .unwrap(); // watch the backup storage, wait for it to reach target epoch and version let wait_res = wait_for_backups( target_epoch, target_version, now, bin_path.as_path(), metadata_cache_path2.path(), backup_path.path(), trusted_waypoints, ); backup_coordinator.kill().unwrap(); wait_res.unwrap(); backup_path } pub(crate) fn db_restore(backup_path: &Path, db_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-restore"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--target-db-dir", db_path.to_str().unwrap(), "auto", "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if!output.status.success() { panic!("db-restore failed, output: {:?}", output); } println!("Backup restored in {} seconds.", now.elapsed().as_secs()); } fn transfer_and_reconfig( client: &BlockingClient, transaction_factory: &TransactionFactory, root_account: &mut LocalAccount, account0: &mut LocalAccount, account1: &LocalAccount, transfers: usize, ) -> Result<()> { for _ in 0..transfers { if random::<u16>() % 10 == 0
transfer_coins(client, transaction_factory, account0, account1, 1); } Ok(()) }
{ let current_version = client.get_metadata()?.into_inner().diem_version.unwrap(); let txn = root_account.sign_with_transaction_builder( transaction_factory.update_diem_version(0, current_version + 1), ); client.submit(&txn)?; client.wait_for_signed_transaction(&txn, None, None)?; println!("Changing diem version to {}", current_version + 1,); }
conditional_block
storage.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, workspace_builder, workspace_builder::workspace_root, }; use anyhow::{bail, Result}; use backup_cli::metadata::view::BackupStorageState; use diem_sdk::{ client::BlockingClient, transaction_builder::TransactionFactory, types::LocalAccount, }; use diem_temppath::TempPath; use diem_types::{transaction::Version, waypoint::Waypoint}; use forge::{NodeExt, Swarm, SwarmExt}; use rand::random; use std::{ fs, path::Path, process::Command, time::{Duration, Instant}, }; #[test] fn test_db_restore() { // pre-build tools workspace_builder::get_bin("db-backup"); workspace_builder::get_bin("db-restore"); workspace_builder::get_bin("db-backup-verify"); let mut swarm = new_local_swarm(4); let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>(); let client_1 = swarm .validator(validator_peer_ids[1]) .unwrap() .json_rpc_client(); let transaction_factory = swarm.chain_info().transaction_factory(); // set up: two accounts, a lot of money let mut account_0 = create_and_fund_account(&mut swarm, 1000000); let account_1 = create_and_fund_account(&mut swarm, 1000000); transfer_coins( &client_1, &transaction_factory, &mut account_0, &account_1, 1, ); let mut expected_balance_0 = 999999; let mut expected_balance_1 = 1000001; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); // make a backup from node 1 let node1_config = swarm.validator(validator_peer_ids[1]).unwrap().config(); let backup_path = db_backup( node1_config.storage.backup_service_address.port(), 1, 50, 20, 40, &[], ); // take down node 0 let node_to_restart = validator_peer_ids[0]; swarm.validator_mut(node_to_restart).unwrap().stop(); // nuke db let node0_config_path = swarm.validator(node_to_restart).unwrap().config_path(); let mut node0_config = swarm.validator(node_to_restart).unwrap().config().clone(); let genesis_waypoint = node0_config.base.waypoint.genesis_waypoint(); insert_waypoint(&mut node0_config, genesis_waypoint); node0_config.save(node0_config_path).unwrap(); let db_dir = node0_config.storage.dir(); fs::remove_dir_all(db_dir.join("diemdb")).unwrap(); fs::remove_dir_all(db_dir.join("consensusdb")).unwrap(); // restore db from backup db_restore(backup_path.path(), db_dir.as_path(), &[]); { transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); } // start node 0 on top of restored db swarm .validator_mut(node_to_restart) .unwrap() .start() .unwrap(); swarm .validator_mut(node_to_restart) .unwrap() .wait_until_healthy(Instant::now() + Duration::from_secs(10)) .unwrap(); // verify it's caught up swarm .wait_for_all_nodes_to_catchup(Instant::now() + Duration::from_secs(60)) .unwrap(); let client_0 = swarm.validator(node_to_restart).unwrap().json_rpc_client(); assert_balance(&client_0, &account_0, expected_balance_0); assert_balance(&client_0, &account_1, expected_balance_1); } fn db_backup_verify(backup_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup-verify"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if!output.status.success() { panic!("db-backup-verify failed, output: {:?}", output); } println!("Backup verified in {} seconds.", now.elapsed().as_secs()); } fn wait_for_backups( target_epoch: u64, target_version: u64, now: Instant, bin_path: &Path, metadata_cache_path: &Path, backup_path: &Path, trusted_waypoints: &[Waypoint], ) -> Result<()> { for _ in 0..60 { // the verify should always succeed. db_backup_verify(backup_path, trusted_waypoints); let output = Command::new(bin_path) .current_dir(workspace_root()) .args(&[ "one-shot", "query", "backup-storage-state", "--metadata-cache-dir", metadata_cache_path.to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .output()? .stdout; let state: BackupStorageState = std::str::from_utf8(&output)?.parse()?; if state.latest_epoch_ending_epoch.is_some() && state.latest_transaction_version.is_some() && state.latest_state_snapshot_version.is_some() && state.latest_epoch_ending_epoch.unwrap() >= target_epoch && state.latest_transaction_version.unwrap() >= target_version { println!("Backup created in {} seconds.", now.elapsed().as_secs()); return Ok(()); } println!("Backup storage state: {}", state); std::thread::sleep(Duration::from_secs(1)); } bail!("Failed to create backup."); } pub(crate) fn db_backup( backup_service_port: u16, target_epoch: u64, target_version: Version, transaction_batch_size: usize, state_snapshot_interval: usize, trusted_waypoints: &[Waypoint], ) -> TempPath
&transaction_batch_size.to_string(), "--state-snapshot-interval", &state_snapshot_interval.to_string(), "--metadata-cache-dir", metadata_cache_path1.path().to_str().unwrap(), "local-fs", "--dir", backup_path.path().to_str().unwrap(), ]) .spawn() .unwrap(); // watch the backup storage, wait for it to reach target epoch and version let wait_res = wait_for_backups( target_epoch, target_version, now, bin_path.as_path(), metadata_cache_path2.path(), backup_path.path(), trusted_waypoints, ); backup_coordinator.kill().unwrap(); wait_res.unwrap(); backup_path } pub(crate) fn db_restore(backup_path: &Path, db_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-restore"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--target-db-dir", db_path.to_str().unwrap(), "auto", "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if!output.status.success() { panic!("db-restore failed, output: {:?}", output); } println!("Backup restored in {} seconds.", now.elapsed().as_secs()); } fn transfer_and_reconfig( client: &BlockingClient, transaction_factory: &TransactionFactory, root_account: &mut LocalAccount, account0: &mut LocalAccount, account1: &LocalAccount, transfers: usize, ) -> Result<()> { for _ in 0..transfers { if random::<u16>() % 10 == 0 { let current_version = client.get_metadata()?.into_inner().diem_version.unwrap(); let txn = root_account.sign_with_transaction_builder( transaction_factory.update_diem_version(0, current_version + 1), ); client.submit(&txn)?; client.wait_for_signed_transaction(&txn, None, None)?; println!("Changing diem version to {}", current_version + 1,); } transfer_coins(client, transaction_factory, account0, account1, 1); } Ok(()) }
{ let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup"); let metadata_cache_path1 = TempPath::new(); let metadata_cache_path2 = TempPath::new(); let backup_path = TempPath::new(); metadata_cache_path1.create_as_dir().unwrap(); metadata_cache_path2.create_as_dir().unwrap(); backup_path.create_as_dir().unwrap(); // spawn the backup coordinator let mut backup_coordinator = Command::new(bin_path.as_path()) .current_dir(workspace_root()) .args(&[ "coordinator", "run", "--backup-service-address", &format!("http://localhost:{}", backup_service_port), "--transaction-batch-size",
identifier_body
storage.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, workspace_builder, workspace_builder::workspace_root, }; use anyhow::{bail, Result}; use backup_cli::metadata::view::BackupStorageState; use diem_sdk::{ client::BlockingClient, transaction_builder::TransactionFactory, types::LocalAccount, }; use diem_temppath::TempPath; use diem_types::{transaction::Version, waypoint::Waypoint}; use forge::{NodeExt, Swarm, SwarmExt}; use rand::random; use std::{ fs, path::Path, process::Command, time::{Duration, Instant}, }; #[test] fn test_db_restore() { // pre-build tools workspace_builder::get_bin("db-backup"); workspace_builder::get_bin("db-restore"); workspace_builder::get_bin("db-backup-verify"); let mut swarm = new_local_swarm(4); let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>(); let client_1 = swarm .validator(validator_peer_ids[1]) .unwrap() .json_rpc_client(); let transaction_factory = swarm.chain_info().transaction_factory(); // set up: two accounts, a lot of money let mut account_0 = create_and_fund_account(&mut swarm, 1000000); let account_1 = create_and_fund_account(&mut swarm, 1000000); transfer_coins( &client_1, &transaction_factory, &mut account_0, &account_1, 1, ); let mut expected_balance_0 = 999999; let mut expected_balance_1 = 1000001; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); // make a backup from node 1 let node1_config = swarm.validator(validator_peer_ids[1]).unwrap().config(); let backup_path = db_backup( node1_config.storage.backup_service_address.port(), 1, 50, 20, 40, &[], ); // take down node 0 let node_to_restart = validator_peer_ids[0]; swarm.validator_mut(node_to_restart).unwrap().stop(); // nuke db let node0_config_path = swarm.validator(node_to_restart).unwrap().config_path(); let mut node0_config = swarm.validator(node_to_restart).unwrap().config().clone(); let genesis_waypoint = node0_config.base.waypoint.genesis_waypoint(); insert_waypoint(&mut node0_config, genesis_waypoint); node0_config.save(node0_config_path).unwrap(); let db_dir = node0_config.storage.dir(); fs::remove_dir_all(db_dir.join("diemdb")).unwrap(); fs::remove_dir_all(db_dir.join("consensusdb")).unwrap(); // restore db from backup db_restore(backup_path.path(), db_dir.as_path(), &[]); { transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); } // start node 0 on top of restored db swarm .validator_mut(node_to_restart) .unwrap() .start() .unwrap(); swarm .validator_mut(node_to_restart) .unwrap() .wait_until_healthy(Instant::now() + Duration::from_secs(10)) .unwrap(); // verify it's caught up swarm .wait_for_all_nodes_to_catchup(Instant::now() + Duration::from_secs(60)) .unwrap(); let client_0 = swarm.validator(node_to_restart).unwrap().json_rpc_client(); assert_balance(&client_0, &account_0, expected_balance_0); assert_balance(&client_0, &account_1, expected_balance_1); } fn db_backup_verify(backup_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup-verify"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if!output.status.success() { panic!("db-backup-verify failed, output: {:?}", output); } println!("Backup verified in {} seconds.", now.elapsed().as_secs()); } fn wait_for_backups( target_epoch: u64, target_version: u64, now: Instant, bin_path: &Path, metadata_cache_path: &Path, backup_path: &Path, trusted_waypoints: &[Waypoint], ) -> Result<()> { for _ in 0..60 { // the verify should always succeed. db_backup_verify(backup_path, trusted_waypoints); let output = Command::new(bin_path) .current_dir(workspace_root()) .args(&[ "one-shot", "query", "backup-storage-state", "--metadata-cache-dir", metadata_cache_path.to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .output()? .stdout; let state: BackupStorageState = std::str::from_utf8(&output)?.parse()?; if state.latest_epoch_ending_epoch.is_some() && state.latest_transaction_version.is_some() && state.latest_state_snapshot_version.is_some() && state.latest_epoch_ending_epoch.unwrap() >= target_epoch && state.latest_transaction_version.unwrap() >= target_version { println!("Backup created in {} seconds.", now.elapsed().as_secs()); return Ok(()); } println!("Backup storage state: {}", state); std::thread::sleep(Duration::from_secs(1)); } bail!("Failed to create backup."); } pub(crate) fn db_backup( backup_service_port: u16, target_epoch: u64, target_version: Version, transaction_batch_size: usize, state_snapshot_interval: usize, trusted_waypoints: &[Waypoint], ) -> TempPath { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup"); let metadata_cache_path1 = TempPath::new(); let metadata_cache_path2 = TempPath::new(); let backup_path = TempPath::new(); metadata_cache_path1.create_as_dir().unwrap(); metadata_cache_path2.create_as_dir().unwrap(); backup_path.create_as_dir().unwrap(); // spawn the backup coordinator let mut backup_coordinator = Command::new(bin_path.as_path()) .current_dir(workspace_root()) .args(&[ "coordinator", "run", "--backup-service-address", &format!("http://localhost:{}", backup_service_port), "--transaction-batch-size", &transaction_batch_size.to_string(), "--state-snapshot-interval", &state_snapshot_interval.to_string(), "--metadata-cache-dir", metadata_cache_path1.path().to_str().unwrap(), "local-fs", "--dir", backup_path.path().to_str().unwrap(), ]) .spawn() .unwrap(); // watch the backup storage, wait for it to reach target epoch and version let wait_res = wait_for_backups( target_epoch, target_version, now, bin_path.as_path(), metadata_cache_path2.path(), backup_path.path(), trusted_waypoints, ); backup_coordinator.kill().unwrap(); wait_res.unwrap(); backup_path } pub(crate) fn db_restore(backup_path: &Path, db_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-restore"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--target-db-dir", db_path.to_str().unwrap(), "auto", "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if!output.status.success() { panic!("db-restore failed, output: {:?}", output); } println!("Backup restored in {} seconds.", now.elapsed().as_secs()); } fn
( client: &BlockingClient, transaction_factory: &TransactionFactory, root_account: &mut LocalAccount, account0: &mut LocalAccount, account1: &LocalAccount, transfers: usize, ) -> Result<()> { for _ in 0..transfers { if random::<u16>() % 10 == 0 { let current_version = client.get_metadata()?.into_inner().diem_version.unwrap(); let txn = root_account.sign_with_transaction_builder( transaction_factory.update_diem_version(0, current_version + 1), ); client.submit(&txn)?; client.wait_for_signed_transaction(&txn, None, None)?; println!("Changing diem version to {}", current_version + 1,); } transfer_coins(client, transaction_factory, account0, account1, 1); } Ok(()) }
transfer_and_reconfig
identifier_name
storage.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, workspace_builder, workspace_builder::workspace_root, }; use anyhow::{bail, Result}; use backup_cli::metadata::view::BackupStorageState; use diem_sdk::{ client::BlockingClient, transaction_builder::TransactionFactory, types::LocalAccount, }; use diem_temppath::TempPath; use diem_types::{transaction::Version, waypoint::Waypoint}; use forge::{NodeExt, Swarm, SwarmExt}; use rand::random; use std::{ fs, path::Path, process::Command, time::{Duration, Instant}, }; #[test] fn test_db_restore() { // pre-build tools workspace_builder::get_bin("db-backup"); workspace_builder::get_bin("db-restore"); workspace_builder::get_bin("db-backup-verify"); let mut swarm = new_local_swarm(4); let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>(); let client_1 = swarm .validator(validator_peer_ids[1]) .unwrap() .json_rpc_client(); let transaction_factory = swarm.chain_info().transaction_factory(); // set up: two accounts, a lot of money let mut account_0 = create_and_fund_account(&mut swarm, 1000000); let account_1 = create_and_fund_account(&mut swarm, 1000000); transfer_coins( &client_1, &transaction_factory, &mut account_0, &account_1, 1, ); let mut expected_balance_0 = 999999; let mut expected_balance_1 = 1000001; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); // make a backup from node 1 let node1_config = swarm.validator(validator_peer_ids[1]).unwrap().config(); let backup_path = db_backup( node1_config.storage.backup_service_address.port(), 1, 50, 20, 40, &[], ); // take down node 0 let node_to_restart = validator_peer_ids[0]; swarm.validator_mut(node_to_restart).unwrap().stop(); // nuke db let node0_config_path = swarm.validator(node_to_restart).unwrap().config_path(); let mut node0_config = swarm.validator(node_to_restart).unwrap().config().clone(); let genesis_waypoint = node0_config.base.waypoint.genesis_waypoint(); insert_waypoint(&mut node0_config, genesis_waypoint); node0_config.save(node0_config_path).unwrap(); let db_dir = node0_config.storage.dir(); fs::remove_dir_all(db_dir.join("diemdb")).unwrap(); fs::remove_dir_all(db_dir.join("consensusdb")).unwrap(); // restore db from backup db_restore(backup_path.path(), db_dir.as_path(), &[]); { transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); } // start node 0 on top of restored db swarm .validator_mut(node_to_restart) .unwrap() .start() .unwrap(); swarm .validator_mut(node_to_restart) .unwrap() .wait_until_healthy(Instant::now() + Duration::from_secs(10)) .unwrap(); // verify it's caught up swarm .wait_for_all_nodes_to_catchup(Instant::now() + Duration::from_secs(60)) .unwrap(); let client_0 = swarm.validator(node_to_restart).unwrap().json_rpc_client(); assert_balance(&client_0, &account_0, expected_balance_0); assert_balance(&client_0, &account_1, expected_balance_1); } fn db_backup_verify(backup_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup-verify"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap();
fn wait_for_backups( target_epoch: u64, target_version: u64, now: Instant, bin_path: &Path, metadata_cache_path: &Path, backup_path: &Path, trusted_waypoints: &[Waypoint], ) -> Result<()> { for _ in 0..60 { // the verify should always succeed. db_backup_verify(backup_path, trusted_waypoints); let output = Command::new(bin_path) .current_dir(workspace_root()) .args(&[ "one-shot", "query", "backup-storage-state", "--metadata-cache-dir", metadata_cache_path.to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .output()? .stdout; let state: BackupStorageState = std::str::from_utf8(&output)?.parse()?; if state.latest_epoch_ending_epoch.is_some() && state.latest_transaction_version.is_some() && state.latest_state_snapshot_version.is_some() && state.latest_epoch_ending_epoch.unwrap() >= target_epoch && state.latest_transaction_version.unwrap() >= target_version { println!("Backup created in {} seconds.", now.elapsed().as_secs()); return Ok(()); } println!("Backup storage state: {}", state); std::thread::sleep(Duration::from_secs(1)); } bail!("Failed to create backup."); } pub(crate) fn db_backup( backup_service_port: u16, target_epoch: u64, target_version: Version, transaction_batch_size: usize, state_snapshot_interval: usize, trusted_waypoints: &[Waypoint], ) -> TempPath { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup"); let metadata_cache_path1 = TempPath::new(); let metadata_cache_path2 = TempPath::new(); let backup_path = TempPath::new(); metadata_cache_path1.create_as_dir().unwrap(); metadata_cache_path2.create_as_dir().unwrap(); backup_path.create_as_dir().unwrap(); // spawn the backup coordinator let mut backup_coordinator = Command::new(bin_path.as_path()) .current_dir(workspace_root()) .args(&[ "coordinator", "run", "--backup-service-address", &format!("http://localhost:{}", backup_service_port), "--transaction-batch-size", &transaction_batch_size.to_string(), "--state-snapshot-interval", &state_snapshot_interval.to_string(), "--metadata-cache-dir", metadata_cache_path1.path().to_str().unwrap(), "local-fs", "--dir", backup_path.path().to_str().unwrap(), ]) .spawn() .unwrap(); // watch the backup storage, wait for it to reach target epoch and version let wait_res = wait_for_backups( target_epoch, target_version, now, bin_path.as_path(), metadata_cache_path2.path(), backup_path.path(), trusted_waypoints, ); backup_coordinator.kill().unwrap(); wait_res.unwrap(); backup_path } pub(crate) fn db_restore(backup_path: &Path, db_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-restore"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--target-db-dir", db_path.to_str().unwrap(), "auto", "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if!output.status.success() { panic!("db-restore failed, output: {:?}", output); } println!("Backup restored in {} seconds.", now.elapsed().as_secs()); } fn transfer_and_reconfig( client: &BlockingClient, transaction_factory: &TransactionFactory, root_account: &mut LocalAccount, account0: &mut LocalAccount, account1: &LocalAccount, transfers: usize, ) -> Result<()> { for _ in 0..transfers { if random::<u16>() % 10 == 0 { let current_version = client.get_metadata()?.into_inner().diem_version.unwrap(); let txn = root_account.sign_with_transaction_builder( transaction_factory.update_diem_version(0, current_version + 1), ); client.submit(&txn)?; client.wait_for_signed_transaction(&txn, None, None)?; println!("Changing diem version to {}", current_version + 1,); } transfer_coins(client, transaction_factory, account0, account1, 1); } Ok(()) }
if !output.status.success() { panic!("db-backup-verify failed, output: {:?}", output); } println!("Backup verified in {} seconds.", now.elapsed().as_secs()); }
random_line_split
lib.rs
use crossbeam_channel as channel; use indexmap::IndexMap as Map; use isahc::{ config::{Configurable, RedirectPolicy}, HttpClient, }; use once_cell::sync::Lazy; use onig::Regex; use rayon::prelude::*; use select::{ document::Document, predicate::{Class, Name}, }; use std::{ borrow::Cow, env, fs::File, io::{BufReader, Write}, path::{Path, PathBuf}, thread, time::Duration, }; mod error; pub use error::Error; use error::ProcessingError; mod utils; const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"; static USER_AGENT: Lazy<Cow<'static, str>> = Lazy::new(|| { env::var("USER_AGENT") .map(Cow::from) .unwrap_or_else(|_| Cow::from(DEFAULT_USER_AGENT)) }); #[derive(Debug, Clone)] pub struct LanguageData { subdomain: &'static str, code: &'static str, header: String, ids_map: Map<String, i64>, } #[derive(Debug, Clone)] pub struct Localizer { data: Vec<LanguageData>, output_dir: PathBuf, } impl Localizer { pub fn run<P: Into<PathBuf>>( ids_map: Map<String, i64>, module_name: &str, output_dir: P, force_all: bool, ) { let output_dir = output_dir.into(); let localizer = Self { data: Self::construct_language_data(vec![ // ("www", "enUS", String::from("L = mod:GetLocale()")), ("de", "deDE", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"deDE\")")), ("es", "esES", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"esES\") or BigWigs:NewBossLocale(\"{module_name}\", \"esMX\")")), ("fr", "frFR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"frFR\")")), ("it", "itIT", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"itIT\")")), ("pt", "ptBR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ptBR\")")), ("ru", "ruRU", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ruRU\")")), ("ko", "koKR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"koKR\")")), ("cn", "zhCN", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"zhCN\")")), ], &ids_map, if force_all { None } else { Some(&output_dir) }), output_dir, }; localizer.process_languages(); } fn construct_language_data( initial_data: Vec<(&'static str, &'static str, String)>, ids_map: &Map<String, i64>, output_dir: Option<&Path>, ) -> Vec<LanguageData> { initial_data .into_par_iter() .filter_map(|language| { let mut ids_map = ids_map.clone(); if let Some(output_dir) = output_dir { let file_path = output_dir.join(format!("{}.lua", language.1)); if let Ok(file) = File::open(file_path) { let mut file = BufReader::new(file); let _ = utils::discard_existing(&mut file, &language.2, &mut ids_map); } } if ids_map.is_empty() { None } else { Some(LanguageData { subdomain: language.0, code: language.1, header: language.2, ids_map, }) } }) .collect() } #[cfg(unix)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use std::fs; use std::os::unix::fs::MetadataExt; let os_tmp = env::temp_dir(); match ( fs::metadata(output_dir).map(|v| v.dev()), fs::metadata(&os_tmp).map(|v| v.dev()), ) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(windows)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use winapi_util::{file, Handle}; let os_tmp = env::temp_dir(); let serial_num = |path: &Path| { Handle::from_path_any(path) .and_then(|h| file::information(h)) .map(|v| v.volume_serial_number()) }; match (serial_num(output_dir), serial_num(&os_tmp)) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(not(any(unix, windows)))] #[inline(always)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { Cow::from(output_dir) } fn process_languages(self) { static TITLE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\s+<.+?>$"#).unwrap()); let total = self.data.iter().fold(0, |acc, el| acc + el.ids_map.len()); if total > 0 { let (tx, rx) = channel::bounded(total); let stderr_thread = thread::spawn(move || { let stderr = std::io::stderr(); let mut stderr = stderr.lock(); let mut processed = 0; let _ = write!(stderr, "\rProgress: 0 / {total}"); while let Ok(msg) = rx.recv() { match msg { Err(ProcessingError::IoError((path, e))) => { let _ = writeln!( stderr, "\rI/O error: {} ({})", e, path.to_string_lossy(), ); } Err(ProcessingError::DataError((language, mob_name, e))) => { let _ = writeln!( stderr, "\rFailed to collect data for \"{mob_name}\" ({language}), error: {e}" ); processed += 1; } _ => processed += 1, } let _ = write!(stderr, "\rProgress: {processed} / {total}"); } let _ = stderr.write(b"\n"); let _ = stderr.flush(); }); let output_dir = self.output_dir; let tmp_dir = Self::get_tmp_dir(&output_dir); self.data.into_par_iter().for_each({ |language| { let client = HttpClient::builder() .timeout(Duration::from_secs(30)) .redirect_policy(RedirectPolicy::Limit(5)) .default_header( "accept", "text/html,application/xhtml+xml,application/xml;q=0.9", ) .default_header("accept-encoding", "gzip, deflate") .default_header("accept-language", "en-US,en;q=0.9") .default_header("sec-fetch-dest", "document") .default_header("sec-fetch-mode", "navigate") .default_header("sec-fetch-site", "same-site") .default_header("sec-fetch-user", "?1") .default_header("upgrade-insecure-requests", "1") .default_header("user-agent", &**USER_AGENT) .build() .unwrap(); let code = language.code; let subdomain = language.subdomain; let map: Map<_, _> = language .ids_map .into_iter() .filter_map({ let client = &client; let tx = tx.clone(); move |(name, id)| { let result: Result<_, Error> = client .get(&format!("https://{subdomain}.wowhead.com/npc={id}")) .map_err(From::from) .and_then(|mut response| { Document::from_read(response.body_mut()).map_err(From::from) }) .and_then(|document| { document .find(Class("heading-size-1")) .next() .ok_or_else(|| { "Couldn't find an element.heading-size-1".into() }) .and_then(|node| { // Check if we were redirected to the search page. if let Some(parent) = node.parent().and_then(|n| n.parent()) { if parent.is(Name("form")) { return Err("Not a valid NPC ID".into()); } for child in parent.children() { if child.is(Class("database-detail-page-not-found-message")) { return Err("Not a valid NPC ID".into()); } } } Ok(node.text()) }) }); match result { Ok(translation) => { let _ = tx.send(Ok(())); let translation = utils::replace_owning(translation, &TITLE_REGEX, ""); let translation = if translation.contains('\"') { translation.replace('\"', "\\\"") } else { translation }; let (translation, is_valid) = match translation.as_bytes() { [b'[', rest @.., b']'] => { (String::from_utf8(rest.to_vec()).unwrap(), false) } _ => (translation, true), }; Some((name, (translation, is_valid))) } Err(e) => { let _ = tx .send(Err(ProcessingError::DataError((code, name, e)))); None } } } }) .collect(); if let Err(e) = utils::write_to_dir( &output_dir, &tmp_dir, language.code, &language.header, map, ) { let _ = tx.send(Err(ProcessingError::IoError(e))); } } }); drop(tx); stderr_thread.join().unwrap(); if let Err(e) = File::open(&output_dir).and_then(|dir| dir.sync_all()) { eprintln!( "Failed to call fsync() on \"{}\": {}", output_dir.display(), e ); } } else { eprintln!("There's nothing to do.");
} } }
random_line_split
lib.rs
use crossbeam_channel as channel; use indexmap::IndexMap as Map; use isahc::{ config::{Configurable, RedirectPolicy}, HttpClient, }; use once_cell::sync::Lazy; use onig::Regex; use rayon::prelude::*; use select::{ document::Document, predicate::{Class, Name}, }; use std::{ borrow::Cow, env, fs::File, io::{BufReader, Write}, path::{Path, PathBuf}, thread, time::Duration, }; mod error; pub use error::Error; use error::ProcessingError; mod utils; const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"; static USER_AGENT: Lazy<Cow<'static, str>> = Lazy::new(|| { env::var("USER_AGENT") .map(Cow::from) .unwrap_or_else(|_| Cow::from(DEFAULT_USER_AGENT)) }); #[derive(Debug, Clone)] pub struct LanguageData { subdomain: &'static str, code: &'static str, header: String, ids_map: Map<String, i64>, } #[derive(Debug, Clone)] pub struct Localizer { data: Vec<LanguageData>, output_dir: PathBuf, } impl Localizer { pub fn run<P: Into<PathBuf>>( ids_map: Map<String, i64>, module_name: &str, output_dir: P, force_all: bool, ) { let output_dir = output_dir.into(); let localizer = Self { data: Self::construct_language_data(vec![ // ("www", "enUS", String::from("L = mod:GetLocale()")), ("de", "deDE", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"deDE\")")), ("es", "esES", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"esES\") or BigWigs:NewBossLocale(\"{module_name}\", \"esMX\")")), ("fr", "frFR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"frFR\")")), ("it", "itIT", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"itIT\")")), ("pt", "ptBR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ptBR\")")), ("ru", "ruRU", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ruRU\")")), ("ko", "koKR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"koKR\")")), ("cn", "zhCN", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"zhCN\")")), ], &ids_map, if force_all { None } else { Some(&output_dir) }), output_dir, }; localizer.process_languages(); } fn construct_language_data( initial_data: Vec<(&'static str, &'static str, String)>, ids_map: &Map<String, i64>, output_dir: Option<&Path>, ) -> Vec<LanguageData> { initial_data .into_par_iter() .filter_map(|language| { let mut ids_map = ids_map.clone(); if let Some(output_dir) = output_dir { let file_path = output_dir.join(format!("{}.lua", language.1)); if let Ok(file) = File::open(file_path) { let mut file = BufReader::new(file); let _ = utils::discard_existing(&mut file, &language.2, &mut ids_map); } } if ids_map.is_empty() { None } else { Some(LanguageData { subdomain: language.0, code: language.1, header: language.2, ids_map, }) } }) .collect() } #[cfg(unix)] fn
(output_dir: &Path) -> Cow<'_, Path> { use std::fs; use std::os::unix::fs::MetadataExt; let os_tmp = env::temp_dir(); match ( fs::metadata(output_dir).map(|v| v.dev()), fs::metadata(&os_tmp).map(|v| v.dev()), ) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(windows)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use winapi_util::{file, Handle}; let os_tmp = env::temp_dir(); let serial_num = |path: &Path| { Handle::from_path_any(path) .and_then(|h| file::information(h)) .map(|v| v.volume_serial_number()) }; match (serial_num(output_dir), serial_num(&os_tmp)) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(not(any(unix, windows)))] #[inline(always)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { Cow::from(output_dir) } fn process_languages(self) { static TITLE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\s+<.+?>$"#).unwrap()); let total = self.data.iter().fold(0, |acc, el| acc + el.ids_map.len()); if total > 0 { let (tx, rx) = channel::bounded(total); let stderr_thread = thread::spawn(move || { let stderr = std::io::stderr(); let mut stderr = stderr.lock(); let mut processed = 0; let _ = write!(stderr, "\rProgress: 0 / {total}"); while let Ok(msg) = rx.recv() { match msg { Err(ProcessingError::IoError((path, e))) => { let _ = writeln!( stderr, "\rI/O error: {} ({})", e, path.to_string_lossy(), ); } Err(ProcessingError::DataError((language, mob_name, e))) => { let _ = writeln!( stderr, "\rFailed to collect data for \"{mob_name}\" ({language}), error: {e}" ); processed += 1; } _ => processed += 1, } let _ = write!(stderr, "\rProgress: {processed} / {total}"); } let _ = stderr.write(b"\n"); let _ = stderr.flush(); }); let output_dir = self.output_dir; let tmp_dir = Self::get_tmp_dir(&output_dir); self.data.into_par_iter().for_each({ |language| { let client = HttpClient::builder() .timeout(Duration::from_secs(30)) .redirect_policy(RedirectPolicy::Limit(5)) .default_header( "accept", "text/html,application/xhtml+xml,application/xml;q=0.9", ) .default_header("accept-encoding", "gzip, deflate") .default_header("accept-language", "en-US,en;q=0.9") .default_header("sec-fetch-dest", "document") .default_header("sec-fetch-mode", "navigate") .default_header("sec-fetch-site", "same-site") .default_header("sec-fetch-user", "?1") .default_header("upgrade-insecure-requests", "1") .default_header("user-agent", &**USER_AGENT) .build() .unwrap(); let code = language.code; let subdomain = language.subdomain; let map: Map<_, _> = language .ids_map .into_iter() .filter_map({ let client = &client; let tx = tx.clone(); move |(name, id)| { let result: Result<_, Error> = client .get(&format!("https://{subdomain}.wowhead.com/npc={id}")) .map_err(From::from) .and_then(|mut response| { Document::from_read(response.body_mut()).map_err(From::from) }) .and_then(|document| { document .find(Class("heading-size-1")) .next() .ok_or_else(|| { "Couldn't find an element.heading-size-1".into() }) .and_then(|node| { // Check if we were redirected to the search page. if let Some(parent) = node.parent().and_then(|n| n.parent()) { if parent.is(Name("form")) { return Err("Not a valid NPC ID".into()); } for child in parent.children() { if child.is(Class("database-detail-page-not-found-message")) { return Err("Not a valid NPC ID".into()); } } } Ok(node.text()) }) }); match result { Ok(translation) => { let _ = tx.send(Ok(())); let translation = utils::replace_owning(translation, &TITLE_REGEX, ""); let translation = if translation.contains('\"') { translation.replace('\"', "\\\"") } else { translation }; let (translation, is_valid) = match translation.as_bytes() { [b'[', rest @.., b']'] => { (String::from_utf8(rest.to_vec()).unwrap(), false) } _ => (translation, true), }; Some((name, (translation, is_valid))) } Err(e) => { let _ = tx .send(Err(ProcessingError::DataError((code, name, e)))); None } } } }) .collect(); if let Err(e) = utils::write_to_dir( &output_dir, &tmp_dir, language.code, &language.header, map, ) { let _ = tx.send(Err(ProcessingError::IoError(e))); } } }); drop(tx); stderr_thread.join().unwrap(); if let Err(e) = File::open(&output_dir).and_then(|dir| dir.sync_all()) { eprintln!( "Failed to call fsync() on \"{}\": {}", output_dir.display(), e ); } } else { eprintln!("There's nothing to do."); } } }
get_tmp_dir
identifier_name
lib.rs
use crossbeam_channel as channel; use indexmap::IndexMap as Map; use isahc::{ config::{Configurable, RedirectPolicy}, HttpClient, }; use once_cell::sync::Lazy; use onig::Regex; use rayon::prelude::*; use select::{ document::Document, predicate::{Class, Name}, }; use std::{ borrow::Cow, env, fs::File, io::{BufReader, Write}, path::{Path, PathBuf}, thread, time::Duration, }; mod error; pub use error::Error; use error::ProcessingError; mod utils; const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"; static USER_AGENT: Lazy<Cow<'static, str>> = Lazy::new(|| { env::var("USER_AGENT") .map(Cow::from) .unwrap_or_else(|_| Cow::from(DEFAULT_USER_AGENT)) }); #[derive(Debug, Clone)] pub struct LanguageData { subdomain: &'static str, code: &'static str, header: String, ids_map: Map<String, i64>, } #[derive(Debug, Clone)] pub struct Localizer { data: Vec<LanguageData>, output_dir: PathBuf, } impl Localizer { pub fn run<P: Into<PathBuf>>( ids_map: Map<String, i64>, module_name: &str, output_dir: P, force_all: bool, ) { let output_dir = output_dir.into(); let localizer = Self { data: Self::construct_language_data(vec![ // ("www", "enUS", String::from("L = mod:GetLocale()")), ("de", "deDE", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"deDE\")")), ("es", "esES", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"esES\") or BigWigs:NewBossLocale(\"{module_name}\", \"esMX\")")), ("fr", "frFR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"frFR\")")), ("it", "itIT", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"itIT\")")), ("pt", "ptBR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ptBR\")")), ("ru", "ruRU", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ruRU\")")), ("ko", "koKR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"koKR\")")), ("cn", "zhCN", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"zhCN\")")), ], &ids_map, if force_all { None } else { Some(&output_dir) }), output_dir, }; localizer.process_languages(); } fn construct_language_data( initial_data: Vec<(&'static str, &'static str, String)>, ids_map: &Map<String, i64>, output_dir: Option<&Path>, ) -> Vec<LanguageData> { initial_data .into_par_iter() .filter_map(|language| { let mut ids_map = ids_map.clone(); if let Some(output_dir) = output_dir { let file_path = output_dir.join(format!("{}.lua", language.1)); if let Ok(file) = File::open(file_path) { let mut file = BufReader::new(file); let _ = utils::discard_existing(&mut file, &language.2, &mut ids_map); } } if ids_map.is_empty() { None } else { Some(LanguageData { subdomain: language.0, code: language.1, header: language.2, ids_map, }) } }) .collect() } #[cfg(unix)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use std::fs; use std::os::unix::fs::MetadataExt; let os_tmp = env::temp_dir(); match ( fs::metadata(output_dir).map(|v| v.dev()), fs::metadata(&os_tmp).map(|v| v.dev()), ) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(windows)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use winapi_util::{file, Handle}; let os_tmp = env::temp_dir(); let serial_num = |path: &Path| { Handle::from_path_any(path) .and_then(|h| file::information(h)) .map(|v| v.volume_serial_number()) }; match (serial_num(output_dir), serial_num(&os_tmp)) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(not(any(unix, windows)))] #[inline(always)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { Cow::from(output_dir) } fn process_languages(self) { static TITLE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\s+<.+?>$"#).unwrap()); let total = self.data.iter().fold(0, |acc, el| acc + el.ids_map.len()); if total > 0 { let (tx, rx) = channel::bounded(total); let stderr_thread = thread::spawn(move || { let stderr = std::io::stderr(); let mut stderr = stderr.lock(); let mut processed = 0; let _ = write!(stderr, "\rProgress: 0 / {total}"); while let Ok(msg) = rx.recv() { match msg { Err(ProcessingError::IoError((path, e))) => { let _ = writeln!( stderr, "\rI/O error: {} ({})", e, path.to_string_lossy(), ); } Err(ProcessingError::DataError((language, mob_name, e))) => { let _ = writeln!( stderr, "\rFailed to collect data for \"{mob_name}\" ({language}), error: {e}" ); processed += 1; } _ => processed += 1, } let _ = write!(stderr, "\rProgress: {processed} / {total}"); } let _ = stderr.write(b"\n"); let _ = stderr.flush(); }); let output_dir = self.output_dir; let tmp_dir = Self::get_tmp_dir(&output_dir); self.data.into_par_iter().for_each({ |language| { let client = HttpClient::builder() .timeout(Duration::from_secs(30)) .redirect_policy(RedirectPolicy::Limit(5)) .default_header( "accept", "text/html,application/xhtml+xml,application/xml;q=0.9", ) .default_header("accept-encoding", "gzip, deflate") .default_header("accept-language", "en-US,en;q=0.9") .default_header("sec-fetch-dest", "document") .default_header("sec-fetch-mode", "navigate") .default_header("sec-fetch-site", "same-site") .default_header("sec-fetch-user", "?1") .default_header("upgrade-insecure-requests", "1") .default_header("user-agent", &**USER_AGENT) .build() .unwrap(); let code = language.code; let subdomain = language.subdomain; let map: Map<_, _> = language .ids_map .into_iter() .filter_map({ let client = &client; let tx = tx.clone(); move |(name, id)| { let result: Result<_, Error> = client .get(&format!("https://{subdomain}.wowhead.com/npc={id}")) .map_err(From::from) .and_then(|mut response| { Document::from_read(response.body_mut()).map_err(From::from) }) .and_then(|document| { document .find(Class("heading-size-1")) .next() .ok_or_else(|| { "Couldn't find an element.heading-size-1".into() }) .and_then(|node| { // Check if we were redirected to the search page. if let Some(parent) = node.parent().and_then(|n| n.parent()) { if parent.is(Name("form")) { return Err("Not a valid NPC ID".into()); } for child in parent.children() { if child.is(Class("database-detail-page-not-found-message"))
} } Ok(node.text()) }) }); match result { Ok(translation) => { let _ = tx.send(Ok(())); let translation = utils::replace_owning(translation, &TITLE_REGEX, ""); let translation = if translation.contains('\"') { translation.replace('\"', "\\\"") } else { translation }; let (translation, is_valid) = match translation.as_bytes() { [b'[', rest @.., b']'] => { (String::from_utf8(rest.to_vec()).unwrap(), false) } _ => (translation, true), }; Some((name, (translation, is_valid))) } Err(e) => { let _ = tx .send(Err(ProcessingError::DataError((code, name, e)))); None } } } }) .collect(); if let Err(e) = utils::write_to_dir( &output_dir, &tmp_dir, language.code, &language.header, map, ) { let _ = tx.send(Err(ProcessingError::IoError(e))); } } }); drop(tx); stderr_thread.join().unwrap(); if let Err(e) = File::open(&output_dir).and_then(|dir| dir.sync_all()) { eprintln!( "Failed to call fsync() on \"{}\": {}", output_dir.display(), e ); } } else { eprintln!("There's nothing to do."); } } }
{ return Err("Not a valid NPC ID".into()); }
conditional_block
mmio.rs
#![cfg_attr(rustfmt, rustfmt::skip)] //! Contains all the MMIO address definitions for the GBA's components. //! //! This module contains *only* the MMIO addresses. The data type definitions //! for each MMIO control value are stored in the appropriate other modules such //! as [`video`](crate::video), [`interrupts`](crate::interrupts), etc. //! //! In general, the docs for each address are quite short. If you want to //! understand how a subsystem of the GBA works, you should read the docs for //! that system's module, and the data type used by the address. //! //! The GBATEK names (and thus mGBA names) are used for the MMIO addresses by //! default. However, in some cases (eg: sound) the GBATEK naming is excessively //! cryptic, and so new names have been created. Whenever a new name is used, //! the GBATEK name is still listed as a doc alias for that address. If //! necessary you can just search the GBATEK name in the rustdoc search bar and //! the search results will show you the new name. //! //! ## Safety //! //! The MMIO declarations and wrapper types in this module **must not** be used //! outside of a GBA. The read and write safety of each address are declared //! assuming that code is running on a GBA. On any other platform, the //! declarations are simply incorrect. use core::{ffi::c_void, mem::size_of}; use bitfrob::u8x2; use voladdress::{Safe, Unsafe, VolAddress, VolBlock, VolSeries, VolGrid2dStrided}; use crate::prelude::*; // Note(Lokathor): This macro lets us stick each address at the start of the // definition, which lets us easily keep each declaration in address order. macro_rules! def_mmio { ($addr:literal = $name:ident : $t:ty $(; $comment:expr )?) => { // redirect a call **without** an alias list to just pass an empty alias list def_mmio!($addr = $name/[]: $t $(; $comment)? ); }; ($addr:literal = $name:ident / [ $( $alias:literal ),* ]: $t:ty $(; $comment:expr )?) => { $(#[doc = $comment])? $(#[doc(alias = $alias)])* #[allow(missing_docs)] pub const $name: $t = unsafe { <$t>::new($addr) }; }; } // Video def_mmio!(0x0400_0000 = DISPCNT: VolAddress<DisplayControl, Safe, Safe>; "Display Control"); def_mmio!(0x0400_0004 = DISPSTAT: VolAddress<DisplayStatus, Safe, Safe>; "Display Status"); def_mmio!(0x0400_0006 = VCOUNT: VolAddress<u16, Safe, ()>; "Vertical Counter"); def_mmio!(0x0400_0008 = BG0CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 0 Control"); def_mmio!(0x0400_000A = BG1CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 1 Control"); def_mmio!(0x0400_000C = BG2CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 2 Control"); def_mmio!(0x0400_000E = BG3CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 3 Control"); def_mmio!(0x0400_0010 = BG0HOFS: VolAddress<u16, (), Safe>; "Background 0 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0012 = BG0VOFS: VolAddress<u16, (), Safe>; "Background 0 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0014 = BG1HOFS: VolAddress<u16, (), Safe>; "Background 1 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0016 = BG1VOFS: VolAddress<u16, (), Safe>; "Background 1 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0018 = BG2HOFS: VolAddress<u16, (), Safe>; "Background 2 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001A = BG2VOFS: VolAddress<u16, (), Safe>; "Background 2 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_001C = BG3HOFS: VolAddress<u16, (), Safe>; "Background 3 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001E = BG3VOFS: VolAddress<u16, (), Safe>; "Background 3 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0020 = BG2PA: VolAddress<i16fx8, (), Safe>; "Background 2 Param A (affine mode)"); def_mmio!(0x0400_0022 = BG2PB: VolAddress<i16fx8, (), Safe>; "Background 2 Param B (affine mode)"); def_mmio!(0x0400_0024 = BG2PC: VolAddress<i16fx8, (), Safe>; "Background 2 Param C (affine mode)"); def_mmio!(0x0400_0026 = BG2PD: VolAddress<i16fx8, (), Safe>; "Background 2 Param D (affine mode)"); def_mmio!(0x0400_0028 = BG2X/["BG2X_L", "BG2X_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_002C = BG2Y/["BG2Y_L", "BG2Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0030 = BG3PA: VolAddress<i16fx8, (), Safe>; "Background 3 Param A (affine mode)"); def_mmio!(0x0400_0032 = BG3PB: VolAddress<i16fx8, (), Safe>; "Background 3 Param B (affine mode)"); def_mmio!(0x0400_0034 = BG3PC: VolAddress<i16fx8, (), Safe>; "Background 3 Param C (affine mode)"); def_mmio!(0x0400_0036 = BG3PD: VolAddress<i16fx8, (), Safe>; "Background 3 Param D (affine mode)"); def_mmio!(0x0400_0038 = BG3X/["BG3X_L", "BG3X_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_003C = BG3Y/["BG3Y_L", "BG3Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0040 = WIN0H: VolAddress<u8x2, (), Safe>; "Window 0 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0042 = WIN1H: VolAddress<u8x2, (), Safe>; "Window 1 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0044 = WIN0V: VolAddress<u8x2, (), Safe>; "Window 0 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0046 = WIN1V: VolAddress<u8x2, (), Safe>; "Window 1 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0048 = WININ: VolAddress<WindowInside, Safe, Safe>; "Controls the inside Windows 0 and 1"); def_mmio!(0x0400_004A = WINOUT: VolAddress<WindowOutside, Safe, Safe>; "Controls inside the object window and outside of windows"); def_mmio!(0x0400_004C = MOSAIC: VolAddress<Mosaic, (), Safe>; "Sets the intensity of all mosaic effects"); def_mmio!(0x0400_0050 = BLDCNT: VolAddress<BlendControl, Safe, Safe>; "Sets color blend effects"); def_mmio!(0x0400_0052 = BLDALPHA: VolAddress<u8x2, Safe, Safe>;"Sets EVA(low) and EVB(high) alpha blend coefficients, allows `0..=16`, in 1/16th units"); def_mmio!(0x0400_0054 = BLDY: VolAddress<u8, (), Safe>;"Sets EVY brightness blend coefficient, allows `0..=16`, in 1/16th units"); // Sound def_mmio!(0x0400_0060 = TONE1_SWEEP/["SOUND1CNT_L","NR10"]: VolAddress<SweepControl, Safe, Safe>; "Tone 1 Sweep"); def_mmio!(0x0400_0062 = TONE1_PATTERN/["SOUND1CNT_H","NR11","NR12"]: VolAddress<TonePattern, Safe, Safe>; "Tone 1 Duty/Len/Envelope"); def_mmio!(0x0400_0064 = TONE1_FREQUENCY/["SOUND1CNT_X","NR13","NR14"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 1 Frequency/Control"); def_mmio!(0x0400_0068 = TONE2_PATTERN/["SOUND2CNT_L","NR21","NR22"]: VolAddress<TonePattern, Safe, Safe>; "Tone 2 Duty/Len/Envelope"); def_mmio!(0x0400_006C = TONE2_FREQUENCY/["SOUND2CNT_H","NR23","NR24"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 2 Frequency/Control"); def_mmio!(0x0400_0070 = WAVE_BANK/["SOUND3CNT_L","NR30"]: VolAddress<WaveBank, Safe, Safe>; "Wave banking controls"); def_mmio!(0x0400_0072 = WAVE_LEN_VOLUME/["SOUND3CNT_H","NR31","NR32"]: VolAddress<WaveLenVolume, Safe, Safe>; "Wave Length/Volume"); def_mmio!(0x0400_0074 = WAVE_FREQ/["SOUND3CNT_X","NR33","NR34"]: VolAddress<WaveFrequency, Safe, Safe>; "Wave Frequency/Control"); def_mmio!(0x0400_0078 = NOISE_LEN_ENV/["SOUND4CNT_L","NR41","NR42"]: VolAddress<NoiseLenEnvelope, Safe, Safe>; "Noise Length/Envelope"); def_mmio!(0x0400_007C = NOISE_FREQ/["SOUND4CNT_H","NR43","NR44"]: VolAddress<NoiseFrequency, Safe, Safe>; "Noise Frequency/Control"); def_mmio!(0x0400_0080 = LEFT_RIGHT_VOLUME/["SOUNDCNT_L","NR50","NR51"]: VolAddress<LeftRightVolume, Safe, Safe>;"Left/Right sound control (but GBAs only have one speaker each)."); def_mmio!(0x0400_0082 = SOUND_MIX/["SOUNDCNT_H"]: VolAddress<SoundMix, Safe, Safe>;"Mixes sound sources out to the left and right"); def_mmio!(0x0400_0084 = SOUND_ENABLED/["SOUNDCNT_X"]: VolAddress<SoundEnable, Safe, Safe>;"Sound active flags (r), as well as the sound primary enable (rw)."); def_mmio!(0x0400_0088 = SOUNDBIAS: VolAddress<SoundBias, Safe, Safe>;"Provides a bias to set the'middle point' of sound output."); def_mmio!(0x0400_0090 = WAVE_RAM/["WAVE_RAM0_L","WAVE_RAM0_H","WAVE_RAM1_L","WAVE_RAM1_H","WAVE_RAM2_L","WAVE_RAM2_H","WAVE_RAM3_L","WAVE_RAM3_H"]: VolBlock<u32, Safe, Safe, 4>; "Wave memory, `u4`, plays MSB/LSB per byte."); def_mmio!(0x0400_00A0 = FIFO_A/["FIFO_A_L", "FIFO_A_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound A buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); def_mmio!(0x0400_00A4 = FIFO_B/["FIFO_B_L", "FIFO_B_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound B buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); // DMA def_mmio!(0x0400_00B0 = DMA0_SRC/["DMA0SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA0 Source Address (internal memory only)"); def_mmio!(0x0400_00B4 = DMA0_DEST/["DMA0DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA0 Destination Address (internal memory only)"); def_mmio!(0x0400_00B8 = DMA0_COUNT/["DMA0CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA0 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00BA = DMA0_CONTROL/["DMA0_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA0 Control Bits"); def_mmio!(0x0400_00BC = DMA1_SRC/["DMA1SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA1 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00C0 = DMA1_DEST/["DMA1DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA1 Destination Address (internal memory only)"); def_mmio!(0x0400_00C4 = DMA1_COUNT/["DMA1CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA1 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00C6 = DMA1_CONTROL/["DMA1_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA1 Control Bits"); def_mmio!(0x0400_00C8 = DMA2_SRC/["DMA2SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA2 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00CC = DMA2_DEST/["DMA2DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA2 Destination Address (internal memory only)"); def_mmio!(0x0400_00D0 = DMA2_COUNT/["DMA2CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA2 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00D2 = DMA2_CONTROL/["DMA2_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA2 Control Bits"); def_mmio!(0x0400_00D4 = DMA3_SRC/["DMA3SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA3 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00D8 = DMA3_DEST/["DMA3DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA3 Destination Address (non-SRAM memory)"); def_mmio!(0x0400_00DC = DMA3_COUNT/["DMA3CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA3 Transfer Count (16-bit, 0=max)");
// Timers def_mmio!(0x0400_0100 = TIMER0_COUNT/["TM0CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 0 Count read"); def_mmio!(0x0400_0100 = TIMER0_RELOAD/["TM0CNT_L"]: VolAddress<u16, (), Safe>; "Timer 0 Reload write"); def_mmio!(0x0400_0102 = TIMER0_CONTROL/["TM0CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 0 control"); def_mmio!(0x0400_0104 = TIMER1_COUNT/["TM1CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 1 Count read"); def_mmio!(0x0400_0104 = TIMER1_RELOAD/["TM1CNT_L"]: VolAddress<u16, (), Safe>; "Timer 1 Reload write"); def_mmio!(0x0400_0106 = TIMER1_CONTROL/["TM1CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 1 control"); def_mmio!(0x0400_0108 = TIMER2_COUNT/["TM2CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 2 Count read"); def_mmio!(0x0400_0108 = TIMER2_RELOAD/["TM2CNT_L"]: VolAddress<u16, (), Safe>; "Timer 2 Reload write"); def_mmio!(0x0400_010A = TIMER2_CONTROL/["TM2CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 2 control"); def_mmio!(0x0400_010C = TIMER3_COUNT/["TM3CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 3 Count read"); def_mmio!(0x0400_010C = TIMER3_RELOAD/["TM3CNT_L"]: VolAddress<u16, (), Safe>; "Timer 3 Reload write"); def_mmio!(0x0400_010E = TIMER3_CONTROL/["TM3CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 3 control"); // Serial (part 1) def_mmio!(0x0400_0120 = SIODATA32: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0120 = SIOMULTI0: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0122 = SIOMULTI1: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0124 = SIOMULTI2: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0126 = SIOMULTI3: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0128 = SIOCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIOMLT_SEND: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIODATA8: VolAddress<u8, Safe, Safe>); // Keys def_mmio!(0x0400_0130 = KEYINPUT: VolAddress<KeyInput, Safe, ()>; "Key state data."); def_mmio!(0x0400_0132 = KEYCNT: VolAddress<KeyControl, Safe, Safe>; "Key control to configure the key interrupt."); // Serial (part 2) def_mmio!(0x0400_0134 = RCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0140 = JOYCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0150 = JOY_RECV: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0154 = JOY_TRANS: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0158 = JOYSTAT: VolAddress<u8, Safe, Safe>); // Interrupts def_mmio!(0x0400_0200 = IE: VolAddress<IrqBits, Safe, Safe>; "Interrupts Enabled: sets which interrupts will be accepted when a subsystem fires an interrupt"); def_mmio!(0x0400_0202 = IF: VolAddress<IrqBits, Safe, Safe>; "Interrupts Flagged: reads which interrupts are pending, writing bit(s) will clear a pending interrupt."); def_mmio!(0x0400_0204 = WAITCNT: VolAddress<u16, Safe, Unsafe>; "Wait state control for interfacing with the ROM.\n\nThis can make reading the ROM give garbage when it's mis-configured!"); def_mmio!(0x0400_0208 = IME: VolAddress<bool, Safe, Safe>; "Interrupt Master Enable: Allows turning on/off all interrupts with a single access."); // mGBA Logging def_mmio!(0x04FF_F600 = MGBA_LOG_BUFFER: VolBlock<u8, Safe, Safe, 256>; "The buffer to put logging messages into.\n\nThe first 0 in the buffer is the end of each message."); def_mmio!(0x04FF_F700 = MGBA_LOG_SEND: VolAddress<MgbaMessageLevel, (), Safe>; "Write to this each time you want to reset a message (it also resets the buffer)."); def_mmio!(0x04FF_F780 = MGBA_LOG_ENABLE: VolAddress<u16, Safe, Safe>; "Allows you to attempt to activate mGBA logging."); // Palette RAM (PALRAM) def_mmio!(0x0500_0000 = BACKDROP_COLOR: VolAddress<Color, Safe, Safe>; "Color that's shown when no BG or OBJ draws to a pixel"); def_mmio!(0x0500_0000 = BG_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Background tile palette entries."); def_mmio!(0x0500_0200 = OBJ_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Object tile palette entries."); #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn bg_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = BG_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn obj_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = OBJ_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } // Video RAM (VRAM) /// The VRAM byte offset per screenblock index. /// /// This is the same for all background types and sizes. pub const SCREENBLOCK_INDEX_OFFSET: usize = 2 * 1_024; /// The size of the background tile region of VRAM. /// /// Background tile index use will work between charblocks, but not past the end /// of BG tile memory into OBJ tile memory. pub const BG_TILE_REGION_SIZE: usize = 64 * 1_024; def_mmio!(0x0600_0000 = CHARBLOCK0_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 0, 4bpp view (512 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 1, 4bpp view (512 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 2, 4bpp view (512 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 3, 4bpp view (512 tiles)."); def_mmio!(0x0600_0000 = CHARBLOCK0_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 0, 8bpp view (256 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 1, 8bpp view (256 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 2, 8bpp view (256 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 3, 8bpp view (256 tiles)."); def_mmio!(0x0600_0000 = TEXT_SCREENBLOCKS: VolGrid2dStrided<TextEntry, Safe, Safe, 32, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Text mode screenblocks."); def_mmio!(0x0600_0000 = AFFINE0_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 8, 16, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 0)."); def_mmio!(0x0600_0000 = AFFINE1_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 16, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 1)."); def_mmio!(0x0600_0000 = AFFINE2_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 32, 64, 31, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 2)."); def_mmio!(0x0600_0000 = AFFINE3_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 64, 128, 25, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 3)."); def_mmio!(0x0600_0000 = VIDEO3_VRAM: VolGrid2dStrided<Color, Safe, Safe, 240, 160, 2, 0xA000>; "Video mode 3 bitmap"); def_mmio!(0x0600_0000 = VIDEO4_VRAM: VolGrid2dStrided<u8x2, Safe, Safe, 120, 160, 2, 0xA000>; "Video mode 4 palette maps (frames 0 and 1). Each entry is two palette indexes."); def_mmio!(0x0600_0000 = VIDEO5_VRAM: VolGrid2dStrided<Color, Safe, Safe, 160, 128, 2, 0xA000>; "Video mode 5 bitmaps (frames 0 and 1)."); def_mmio!(0x0601_0000 = OBJ_TILES: VolBlock<Tile4, Safe, Safe, 1024>; "Object tiles. In video modes 3, 4, and 5 only indices 512..=1023 are available."); // Object Attribute Memory (OAM) def_mmio!(0x0700_0000 = OBJ_ATTR0: VolSeries<ObjAttr0, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 0."); def_mmio!(0x0700_0002 = OBJ_ATTR1: VolSeries<ObjAttr1, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 1."); def_mmio!(0x0700_0004 = OBJ_ATTR2: VolSeries<ObjAttr2, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 2."); def_mmio!(0x0700_0000 = OBJ_ATTR_ALL: VolSeries<ObjAttr, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes (all in one)."); def_mmio!(0x0700_0006 = AFFINE_PARAM_A: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters A."); def_mmio!(0x0700_000E = AFFINE_PARAM_B: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters B."); def_mmio!(0x0700_0016 = AFFINE_PARAM_C: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters C."); def_mmio!(0x0700_001E = AFFINE_PARAM_D: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters D."); // Cartridge IO port // https://problemkaputt.de/gbatek.htm#gbacartioportgpio def_mmio!(0x0800_00C4 = IO_PORT_DATA: VolAddress<u16, Safe, Safe>; "I/O port data"); def_mmio!(0x0800_00C6 = IO_PORT_DIRECTION: VolAddress<u16, Safe, Safe>; "I/O port direction"); def_mmio!(0x0800_00C8 = IO_PORT_CONTROL: VolAddress<u16, Safe, Safe>; "I/O port control");
def_mmio!(0x0400_00DE = DMA3_CONTROL/["DMA3_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA3 Control Bits");
random_line_split
mmio.rs
#![cfg_attr(rustfmt, rustfmt::skip)] //! Contains all the MMIO address definitions for the GBA's components. //! //! This module contains *only* the MMIO addresses. The data type definitions //! for each MMIO control value are stored in the appropriate other modules such //! as [`video`](crate::video), [`interrupts`](crate::interrupts), etc. //! //! In general, the docs for each address are quite short. If you want to //! understand how a subsystem of the GBA works, you should read the docs for //! that system's module, and the data type used by the address. //! //! The GBATEK names (and thus mGBA names) are used for the MMIO addresses by //! default. However, in some cases (eg: sound) the GBATEK naming is excessively //! cryptic, and so new names have been created. Whenever a new name is used, //! the GBATEK name is still listed as a doc alias for that address. If //! necessary you can just search the GBATEK name in the rustdoc search bar and //! the search results will show you the new name. //! //! ## Safety //! //! The MMIO declarations and wrapper types in this module **must not** be used //! outside of a GBA. The read and write safety of each address are declared //! assuming that code is running on a GBA. On any other platform, the //! declarations are simply incorrect. use core::{ffi::c_void, mem::size_of}; use bitfrob::u8x2; use voladdress::{Safe, Unsafe, VolAddress, VolBlock, VolSeries, VolGrid2dStrided}; use crate::prelude::*; // Note(Lokathor): This macro lets us stick each address at the start of the // definition, which lets us easily keep each declaration in address order. macro_rules! def_mmio { ($addr:literal = $name:ident : $t:ty $(; $comment:expr )?) => { // redirect a call **without** an alias list to just pass an empty alias list def_mmio!($addr = $name/[]: $t $(; $comment)? ); }; ($addr:literal = $name:ident / [ $( $alias:literal ),* ]: $t:ty $(; $comment:expr )?) => { $(#[doc = $comment])? $(#[doc(alias = $alias)])* #[allow(missing_docs)] pub const $name: $t = unsafe { <$t>::new($addr) }; }; } // Video def_mmio!(0x0400_0000 = DISPCNT: VolAddress<DisplayControl, Safe, Safe>; "Display Control"); def_mmio!(0x0400_0004 = DISPSTAT: VolAddress<DisplayStatus, Safe, Safe>; "Display Status"); def_mmio!(0x0400_0006 = VCOUNT: VolAddress<u16, Safe, ()>; "Vertical Counter"); def_mmio!(0x0400_0008 = BG0CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 0 Control"); def_mmio!(0x0400_000A = BG1CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 1 Control"); def_mmio!(0x0400_000C = BG2CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 2 Control"); def_mmio!(0x0400_000E = BG3CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 3 Control"); def_mmio!(0x0400_0010 = BG0HOFS: VolAddress<u16, (), Safe>; "Background 0 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0012 = BG0VOFS: VolAddress<u16, (), Safe>; "Background 0 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0014 = BG1HOFS: VolAddress<u16, (), Safe>; "Background 1 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0016 = BG1VOFS: VolAddress<u16, (), Safe>; "Background 1 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0018 = BG2HOFS: VolAddress<u16, (), Safe>; "Background 2 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001A = BG2VOFS: VolAddress<u16, (), Safe>; "Background 2 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_001C = BG3HOFS: VolAddress<u16, (), Safe>; "Background 3 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001E = BG3VOFS: VolAddress<u16, (), Safe>; "Background 3 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0020 = BG2PA: VolAddress<i16fx8, (), Safe>; "Background 2 Param A (affine mode)"); def_mmio!(0x0400_0022 = BG2PB: VolAddress<i16fx8, (), Safe>; "Background 2 Param B (affine mode)"); def_mmio!(0x0400_0024 = BG2PC: VolAddress<i16fx8, (), Safe>; "Background 2 Param C (affine mode)"); def_mmio!(0x0400_0026 = BG2PD: VolAddress<i16fx8, (), Safe>; "Background 2 Param D (affine mode)"); def_mmio!(0x0400_0028 = BG2X/["BG2X_L", "BG2X_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_002C = BG2Y/["BG2Y_L", "BG2Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0030 = BG3PA: VolAddress<i16fx8, (), Safe>; "Background 3 Param A (affine mode)"); def_mmio!(0x0400_0032 = BG3PB: VolAddress<i16fx8, (), Safe>; "Background 3 Param B (affine mode)"); def_mmio!(0x0400_0034 = BG3PC: VolAddress<i16fx8, (), Safe>; "Background 3 Param C (affine mode)"); def_mmio!(0x0400_0036 = BG3PD: VolAddress<i16fx8, (), Safe>; "Background 3 Param D (affine mode)"); def_mmio!(0x0400_0038 = BG3X/["BG3X_L", "BG3X_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_003C = BG3Y/["BG3Y_L", "BG3Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0040 = WIN0H: VolAddress<u8x2, (), Safe>; "Window 0 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0042 = WIN1H: VolAddress<u8x2, (), Safe>; "Window 1 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0044 = WIN0V: VolAddress<u8x2, (), Safe>; "Window 0 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0046 = WIN1V: VolAddress<u8x2, (), Safe>; "Window 1 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0048 = WININ: VolAddress<WindowInside, Safe, Safe>; "Controls the inside Windows 0 and 1"); def_mmio!(0x0400_004A = WINOUT: VolAddress<WindowOutside, Safe, Safe>; "Controls inside the object window and outside of windows"); def_mmio!(0x0400_004C = MOSAIC: VolAddress<Mosaic, (), Safe>; "Sets the intensity of all mosaic effects"); def_mmio!(0x0400_0050 = BLDCNT: VolAddress<BlendControl, Safe, Safe>; "Sets color blend effects"); def_mmio!(0x0400_0052 = BLDALPHA: VolAddress<u8x2, Safe, Safe>;"Sets EVA(low) and EVB(high) alpha blend coefficients, allows `0..=16`, in 1/16th units"); def_mmio!(0x0400_0054 = BLDY: VolAddress<u8, (), Safe>;"Sets EVY brightness blend coefficient, allows `0..=16`, in 1/16th units"); // Sound def_mmio!(0x0400_0060 = TONE1_SWEEP/["SOUND1CNT_L","NR10"]: VolAddress<SweepControl, Safe, Safe>; "Tone 1 Sweep"); def_mmio!(0x0400_0062 = TONE1_PATTERN/["SOUND1CNT_H","NR11","NR12"]: VolAddress<TonePattern, Safe, Safe>; "Tone 1 Duty/Len/Envelope"); def_mmio!(0x0400_0064 = TONE1_FREQUENCY/["SOUND1CNT_X","NR13","NR14"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 1 Frequency/Control"); def_mmio!(0x0400_0068 = TONE2_PATTERN/["SOUND2CNT_L","NR21","NR22"]: VolAddress<TonePattern, Safe, Safe>; "Tone 2 Duty/Len/Envelope"); def_mmio!(0x0400_006C = TONE2_FREQUENCY/["SOUND2CNT_H","NR23","NR24"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 2 Frequency/Control"); def_mmio!(0x0400_0070 = WAVE_BANK/["SOUND3CNT_L","NR30"]: VolAddress<WaveBank, Safe, Safe>; "Wave banking controls"); def_mmio!(0x0400_0072 = WAVE_LEN_VOLUME/["SOUND3CNT_H","NR31","NR32"]: VolAddress<WaveLenVolume, Safe, Safe>; "Wave Length/Volume"); def_mmio!(0x0400_0074 = WAVE_FREQ/["SOUND3CNT_X","NR33","NR34"]: VolAddress<WaveFrequency, Safe, Safe>; "Wave Frequency/Control"); def_mmio!(0x0400_0078 = NOISE_LEN_ENV/["SOUND4CNT_L","NR41","NR42"]: VolAddress<NoiseLenEnvelope, Safe, Safe>; "Noise Length/Envelope"); def_mmio!(0x0400_007C = NOISE_FREQ/["SOUND4CNT_H","NR43","NR44"]: VolAddress<NoiseFrequency, Safe, Safe>; "Noise Frequency/Control"); def_mmio!(0x0400_0080 = LEFT_RIGHT_VOLUME/["SOUNDCNT_L","NR50","NR51"]: VolAddress<LeftRightVolume, Safe, Safe>;"Left/Right sound control (but GBAs only have one speaker each)."); def_mmio!(0x0400_0082 = SOUND_MIX/["SOUNDCNT_H"]: VolAddress<SoundMix, Safe, Safe>;"Mixes sound sources out to the left and right"); def_mmio!(0x0400_0084 = SOUND_ENABLED/["SOUNDCNT_X"]: VolAddress<SoundEnable, Safe, Safe>;"Sound active flags (r), as well as the sound primary enable (rw)."); def_mmio!(0x0400_0088 = SOUNDBIAS: VolAddress<SoundBias, Safe, Safe>;"Provides a bias to set the'middle point' of sound output."); def_mmio!(0x0400_0090 = WAVE_RAM/["WAVE_RAM0_L","WAVE_RAM0_H","WAVE_RAM1_L","WAVE_RAM1_H","WAVE_RAM2_L","WAVE_RAM2_H","WAVE_RAM3_L","WAVE_RAM3_H"]: VolBlock<u32, Safe, Safe, 4>; "Wave memory, `u4`, plays MSB/LSB per byte."); def_mmio!(0x0400_00A0 = FIFO_A/["FIFO_A_L", "FIFO_A_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound A buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); def_mmio!(0x0400_00A4 = FIFO_B/["FIFO_B_L", "FIFO_B_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound B buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); // DMA def_mmio!(0x0400_00B0 = DMA0_SRC/["DMA0SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA0 Source Address (internal memory only)"); def_mmio!(0x0400_00B4 = DMA0_DEST/["DMA0DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA0 Destination Address (internal memory only)"); def_mmio!(0x0400_00B8 = DMA0_COUNT/["DMA0CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA0 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00BA = DMA0_CONTROL/["DMA0_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA0 Control Bits"); def_mmio!(0x0400_00BC = DMA1_SRC/["DMA1SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA1 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00C0 = DMA1_DEST/["DMA1DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA1 Destination Address (internal memory only)"); def_mmio!(0x0400_00C4 = DMA1_COUNT/["DMA1CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA1 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00C6 = DMA1_CONTROL/["DMA1_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA1 Control Bits"); def_mmio!(0x0400_00C8 = DMA2_SRC/["DMA2SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA2 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00CC = DMA2_DEST/["DMA2DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA2 Destination Address (internal memory only)"); def_mmio!(0x0400_00D0 = DMA2_COUNT/["DMA2CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA2 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00D2 = DMA2_CONTROL/["DMA2_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA2 Control Bits"); def_mmio!(0x0400_00D4 = DMA3_SRC/["DMA3SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA3 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00D8 = DMA3_DEST/["DMA3DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA3 Destination Address (non-SRAM memory)"); def_mmio!(0x0400_00DC = DMA3_COUNT/["DMA3CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA3 Transfer Count (16-bit, 0=max)"); def_mmio!(0x0400_00DE = DMA3_CONTROL/["DMA3_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA3 Control Bits"); // Timers def_mmio!(0x0400_0100 = TIMER0_COUNT/["TM0CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 0 Count read"); def_mmio!(0x0400_0100 = TIMER0_RELOAD/["TM0CNT_L"]: VolAddress<u16, (), Safe>; "Timer 0 Reload write"); def_mmio!(0x0400_0102 = TIMER0_CONTROL/["TM0CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 0 control"); def_mmio!(0x0400_0104 = TIMER1_COUNT/["TM1CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 1 Count read"); def_mmio!(0x0400_0104 = TIMER1_RELOAD/["TM1CNT_L"]: VolAddress<u16, (), Safe>; "Timer 1 Reload write"); def_mmio!(0x0400_0106 = TIMER1_CONTROL/["TM1CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 1 control"); def_mmio!(0x0400_0108 = TIMER2_COUNT/["TM2CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 2 Count read"); def_mmio!(0x0400_0108 = TIMER2_RELOAD/["TM2CNT_L"]: VolAddress<u16, (), Safe>; "Timer 2 Reload write"); def_mmio!(0x0400_010A = TIMER2_CONTROL/["TM2CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 2 control"); def_mmio!(0x0400_010C = TIMER3_COUNT/["TM3CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 3 Count read"); def_mmio!(0x0400_010C = TIMER3_RELOAD/["TM3CNT_L"]: VolAddress<u16, (), Safe>; "Timer 3 Reload write"); def_mmio!(0x0400_010E = TIMER3_CONTROL/["TM3CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 3 control"); // Serial (part 1) def_mmio!(0x0400_0120 = SIODATA32: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0120 = SIOMULTI0: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0122 = SIOMULTI1: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0124 = SIOMULTI2: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0126 = SIOMULTI3: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0128 = SIOCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIOMLT_SEND: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIODATA8: VolAddress<u8, Safe, Safe>); // Keys def_mmio!(0x0400_0130 = KEYINPUT: VolAddress<KeyInput, Safe, ()>; "Key state data."); def_mmio!(0x0400_0132 = KEYCNT: VolAddress<KeyControl, Safe, Safe>; "Key control to configure the key interrupt."); // Serial (part 2) def_mmio!(0x0400_0134 = RCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0140 = JOYCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0150 = JOY_RECV: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0154 = JOY_TRANS: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0158 = JOYSTAT: VolAddress<u8, Safe, Safe>); // Interrupts def_mmio!(0x0400_0200 = IE: VolAddress<IrqBits, Safe, Safe>; "Interrupts Enabled: sets which interrupts will be accepted when a subsystem fires an interrupt"); def_mmio!(0x0400_0202 = IF: VolAddress<IrqBits, Safe, Safe>; "Interrupts Flagged: reads which interrupts are pending, writing bit(s) will clear a pending interrupt."); def_mmio!(0x0400_0204 = WAITCNT: VolAddress<u16, Safe, Unsafe>; "Wait state control for interfacing with the ROM.\n\nThis can make reading the ROM give garbage when it's mis-configured!"); def_mmio!(0x0400_0208 = IME: VolAddress<bool, Safe, Safe>; "Interrupt Master Enable: Allows turning on/off all interrupts with a single access."); // mGBA Logging def_mmio!(0x04FF_F600 = MGBA_LOG_BUFFER: VolBlock<u8, Safe, Safe, 256>; "The buffer to put logging messages into.\n\nThe first 0 in the buffer is the end of each message."); def_mmio!(0x04FF_F700 = MGBA_LOG_SEND: VolAddress<MgbaMessageLevel, (), Safe>; "Write to this each time you want to reset a message (it also resets the buffer)."); def_mmio!(0x04FF_F780 = MGBA_LOG_ENABLE: VolAddress<u16, Safe, Safe>; "Allows you to attempt to activate mGBA logging."); // Palette RAM (PALRAM) def_mmio!(0x0500_0000 = BACKDROP_COLOR: VolAddress<Color, Safe, Safe>; "Color that's shown when no BG or OBJ draws to a pixel"); def_mmio!(0x0500_0000 = BG_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Background tile palette entries."); def_mmio!(0x0500_0200 = OBJ_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Object tile palette entries."); #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn bg_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16>
#[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn obj_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = OBJ_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } // Video RAM (VRAM) /// The VRAM byte offset per screenblock index. /// /// This is the same for all background types and sizes. pub const SCREENBLOCK_INDEX_OFFSET: usize = 2 * 1_024; /// The size of the background tile region of VRAM. /// /// Background tile index use will work between charblocks, but not past the end /// of BG tile memory into OBJ tile memory. pub const BG_TILE_REGION_SIZE: usize = 64 * 1_024; def_mmio!(0x0600_0000 = CHARBLOCK0_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 0, 4bpp view (512 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 1, 4bpp view (512 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 2, 4bpp view (512 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 3, 4bpp view (512 tiles)."); def_mmio!(0x0600_0000 = CHARBLOCK0_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 0, 8bpp view (256 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 1, 8bpp view (256 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 2, 8bpp view (256 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 3, 8bpp view (256 tiles)."); def_mmio!(0x0600_0000 = TEXT_SCREENBLOCKS: VolGrid2dStrided<TextEntry, Safe, Safe, 32, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Text mode screenblocks."); def_mmio!(0x0600_0000 = AFFINE0_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 8, 16, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 0)."); def_mmio!(0x0600_0000 = AFFINE1_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 16, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 1)."); def_mmio!(0x0600_0000 = AFFINE2_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 32, 64, 31, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 2)."); def_mmio!(0x0600_0000 = AFFINE3_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 64, 128, 25, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 3)."); def_mmio!(0x0600_0000 = VIDEO3_VRAM: VolGrid2dStrided<Color, Safe, Safe, 240, 160, 2, 0xA000>; "Video mode 3 bitmap"); def_mmio!(0x0600_0000 = VIDEO4_VRAM: VolGrid2dStrided<u8x2, Safe, Safe, 120, 160, 2, 0xA000>; "Video mode 4 palette maps (frames 0 and 1). Each entry is two palette indexes."); def_mmio!(0x0600_0000 = VIDEO5_VRAM: VolGrid2dStrided<Color, Safe, Safe, 160, 128, 2, 0xA000>; "Video mode 5 bitmaps (frames 0 and 1)."); def_mmio!(0x0601_0000 = OBJ_TILES: VolBlock<Tile4, Safe, Safe, 1024>; "Object tiles. In video modes 3, 4, and 5 only indices 512..=1023 are available."); // Object Attribute Memory (OAM) def_mmio!(0x0700_0000 = OBJ_ATTR0: VolSeries<ObjAttr0, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 0."); def_mmio!(0x0700_0002 = OBJ_ATTR1: VolSeries<ObjAttr1, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 1."); def_mmio!(0x0700_0004 = OBJ_ATTR2: VolSeries<ObjAttr2, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 2."); def_mmio!(0x0700_0000 = OBJ_ATTR_ALL: VolSeries<ObjAttr, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes (all in one)."); def_mmio!(0x0700_0006 = AFFINE_PARAM_A: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters A."); def_mmio!(0x0700_000E = AFFINE_PARAM_B: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters B."); def_mmio!(0x0700_0016 = AFFINE_PARAM_C: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters C."); def_mmio!(0x0700_001E = AFFINE_PARAM_D: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters D."); // Cartridge IO port // https://problemkaputt.de/gbatek.htm#gbacartioportgpio def_mmio!(0x0800_00C4 = IO_PORT_DATA: VolAddress<u16, Safe, Safe>; "I/O port data"); def_mmio!(0x0800_00C6 = IO_PORT_DIRECTION: VolAddress<u16, Safe, Safe>; "I/O port direction"); def_mmio!(0x0800_00C8 = IO_PORT_CONTROL: VolAddress<u16, Safe, Safe>; "I/O port control");
{ let u = BG_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } }
identifier_body
mmio.rs
#![cfg_attr(rustfmt, rustfmt::skip)] //! Contains all the MMIO address definitions for the GBA's components. //! //! This module contains *only* the MMIO addresses. The data type definitions //! for each MMIO control value are stored in the appropriate other modules such //! as [`video`](crate::video), [`interrupts`](crate::interrupts), etc. //! //! In general, the docs for each address are quite short. If you want to //! understand how a subsystem of the GBA works, you should read the docs for //! that system's module, and the data type used by the address. //! //! The GBATEK names (and thus mGBA names) are used for the MMIO addresses by //! default. However, in some cases (eg: sound) the GBATEK naming is excessively //! cryptic, and so new names have been created. Whenever a new name is used, //! the GBATEK name is still listed as a doc alias for that address. If //! necessary you can just search the GBATEK name in the rustdoc search bar and //! the search results will show you the new name. //! //! ## Safety //! //! The MMIO declarations and wrapper types in this module **must not** be used //! outside of a GBA. The read and write safety of each address are declared //! assuming that code is running on a GBA. On any other platform, the //! declarations are simply incorrect. use core::{ffi::c_void, mem::size_of}; use bitfrob::u8x2; use voladdress::{Safe, Unsafe, VolAddress, VolBlock, VolSeries, VolGrid2dStrided}; use crate::prelude::*; // Note(Lokathor): This macro lets us stick each address at the start of the // definition, which lets us easily keep each declaration in address order. macro_rules! def_mmio { ($addr:literal = $name:ident : $t:ty $(; $comment:expr )?) => { // redirect a call **without** an alias list to just pass an empty alias list def_mmio!($addr = $name/[]: $t $(; $comment)? ); }; ($addr:literal = $name:ident / [ $( $alias:literal ),* ]: $t:ty $(; $comment:expr )?) => { $(#[doc = $comment])? $(#[doc(alias = $alias)])* #[allow(missing_docs)] pub const $name: $t = unsafe { <$t>::new($addr) }; }; } // Video def_mmio!(0x0400_0000 = DISPCNT: VolAddress<DisplayControl, Safe, Safe>; "Display Control"); def_mmio!(0x0400_0004 = DISPSTAT: VolAddress<DisplayStatus, Safe, Safe>; "Display Status"); def_mmio!(0x0400_0006 = VCOUNT: VolAddress<u16, Safe, ()>; "Vertical Counter"); def_mmio!(0x0400_0008 = BG0CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 0 Control"); def_mmio!(0x0400_000A = BG1CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 1 Control"); def_mmio!(0x0400_000C = BG2CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 2 Control"); def_mmio!(0x0400_000E = BG3CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 3 Control"); def_mmio!(0x0400_0010 = BG0HOFS: VolAddress<u16, (), Safe>; "Background 0 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0012 = BG0VOFS: VolAddress<u16, (), Safe>; "Background 0 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0014 = BG1HOFS: VolAddress<u16, (), Safe>; "Background 1 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0016 = BG1VOFS: VolAddress<u16, (), Safe>; "Background 1 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0018 = BG2HOFS: VolAddress<u16, (), Safe>; "Background 2 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001A = BG2VOFS: VolAddress<u16, (), Safe>; "Background 2 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_001C = BG3HOFS: VolAddress<u16, (), Safe>; "Background 3 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001E = BG3VOFS: VolAddress<u16, (), Safe>; "Background 3 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0020 = BG2PA: VolAddress<i16fx8, (), Safe>; "Background 2 Param A (affine mode)"); def_mmio!(0x0400_0022 = BG2PB: VolAddress<i16fx8, (), Safe>; "Background 2 Param B (affine mode)"); def_mmio!(0x0400_0024 = BG2PC: VolAddress<i16fx8, (), Safe>; "Background 2 Param C (affine mode)"); def_mmio!(0x0400_0026 = BG2PD: VolAddress<i16fx8, (), Safe>; "Background 2 Param D (affine mode)"); def_mmio!(0x0400_0028 = BG2X/["BG2X_L", "BG2X_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_002C = BG2Y/["BG2Y_L", "BG2Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0030 = BG3PA: VolAddress<i16fx8, (), Safe>; "Background 3 Param A (affine mode)"); def_mmio!(0x0400_0032 = BG3PB: VolAddress<i16fx8, (), Safe>; "Background 3 Param B (affine mode)"); def_mmio!(0x0400_0034 = BG3PC: VolAddress<i16fx8, (), Safe>; "Background 3 Param C (affine mode)"); def_mmio!(0x0400_0036 = BG3PD: VolAddress<i16fx8, (), Safe>; "Background 3 Param D (affine mode)"); def_mmio!(0x0400_0038 = BG3X/["BG3X_L", "BG3X_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_003C = BG3Y/["BG3Y_L", "BG3Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0040 = WIN0H: VolAddress<u8x2, (), Safe>; "Window 0 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0042 = WIN1H: VolAddress<u8x2, (), Safe>; "Window 1 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0044 = WIN0V: VolAddress<u8x2, (), Safe>; "Window 0 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0046 = WIN1V: VolAddress<u8x2, (), Safe>; "Window 1 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0048 = WININ: VolAddress<WindowInside, Safe, Safe>; "Controls the inside Windows 0 and 1"); def_mmio!(0x0400_004A = WINOUT: VolAddress<WindowOutside, Safe, Safe>; "Controls inside the object window and outside of windows"); def_mmio!(0x0400_004C = MOSAIC: VolAddress<Mosaic, (), Safe>; "Sets the intensity of all mosaic effects"); def_mmio!(0x0400_0050 = BLDCNT: VolAddress<BlendControl, Safe, Safe>; "Sets color blend effects"); def_mmio!(0x0400_0052 = BLDALPHA: VolAddress<u8x2, Safe, Safe>;"Sets EVA(low) and EVB(high) alpha blend coefficients, allows `0..=16`, in 1/16th units"); def_mmio!(0x0400_0054 = BLDY: VolAddress<u8, (), Safe>;"Sets EVY brightness blend coefficient, allows `0..=16`, in 1/16th units"); // Sound def_mmio!(0x0400_0060 = TONE1_SWEEP/["SOUND1CNT_L","NR10"]: VolAddress<SweepControl, Safe, Safe>; "Tone 1 Sweep"); def_mmio!(0x0400_0062 = TONE1_PATTERN/["SOUND1CNT_H","NR11","NR12"]: VolAddress<TonePattern, Safe, Safe>; "Tone 1 Duty/Len/Envelope"); def_mmio!(0x0400_0064 = TONE1_FREQUENCY/["SOUND1CNT_X","NR13","NR14"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 1 Frequency/Control"); def_mmio!(0x0400_0068 = TONE2_PATTERN/["SOUND2CNT_L","NR21","NR22"]: VolAddress<TonePattern, Safe, Safe>; "Tone 2 Duty/Len/Envelope"); def_mmio!(0x0400_006C = TONE2_FREQUENCY/["SOUND2CNT_H","NR23","NR24"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 2 Frequency/Control"); def_mmio!(0x0400_0070 = WAVE_BANK/["SOUND3CNT_L","NR30"]: VolAddress<WaveBank, Safe, Safe>; "Wave banking controls"); def_mmio!(0x0400_0072 = WAVE_LEN_VOLUME/["SOUND3CNT_H","NR31","NR32"]: VolAddress<WaveLenVolume, Safe, Safe>; "Wave Length/Volume"); def_mmio!(0x0400_0074 = WAVE_FREQ/["SOUND3CNT_X","NR33","NR34"]: VolAddress<WaveFrequency, Safe, Safe>; "Wave Frequency/Control"); def_mmio!(0x0400_0078 = NOISE_LEN_ENV/["SOUND4CNT_L","NR41","NR42"]: VolAddress<NoiseLenEnvelope, Safe, Safe>; "Noise Length/Envelope"); def_mmio!(0x0400_007C = NOISE_FREQ/["SOUND4CNT_H","NR43","NR44"]: VolAddress<NoiseFrequency, Safe, Safe>; "Noise Frequency/Control"); def_mmio!(0x0400_0080 = LEFT_RIGHT_VOLUME/["SOUNDCNT_L","NR50","NR51"]: VolAddress<LeftRightVolume, Safe, Safe>;"Left/Right sound control (but GBAs only have one speaker each)."); def_mmio!(0x0400_0082 = SOUND_MIX/["SOUNDCNT_H"]: VolAddress<SoundMix, Safe, Safe>;"Mixes sound sources out to the left and right"); def_mmio!(0x0400_0084 = SOUND_ENABLED/["SOUNDCNT_X"]: VolAddress<SoundEnable, Safe, Safe>;"Sound active flags (r), as well as the sound primary enable (rw)."); def_mmio!(0x0400_0088 = SOUNDBIAS: VolAddress<SoundBias, Safe, Safe>;"Provides a bias to set the'middle point' of sound output."); def_mmio!(0x0400_0090 = WAVE_RAM/["WAVE_RAM0_L","WAVE_RAM0_H","WAVE_RAM1_L","WAVE_RAM1_H","WAVE_RAM2_L","WAVE_RAM2_H","WAVE_RAM3_L","WAVE_RAM3_H"]: VolBlock<u32, Safe, Safe, 4>; "Wave memory, `u4`, plays MSB/LSB per byte."); def_mmio!(0x0400_00A0 = FIFO_A/["FIFO_A_L", "FIFO_A_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound A buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); def_mmio!(0x0400_00A4 = FIFO_B/["FIFO_B_L", "FIFO_B_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound B buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); // DMA def_mmio!(0x0400_00B0 = DMA0_SRC/["DMA0SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA0 Source Address (internal memory only)"); def_mmio!(0x0400_00B4 = DMA0_DEST/["DMA0DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA0 Destination Address (internal memory only)"); def_mmio!(0x0400_00B8 = DMA0_COUNT/["DMA0CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA0 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00BA = DMA0_CONTROL/["DMA0_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA0 Control Bits"); def_mmio!(0x0400_00BC = DMA1_SRC/["DMA1SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA1 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00C0 = DMA1_DEST/["DMA1DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA1 Destination Address (internal memory only)"); def_mmio!(0x0400_00C4 = DMA1_COUNT/["DMA1CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA1 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00C6 = DMA1_CONTROL/["DMA1_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA1 Control Bits"); def_mmio!(0x0400_00C8 = DMA2_SRC/["DMA2SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA2 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00CC = DMA2_DEST/["DMA2DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA2 Destination Address (internal memory only)"); def_mmio!(0x0400_00D0 = DMA2_COUNT/["DMA2CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA2 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00D2 = DMA2_CONTROL/["DMA2_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA2 Control Bits"); def_mmio!(0x0400_00D4 = DMA3_SRC/["DMA3SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA3 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00D8 = DMA3_DEST/["DMA3DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA3 Destination Address (non-SRAM memory)"); def_mmio!(0x0400_00DC = DMA3_COUNT/["DMA3CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA3 Transfer Count (16-bit, 0=max)"); def_mmio!(0x0400_00DE = DMA3_CONTROL/["DMA3_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA3 Control Bits"); // Timers def_mmio!(0x0400_0100 = TIMER0_COUNT/["TM0CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 0 Count read"); def_mmio!(0x0400_0100 = TIMER0_RELOAD/["TM0CNT_L"]: VolAddress<u16, (), Safe>; "Timer 0 Reload write"); def_mmio!(0x0400_0102 = TIMER0_CONTROL/["TM0CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 0 control"); def_mmio!(0x0400_0104 = TIMER1_COUNT/["TM1CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 1 Count read"); def_mmio!(0x0400_0104 = TIMER1_RELOAD/["TM1CNT_L"]: VolAddress<u16, (), Safe>; "Timer 1 Reload write"); def_mmio!(0x0400_0106 = TIMER1_CONTROL/["TM1CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 1 control"); def_mmio!(0x0400_0108 = TIMER2_COUNT/["TM2CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 2 Count read"); def_mmio!(0x0400_0108 = TIMER2_RELOAD/["TM2CNT_L"]: VolAddress<u16, (), Safe>; "Timer 2 Reload write"); def_mmio!(0x0400_010A = TIMER2_CONTROL/["TM2CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 2 control"); def_mmio!(0x0400_010C = TIMER3_COUNT/["TM3CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 3 Count read"); def_mmio!(0x0400_010C = TIMER3_RELOAD/["TM3CNT_L"]: VolAddress<u16, (), Safe>; "Timer 3 Reload write"); def_mmio!(0x0400_010E = TIMER3_CONTROL/["TM3CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 3 control"); // Serial (part 1) def_mmio!(0x0400_0120 = SIODATA32: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0120 = SIOMULTI0: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0122 = SIOMULTI1: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0124 = SIOMULTI2: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0126 = SIOMULTI3: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0128 = SIOCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIOMLT_SEND: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIODATA8: VolAddress<u8, Safe, Safe>); // Keys def_mmio!(0x0400_0130 = KEYINPUT: VolAddress<KeyInput, Safe, ()>; "Key state data."); def_mmio!(0x0400_0132 = KEYCNT: VolAddress<KeyControl, Safe, Safe>; "Key control to configure the key interrupt."); // Serial (part 2) def_mmio!(0x0400_0134 = RCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0140 = JOYCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0150 = JOY_RECV: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0154 = JOY_TRANS: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0158 = JOYSTAT: VolAddress<u8, Safe, Safe>); // Interrupts def_mmio!(0x0400_0200 = IE: VolAddress<IrqBits, Safe, Safe>; "Interrupts Enabled: sets which interrupts will be accepted when a subsystem fires an interrupt"); def_mmio!(0x0400_0202 = IF: VolAddress<IrqBits, Safe, Safe>; "Interrupts Flagged: reads which interrupts are pending, writing bit(s) will clear a pending interrupt."); def_mmio!(0x0400_0204 = WAITCNT: VolAddress<u16, Safe, Unsafe>; "Wait state control for interfacing with the ROM.\n\nThis can make reading the ROM give garbage when it's mis-configured!"); def_mmio!(0x0400_0208 = IME: VolAddress<bool, Safe, Safe>; "Interrupt Master Enable: Allows turning on/off all interrupts with a single access."); // mGBA Logging def_mmio!(0x04FF_F600 = MGBA_LOG_BUFFER: VolBlock<u8, Safe, Safe, 256>; "The buffer to put logging messages into.\n\nThe first 0 in the buffer is the end of each message."); def_mmio!(0x04FF_F700 = MGBA_LOG_SEND: VolAddress<MgbaMessageLevel, (), Safe>; "Write to this each time you want to reset a message (it also resets the buffer)."); def_mmio!(0x04FF_F780 = MGBA_LOG_ENABLE: VolAddress<u16, Safe, Safe>; "Allows you to attempt to activate mGBA logging."); // Palette RAM (PALRAM) def_mmio!(0x0500_0000 = BACKDROP_COLOR: VolAddress<Color, Safe, Safe>; "Color that's shown when no BG or OBJ draws to a pixel"); def_mmio!(0x0500_0000 = BG_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Background tile palette entries."); def_mmio!(0x0500_0200 = OBJ_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Object tile palette entries."); #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn bg_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = BG_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn
(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = OBJ_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } // Video RAM (VRAM) /// The VRAM byte offset per screenblock index. /// /// This is the same for all background types and sizes. pub const SCREENBLOCK_INDEX_OFFSET: usize = 2 * 1_024; /// The size of the background tile region of VRAM. /// /// Background tile index use will work between charblocks, but not past the end /// of BG tile memory into OBJ tile memory. pub const BG_TILE_REGION_SIZE: usize = 64 * 1_024; def_mmio!(0x0600_0000 = CHARBLOCK0_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 0, 4bpp view (512 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 1, 4bpp view (512 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 2, 4bpp view (512 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 3, 4bpp view (512 tiles)."); def_mmio!(0x0600_0000 = CHARBLOCK0_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 0, 8bpp view (256 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 1, 8bpp view (256 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 2, 8bpp view (256 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 3, 8bpp view (256 tiles)."); def_mmio!(0x0600_0000 = TEXT_SCREENBLOCKS: VolGrid2dStrided<TextEntry, Safe, Safe, 32, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Text mode screenblocks."); def_mmio!(0x0600_0000 = AFFINE0_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 8, 16, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 0)."); def_mmio!(0x0600_0000 = AFFINE1_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 16, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 1)."); def_mmio!(0x0600_0000 = AFFINE2_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 32, 64, 31, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 2)."); def_mmio!(0x0600_0000 = AFFINE3_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 64, 128, 25, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 3)."); def_mmio!(0x0600_0000 = VIDEO3_VRAM: VolGrid2dStrided<Color, Safe, Safe, 240, 160, 2, 0xA000>; "Video mode 3 bitmap"); def_mmio!(0x0600_0000 = VIDEO4_VRAM: VolGrid2dStrided<u8x2, Safe, Safe, 120, 160, 2, 0xA000>; "Video mode 4 palette maps (frames 0 and 1). Each entry is two palette indexes."); def_mmio!(0x0600_0000 = VIDEO5_VRAM: VolGrid2dStrided<Color, Safe, Safe, 160, 128, 2, 0xA000>; "Video mode 5 bitmaps (frames 0 and 1)."); def_mmio!(0x0601_0000 = OBJ_TILES: VolBlock<Tile4, Safe, Safe, 1024>; "Object tiles. In video modes 3, 4, and 5 only indices 512..=1023 are available."); // Object Attribute Memory (OAM) def_mmio!(0x0700_0000 = OBJ_ATTR0: VolSeries<ObjAttr0, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 0."); def_mmio!(0x0700_0002 = OBJ_ATTR1: VolSeries<ObjAttr1, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 1."); def_mmio!(0x0700_0004 = OBJ_ATTR2: VolSeries<ObjAttr2, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 2."); def_mmio!(0x0700_0000 = OBJ_ATTR_ALL: VolSeries<ObjAttr, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes (all in one)."); def_mmio!(0x0700_0006 = AFFINE_PARAM_A: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters A."); def_mmio!(0x0700_000E = AFFINE_PARAM_B: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters B."); def_mmio!(0x0700_0016 = AFFINE_PARAM_C: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters C."); def_mmio!(0x0700_001E = AFFINE_PARAM_D: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters D."); // Cartridge IO port // https://problemkaputt.de/gbatek.htm#gbacartioportgpio def_mmio!(0x0800_00C4 = IO_PORT_DATA: VolAddress<u16, Safe, Safe>; "I/O port data"); def_mmio!(0x0800_00C6 = IO_PORT_DIRECTION: VolAddress<u16, Safe, Safe>; "I/O port direction"); def_mmio!(0x0800_00C8 = IO_PORT_CONTROL: VolAddress<u16, Safe, Safe>; "I/O port control");
obj_palbank
identifier_name
lib.rs
//! This crate adds support for subscriptions as defined in [here]. //! //! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB extern crate futures; extern crate jsonrpc_client_core; extern crate jsonrpc_client_utils; #[macro_use] extern crate serde; extern crate serde_json; extern crate tokio; #[macro_use] extern crate log; #[macro_use] extern crate error_chain; use futures::{future, future::Either, sync::mpsc, Async, Future, Poll, Sink, Stream}; use jsonrpc_client_core::server::{ types::Params, Handler, HandlerSettingError, Server, ServerHandle, }; use jsonrpc_client_core::{ ClientHandle, DuplexTransport, Error as CoreError, ErrorKind as CoreErrorKind, }; use serde_json::Value; use std::collections::BTreeMap; use std::fmt; use std::marker::PhantomData; use tokio::prelude::future::Executor; use jsonrpc_client_utils::select_weak::{SelectWithWeak, SelectWithWeakExt}; error_chain! { links { Core(CoreError, CoreErrorKind); } foreign_links { HandlerError(HandlerSettingError); SpawnError(tokio::executor::SpawnError); } } #[derive(Debug, Deserialize)] struct SubscriptionMessage { subscription: SubscriptionId, result: Value, } /// A stream of messages from a subscription. #[derive(Debug)] pub struct Subscription<T: serde::de::DeserializeOwned> { rx: mpsc::Receiver<Value>, id: Option<SubscriptionId>, handler_chan: mpsc::UnboundedSender<SubscriberMsg>, _marker: PhantomData<T>, } impl<T: serde::de::DeserializeOwned> Stream for Subscription<T> { type Item = T; type Error = CoreError; fn poll(&mut self) -> Poll<Option<T>, CoreError> { match self.rx.poll().map_err(|_: ()| CoreErrorKind::Shutdown)? { Async::Ready(Some(v)) => Ok(Async::Ready(Some( serde_json::from_value(v).map_err(|_| CoreErrorKind::DeserializeError)?, ))), Async::Ready(None) => Ok(Async::Ready(None)), Async::NotReady => Ok(Async::NotReady), } } } impl<T: serde::de::DeserializeOwned> Drop for Subscription<T> { fn drop(&mut self) { if let Some(id) = self.id.take() { let _ = self .handler_chan .unbounded_send(SubscriberMsg::RemoveSubscriber(id)); } } } /// A subscriber creates new subscriptions. #[derive(Debug)] pub struct Subscriber<E: Executor<Box<Future<Item = (), Error = ()> + Send>>> { client_handle: ClientHandle, handlers: ServerHandle, notification_handlers: BTreeMap<String, mpsc::UnboundedSender<SubscriberMsg>>, executor: E, } impl<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized> Subscriber<E> { /// Constructs a new subscriber with the provided executor. pub fn new(executor: E, client_handle: ClientHandle, handlers: ServerHandle) -> Self { let notification_handlers = BTreeMap::new(); Self { client_handle, handlers, notification_handlers, executor, } } /// Creates a new subscription with the given method names and parameters. Parameters /// `sub_method` and `unsub_method` are only taken into account if this is the first time a /// subscription for `notification` has been created in the lifetime of this `Subscriber`. pub fn subscribe<T, P>( &mut self, sub_method: String, unsub_method: String, notification_method: String, buffer_size: usize, sub_parameters: P, ) -> impl Future<Item = Subscription<T>, Error = Error> where T: serde::de::DeserializeOwned +'static, P: serde::Serialize +'static, { // Get a channel to an existing notification handler or spawn a new one. let chan = self .notification_handlers .get(&notification_method) .filter(|c| c.is_closed()) .map(|chan| Ok(chan.clone())) .unwrap_or_else(|| { self.spawn_notification_handler(notification_method.clone(), unsub_method) }); let (sub_tx, sub_rx) = mpsc::channel(buffer_size); match chan { Ok(chan) => Either::A( self.client_handle .call_method(sub_method, &sub_parameters) .map_err(|e| e.into()) .and_then(move |id: SubscriptionId| { if let Err(_) = chan.unbounded_send(SubscriberMsg::NewSubscriber(id.clone(), sub_tx)) { debug!( "Notificaton handler for {} - {} already closed", notification_method, id ); }; Ok(Subscription { rx: sub_rx, id: Some(id), handler_chan: chan.clone(), _marker: PhantomData::<T>, }) }), ), Err(e) => Either::B(future::err(e)), } } fn spawn_notification_handler( &mut self, notification_method: String, unsub_method: String, ) -> Result<mpsc::UnboundedSender<SubscriberMsg>> { let (msg_tx, msg_rx) = mpsc::channel(0); self.handlers .add( notification_method.clone(), Handler::Notification(Box::new(move |notification| { let fut = match params_to_subscription_message(notification.params) { Some(msg) => Either::A( msg_tx .clone() .send(msg) .map(|_| ()) .map_err(|_| CoreErrorKind::Shutdown.into()), ), None => { error!( "Received notification with invalid parameters for subscription - {}", notification.method ); Either::B(futures::future::ok(())) } }; Box::new(fut) })), ) .wait()?; let (control_tx, control_rx) = mpsc::unbounded(); let notification_handler = NotificationHandler::new( notification_method.clone(), self.handlers.clone(), self.client_handle.clone(), unsub_method, msg_rx, control_rx, ); if let Err(e) = self .executor .execute(Box::new(notification_handler.map_err(|_| ()))) { error!("Failed to spawn notification handler - {:?}", e); }; self.notification_handlers .insert(notification_method, control_tx.clone()); Ok(control_tx) } } fn params_to_subscription_message(params: Option<Params>) -> Option<SubscriberMsg> { params .and_then(|p| p.parse().ok()) .map(SubscriberMsg::NewMessage) } #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Debug, Deserialize)] #[serde(untagged)] enum SubscriptionId { Num(u64), String(String), } impl fmt::Display for SubscriptionId { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { SubscriptionId::Num(n) => write!(f, "{}", n), SubscriptionId::String(s) => write!(f, "{}", s), } } } #[derive(Debug)] enum SubscriberMsg { NewMessage(SubscriptionMessage), NewSubscriber(SubscriptionId, mpsc::Sender<Value>), RemoveSubscriber(SubscriptionId), } // A single notification can receive messages for different subscribers for the same notification. struct NotificationHandler { notification_method: String, subscribers: BTreeMap<SubscriptionId, mpsc::Sender<Value>>, messages: SelectWithWeak<mpsc::Receiver<SubscriberMsg>, mpsc::UnboundedReceiver<SubscriberMsg>>, unsub_method: String, client_handle: ClientHandle, current_future: Option<Box<dyn Future<Item = (), Error = ()> + Send>>, server_handlers: ServerHandle, should_shut_down: bool, } impl Drop for NotificationHandler { fn drop(&mut self) { let _ = self .server_handlers .remove(self.notification_method.clone()); } } impl NotificationHandler { fn new( notification_method: String, server_handlers: ServerHandle, client_handle: ClientHandle, unsub_method: String, subscription_messages: mpsc::Receiver<SubscriberMsg>, control_messages: mpsc::UnboundedReceiver<SubscriberMsg>, ) -> Self { let messages = subscription_messages.select_with_weak(control_messages); Self { notification_method, messages, server_handlers, unsub_method, subscribers: BTreeMap::new(), client_handle, current_future: None, should_shut_down: false, } } fn handle_new_subscription(&mut self, id: SubscriptionId, chan: mpsc::Sender<Value>) { self.subscribers.insert(id, chan); } fn handle_removal(&mut self, id: SubscriptionId) { if let None = self.subscribers.remove(&id) { debug!("Removing non-existant subscriber - {}", &id); }; let fut = self .client_handle .call_method(self.unsub_method.clone(), &[0u8; 0]) .map(|_r: bool| ()) .map_err(|e| trace!("Failed to unsubscribe - {}", e)); self.should_shut_down = self.subscribers.len() < 1; self.current_future = Some(Box::new(fut)); } fn handle_new_message(&mut self, id: SubscriptionId, message: Value) { match self.subscribers.get(&id) { Some(chan) => { let fut = chan .clone() .send(message) .map_err(move |_| trace!("Subscriber already gone: {}", id)) .map(|_| ()); self.current_future = Some(Box::new(fut)); } None => trace!("Received message for non existant subscription - {}", id), } } fn ready_for_next_connection(&mut self) -> bool { match self.current_future.take() { None => true, Some(mut fut) => match fut.poll() { Ok(Async::NotReady) => { self.current_future = Some(fut); false } _ => true, }, } } } impl Future for NotificationHandler { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { while self.ready_for_next_connection() { match self.messages.poll()? { Async::NotReady => { break; } Async::Ready(None) => { return Ok(Async::Ready(())); } Async::Ready(Some(SubscriberMsg::NewMessage(msg))) => { self.handle_new_message(msg.subscription, msg.result); } Async::Ready(Some(SubscriberMsg::NewSubscriber(id, chan))) => { self.handle_new_subscription(id, chan); } Async::Ready(Some(SubscriberMsg::RemoveSubscriber(id))) => { self.handle_removal(id); } } } if self.should_shut_down { trace!( "shutting down notification handler for notification '{}'", self.notification_method ); Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } } /// A trait for constructing the usual client handles with coupled `Subscriber` structs. pub trait SubscriberTransport: DuplexTransport { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ); } /// Subscriber transport trait allows one to create a client future, a subscriber and a client /// handle from a valid JSON-RPC transport. impl<T: DuplexTransport> SubscriberTransport for T { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ) { let (server, server_handle) = Server::new(); let (client, client_handle) = self.with_server(server); let subscriber = Subscriber::new(executor, client_handle.clone(), server_handle); (client, client_handle, subscriber) } }
fmt
identifier_name
lib.rs
//! This crate adds support for subscriptions as defined in [here]. //! //! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB extern crate futures; extern crate jsonrpc_client_core; extern crate jsonrpc_client_utils; #[macro_use] extern crate serde; extern crate serde_json; extern crate tokio; #[macro_use] extern crate log; #[macro_use] extern crate error_chain; use futures::{future, future::Either, sync::mpsc, Async, Future, Poll, Sink, Stream}; use jsonrpc_client_core::server::{ types::Params, Handler, HandlerSettingError, Server, ServerHandle, }; use jsonrpc_client_core::{ ClientHandle, DuplexTransport, Error as CoreError, ErrorKind as CoreErrorKind, }; use serde_json::Value; use std::collections::BTreeMap; use std::fmt; use std::marker::PhantomData; use tokio::prelude::future::Executor; use jsonrpc_client_utils::select_weak::{SelectWithWeak, SelectWithWeakExt}; error_chain! { links { Core(CoreError, CoreErrorKind); } foreign_links { HandlerError(HandlerSettingError); SpawnError(tokio::executor::SpawnError); } } #[derive(Debug, Deserialize)] struct SubscriptionMessage { subscription: SubscriptionId, result: Value, } /// A stream of messages from a subscription. #[derive(Debug)] pub struct Subscription<T: serde::de::DeserializeOwned> { rx: mpsc::Receiver<Value>, id: Option<SubscriptionId>, handler_chan: mpsc::UnboundedSender<SubscriberMsg>, _marker: PhantomData<T>, } impl<T: serde::de::DeserializeOwned> Stream for Subscription<T> { type Item = T; type Error = CoreError; fn poll(&mut self) -> Poll<Option<T>, CoreError> { match self.rx.poll().map_err(|_: ()| CoreErrorKind::Shutdown)? { Async::Ready(Some(v)) => Ok(Async::Ready(Some( serde_json::from_value(v).map_err(|_| CoreErrorKind::DeserializeError)?, ))), Async::Ready(None) => Ok(Async::Ready(None)), Async::NotReady => Ok(Async::NotReady), } } } impl<T: serde::de::DeserializeOwned> Drop for Subscription<T> { fn drop(&mut self) { if let Some(id) = self.id.take() { let _ = self .handler_chan .unbounded_send(SubscriberMsg::RemoveSubscriber(id)); } } } /// A subscriber creates new subscriptions. #[derive(Debug)] pub struct Subscriber<E: Executor<Box<Future<Item = (), Error = ()> + Send>>> { client_handle: ClientHandle, handlers: ServerHandle, notification_handlers: BTreeMap<String, mpsc::UnboundedSender<SubscriberMsg>>, executor: E, } impl<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized> Subscriber<E> { /// Constructs a new subscriber with the provided executor. pub fn new(executor: E, client_handle: ClientHandle, handlers: ServerHandle) -> Self { let notification_handlers = BTreeMap::new(); Self { client_handle, handlers, notification_handlers, executor, } } /// Creates a new subscription with the given method names and parameters. Parameters /// `sub_method` and `unsub_method` are only taken into account if this is the first time a /// subscription for `notification` has been created in the lifetime of this `Subscriber`. pub fn subscribe<T, P>( &mut self, sub_method: String, unsub_method: String, notification_method: String, buffer_size: usize, sub_parameters: P, ) -> impl Future<Item = Subscription<T>, Error = Error> where T: serde::de::DeserializeOwned +'static, P: serde::Serialize +'static, { // Get a channel to an existing notification handler or spawn a new one. let chan = self .notification_handlers .get(&notification_method) .filter(|c| c.is_closed()) .map(|chan| Ok(chan.clone())) .unwrap_or_else(|| { self.spawn_notification_handler(notification_method.clone(), unsub_method) }); let (sub_tx, sub_rx) = mpsc::channel(buffer_size); match chan { Ok(chan) => Either::A( self.client_handle .call_method(sub_method, &sub_parameters) .map_err(|e| e.into()) .and_then(move |id: SubscriptionId| { if let Err(_) = chan.unbounded_send(SubscriberMsg::NewSubscriber(id.clone(), sub_tx)) { debug!( "Notificaton handler for {} - {} already closed", notification_method, id ); }; Ok(Subscription { rx: sub_rx, id: Some(id), handler_chan: chan.clone(), _marker: PhantomData::<T>, }) }), ), Err(e) => Either::B(future::err(e)), } } fn spawn_notification_handler( &mut self, notification_method: String, unsub_method: String, ) -> Result<mpsc::UnboundedSender<SubscriberMsg>> { let (msg_tx, msg_rx) = mpsc::channel(0); self.handlers .add( notification_method.clone(), Handler::Notification(Box::new(move |notification| { let fut = match params_to_subscription_message(notification.params) { Some(msg) => Either::A( msg_tx .clone() .send(msg) .map(|_| ()) .map_err(|_| CoreErrorKind::Shutdown.into()), ), None => { error!( "Received notification with invalid parameters for subscription - {}", notification.method ); Either::B(futures::future::ok(())) } }; Box::new(fut) })), ) .wait()?; let (control_tx, control_rx) = mpsc::unbounded(); let notification_handler = NotificationHandler::new( notification_method.clone(), self.handlers.clone(), self.client_handle.clone(), unsub_method, msg_rx, control_rx, ); if let Err(e) = self .executor .execute(Box::new(notification_handler.map_err(|_| ()))) { error!("Failed to spawn notification handler - {:?}", e); }; self.notification_handlers .insert(notification_method, control_tx.clone()); Ok(control_tx) } } fn params_to_subscription_message(params: Option<Params>) -> Option<SubscriberMsg> { params .and_then(|p| p.parse().ok()) .map(SubscriberMsg::NewMessage) } #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Debug, Deserialize)] #[serde(untagged)] enum SubscriptionId { Num(u64), String(String), } impl fmt::Display for SubscriptionId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { SubscriptionId::Num(n) => write!(f, "{}", n), SubscriptionId::String(s) => write!(f, "{}", s), } } } #[derive(Debug)] enum SubscriberMsg { NewMessage(SubscriptionMessage), NewSubscriber(SubscriptionId, mpsc::Sender<Value>), RemoveSubscriber(SubscriptionId), } // A single notification can receive messages for different subscribers for the same notification. struct NotificationHandler { notification_method: String, subscribers: BTreeMap<SubscriptionId, mpsc::Sender<Value>>, messages: SelectWithWeak<mpsc::Receiver<SubscriberMsg>, mpsc::UnboundedReceiver<SubscriberMsg>>, unsub_method: String, client_handle: ClientHandle, current_future: Option<Box<dyn Future<Item = (), Error = ()> + Send>>, server_handlers: ServerHandle, should_shut_down: bool, } impl Drop for NotificationHandler { fn drop(&mut self) { let _ = self .server_handlers .remove(self.notification_method.clone()); } } impl NotificationHandler { fn new( notification_method: String, server_handlers: ServerHandle, client_handle: ClientHandle, unsub_method: String, subscription_messages: mpsc::Receiver<SubscriberMsg>, control_messages: mpsc::UnboundedReceiver<SubscriberMsg>, ) -> Self { let messages = subscription_messages.select_with_weak(control_messages); Self { notification_method, messages, server_handlers, unsub_method, subscribers: BTreeMap::new(), client_handle, current_future: None, should_shut_down: false, } } fn handle_new_subscription(&mut self, id: SubscriptionId, chan: mpsc::Sender<Value>) { self.subscribers.insert(id, chan); } fn handle_removal(&mut self, id: SubscriptionId) { if let None = self.subscribers.remove(&id) { debug!("Removing non-existant subscriber - {}", &id); }; let fut = self .client_handle .call_method(self.unsub_method.clone(), &[0u8; 0]) .map(|_r: bool| ()) .map_err(|e| trace!("Failed to unsubscribe - {}", e)); self.should_shut_down = self.subscribers.len() < 1; self.current_future = Some(Box::new(fut)); } fn handle_new_message(&mut self, id: SubscriptionId, message: Value) { match self.subscribers.get(&id) { Some(chan) => { let fut = chan .clone() .send(message) .map_err(move |_| trace!("Subscriber already gone: {}", id)) .map(|_| ()); self.current_future = Some(Box::new(fut)); } None => trace!("Received message for non existant subscription - {}", id), } } fn ready_for_next_connection(&mut self) -> bool { match self.current_future.take() { None => true, Some(mut fut) => match fut.poll() { Ok(Async::NotReady) =>
_ => true, }, } } } impl Future for NotificationHandler { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { while self.ready_for_next_connection() { match self.messages.poll()? { Async::NotReady => { break; } Async::Ready(None) => { return Ok(Async::Ready(())); } Async::Ready(Some(SubscriberMsg::NewMessage(msg))) => { self.handle_new_message(msg.subscription, msg.result); } Async::Ready(Some(SubscriberMsg::NewSubscriber(id, chan))) => { self.handle_new_subscription(id, chan); } Async::Ready(Some(SubscriberMsg::RemoveSubscriber(id))) => { self.handle_removal(id); } } } if self.should_shut_down { trace!( "shutting down notification handler for notification '{}'", self.notification_method ); Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } } /// A trait for constructing the usual client handles with coupled `Subscriber` structs. pub trait SubscriberTransport: DuplexTransport { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ); } /// Subscriber transport trait allows one to create a client future, a subscriber and a client /// handle from a valid JSON-RPC transport. impl<T: DuplexTransport> SubscriberTransport for T { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ) { let (server, server_handle) = Server::new(); let (client, client_handle) = self.with_server(server); let subscriber = Subscriber::new(executor, client_handle.clone(), server_handle); (client, client_handle, subscriber) } }
{ self.current_future = Some(fut); false }
conditional_block
lib.rs
//! This crate adds support for subscriptions as defined in [here].
extern crate jsonrpc_client_utils; #[macro_use] extern crate serde; extern crate serde_json; extern crate tokio; #[macro_use] extern crate log; #[macro_use] extern crate error_chain; use futures::{future, future::Either, sync::mpsc, Async, Future, Poll, Sink, Stream}; use jsonrpc_client_core::server::{ types::Params, Handler, HandlerSettingError, Server, ServerHandle, }; use jsonrpc_client_core::{ ClientHandle, DuplexTransport, Error as CoreError, ErrorKind as CoreErrorKind, }; use serde_json::Value; use std::collections::BTreeMap; use std::fmt; use std::marker::PhantomData; use tokio::prelude::future::Executor; use jsonrpc_client_utils::select_weak::{SelectWithWeak, SelectWithWeakExt}; error_chain! { links { Core(CoreError, CoreErrorKind); } foreign_links { HandlerError(HandlerSettingError); SpawnError(tokio::executor::SpawnError); } } #[derive(Debug, Deserialize)] struct SubscriptionMessage { subscription: SubscriptionId, result: Value, } /// A stream of messages from a subscription. #[derive(Debug)] pub struct Subscription<T: serde::de::DeserializeOwned> { rx: mpsc::Receiver<Value>, id: Option<SubscriptionId>, handler_chan: mpsc::UnboundedSender<SubscriberMsg>, _marker: PhantomData<T>, } impl<T: serde::de::DeserializeOwned> Stream for Subscription<T> { type Item = T; type Error = CoreError; fn poll(&mut self) -> Poll<Option<T>, CoreError> { match self.rx.poll().map_err(|_: ()| CoreErrorKind::Shutdown)? { Async::Ready(Some(v)) => Ok(Async::Ready(Some( serde_json::from_value(v).map_err(|_| CoreErrorKind::DeserializeError)?, ))), Async::Ready(None) => Ok(Async::Ready(None)), Async::NotReady => Ok(Async::NotReady), } } } impl<T: serde::de::DeserializeOwned> Drop for Subscription<T> { fn drop(&mut self) { if let Some(id) = self.id.take() { let _ = self .handler_chan .unbounded_send(SubscriberMsg::RemoveSubscriber(id)); } } } /// A subscriber creates new subscriptions. #[derive(Debug)] pub struct Subscriber<E: Executor<Box<Future<Item = (), Error = ()> + Send>>> { client_handle: ClientHandle, handlers: ServerHandle, notification_handlers: BTreeMap<String, mpsc::UnboundedSender<SubscriberMsg>>, executor: E, } impl<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized> Subscriber<E> { /// Constructs a new subscriber with the provided executor. pub fn new(executor: E, client_handle: ClientHandle, handlers: ServerHandle) -> Self { let notification_handlers = BTreeMap::new(); Self { client_handle, handlers, notification_handlers, executor, } } /// Creates a new subscription with the given method names and parameters. Parameters /// `sub_method` and `unsub_method` are only taken into account if this is the first time a /// subscription for `notification` has been created in the lifetime of this `Subscriber`. pub fn subscribe<T, P>( &mut self, sub_method: String, unsub_method: String, notification_method: String, buffer_size: usize, sub_parameters: P, ) -> impl Future<Item = Subscription<T>, Error = Error> where T: serde::de::DeserializeOwned +'static, P: serde::Serialize +'static, { // Get a channel to an existing notification handler or spawn a new one. let chan = self .notification_handlers .get(&notification_method) .filter(|c| c.is_closed()) .map(|chan| Ok(chan.clone())) .unwrap_or_else(|| { self.spawn_notification_handler(notification_method.clone(), unsub_method) }); let (sub_tx, sub_rx) = mpsc::channel(buffer_size); match chan { Ok(chan) => Either::A( self.client_handle .call_method(sub_method, &sub_parameters) .map_err(|e| e.into()) .and_then(move |id: SubscriptionId| { if let Err(_) = chan.unbounded_send(SubscriberMsg::NewSubscriber(id.clone(), sub_tx)) { debug!( "Notificaton handler for {} - {} already closed", notification_method, id ); }; Ok(Subscription { rx: sub_rx, id: Some(id), handler_chan: chan.clone(), _marker: PhantomData::<T>, }) }), ), Err(e) => Either::B(future::err(e)), } } fn spawn_notification_handler( &mut self, notification_method: String, unsub_method: String, ) -> Result<mpsc::UnboundedSender<SubscriberMsg>> { let (msg_tx, msg_rx) = mpsc::channel(0); self.handlers .add( notification_method.clone(), Handler::Notification(Box::new(move |notification| { let fut = match params_to_subscription_message(notification.params) { Some(msg) => Either::A( msg_tx .clone() .send(msg) .map(|_| ()) .map_err(|_| CoreErrorKind::Shutdown.into()), ), None => { error!( "Received notification with invalid parameters for subscription - {}", notification.method ); Either::B(futures::future::ok(())) } }; Box::new(fut) })), ) .wait()?; let (control_tx, control_rx) = mpsc::unbounded(); let notification_handler = NotificationHandler::new( notification_method.clone(), self.handlers.clone(), self.client_handle.clone(), unsub_method, msg_rx, control_rx, ); if let Err(e) = self .executor .execute(Box::new(notification_handler.map_err(|_| ()))) { error!("Failed to spawn notification handler - {:?}", e); }; self.notification_handlers .insert(notification_method, control_tx.clone()); Ok(control_tx) } } fn params_to_subscription_message(params: Option<Params>) -> Option<SubscriberMsg> { params .and_then(|p| p.parse().ok()) .map(SubscriberMsg::NewMessage) } #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Debug, Deserialize)] #[serde(untagged)] enum SubscriptionId { Num(u64), String(String), } impl fmt::Display for SubscriptionId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { SubscriptionId::Num(n) => write!(f, "{}", n), SubscriptionId::String(s) => write!(f, "{}", s), } } } #[derive(Debug)] enum SubscriberMsg { NewMessage(SubscriptionMessage), NewSubscriber(SubscriptionId, mpsc::Sender<Value>), RemoveSubscriber(SubscriptionId), } // A single notification can receive messages for different subscribers for the same notification. struct NotificationHandler { notification_method: String, subscribers: BTreeMap<SubscriptionId, mpsc::Sender<Value>>, messages: SelectWithWeak<mpsc::Receiver<SubscriberMsg>, mpsc::UnboundedReceiver<SubscriberMsg>>, unsub_method: String, client_handle: ClientHandle, current_future: Option<Box<dyn Future<Item = (), Error = ()> + Send>>, server_handlers: ServerHandle, should_shut_down: bool, } impl Drop for NotificationHandler { fn drop(&mut self) { let _ = self .server_handlers .remove(self.notification_method.clone()); } } impl NotificationHandler { fn new( notification_method: String, server_handlers: ServerHandle, client_handle: ClientHandle, unsub_method: String, subscription_messages: mpsc::Receiver<SubscriberMsg>, control_messages: mpsc::UnboundedReceiver<SubscriberMsg>, ) -> Self { let messages = subscription_messages.select_with_weak(control_messages); Self { notification_method, messages, server_handlers, unsub_method, subscribers: BTreeMap::new(), client_handle, current_future: None, should_shut_down: false, } } fn handle_new_subscription(&mut self, id: SubscriptionId, chan: mpsc::Sender<Value>) { self.subscribers.insert(id, chan); } fn handle_removal(&mut self, id: SubscriptionId) { if let None = self.subscribers.remove(&id) { debug!("Removing non-existant subscriber - {}", &id); }; let fut = self .client_handle .call_method(self.unsub_method.clone(), &[0u8; 0]) .map(|_r: bool| ()) .map_err(|e| trace!("Failed to unsubscribe - {}", e)); self.should_shut_down = self.subscribers.len() < 1; self.current_future = Some(Box::new(fut)); } fn handle_new_message(&mut self, id: SubscriptionId, message: Value) { match self.subscribers.get(&id) { Some(chan) => { let fut = chan .clone() .send(message) .map_err(move |_| trace!("Subscriber already gone: {}", id)) .map(|_| ()); self.current_future = Some(Box::new(fut)); } None => trace!("Received message for non existant subscription - {}", id), } } fn ready_for_next_connection(&mut self) -> bool { match self.current_future.take() { None => true, Some(mut fut) => match fut.poll() { Ok(Async::NotReady) => { self.current_future = Some(fut); false } _ => true, }, } } } impl Future for NotificationHandler { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { while self.ready_for_next_connection() { match self.messages.poll()? { Async::NotReady => { break; } Async::Ready(None) => { return Ok(Async::Ready(())); } Async::Ready(Some(SubscriberMsg::NewMessage(msg))) => { self.handle_new_message(msg.subscription, msg.result); } Async::Ready(Some(SubscriberMsg::NewSubscriber(id, chan))) => { self.handle_new_subscription(id, chan); } Async::Ready(Some(SubscriberMsg::RemoveSubscriber(id))) => { self.handle_removal(id); } } } if self.should_shut_down { trace!( "shutting down notification handler for notification '{}'", self.notification_method ); Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } } /// A trait for constructing the usual client handles with coupled `Subscriber` structs. pub trait SubscriberTransport: DuplexTransport { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ); } /// Subscriber transport trait allows one to create a client future, a subscriber and a client /// handle from a valid JSON-RPC transport. impl<T: DuplexTransport> SubscriberTransport for T { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ) { let (server, server_handle) = Server::new(); let (client, client_handle) = self.with_server(server); let subscriber = Subscriber::new(executor, client_handle.clone(), server_handle); (client, client_handle, subscriber) } }
//! //! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB extern crate futures; extern crate jsonrpc_client_core;
random_line_split
boxed.rs
self.ptr.as_ptr(), self.len, ) } } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. This [`Box`] will be unlocked and *must* be locked before /// it is dropped. /// /// TODO: make `len` a `NonZero` when it's stabilized and remove the /// related panic. fn new_unlocked(len: usize) -> Self { tested!(len == 0); tested!(std::mem::size_of::<T>() == 0); assert!(sodium::init(), "secrets: failed to initialize libsodium"); // `sodium::allocarray` returns a memory location that already // allows r/w access let ptr = NonNull::new(unsafe { sodium::allocarray::<T>(len) }) .expect("secrets: failed to allocate memory"); // NOTE: We technically could save a little extra work here by // initializing the struct with [`Prot::NoAccess`] and a zero // refcount, and manually calling `mprotect` when finished with // initialization. However, the `as_mut()` call performs sanity // checks that ensure it's [`Prot::ReadWrite`] so it's easier to // just send everything through the "normal" code paths. Self { ptr, len, prot: Cell::new(Prot::ReadWrite), refs: Cell::new(1), } } /// Performs the underlying retain half of the retain/release logic /// for monitoring outstanding calls to unlock. fn retain(&self, prot: Prot) { let refs = self.refs.get(); tested!(refs == RefCount::min_value()); tested!(refs == RefCount::max_value()); tested!(prot == Prot::NoAccess); if refs == 0 { // when retaining, we must retain to a protection level with // some access proven!(prot!= Prot::NoAccess, "secrets: must retain readably or writably"); // allow access to the pointer and record what level of // access is being permitted // // ordering probably doesn't matter here, but we set our // internal protection flag first so we never run the risk // of believing that memory is protected when it isn't self.prot.set(prot); mprotect(self.ptr.as_ptr(), prot); } else { // if we have a nonzero retain count, there is nothing to // change, but we can assert some invariants: // // * our current protection level *must not* be // [`Prot::NoAccess`] or we have underflowed the ref // counter // * our current protection level *must not* be // [`Prot::ReadWrite`] because that would imply non- // exclusive mutable access // * our target protection level *must* be `ReadOnly` // since otherwise would involve changing the protection // level of a currently-borrowed resource proven!(Prot::NoAccess!= self.prot.get(), "secrets: out-of-order retain/release detected"); proven!(Prot::ReadWrite!= self.prot.get(), "secrets: cannot unlock mutably more than once"); proven!(Prot::ReadOnly == prot, "secrets: cannot unlock mutably while unlocked immutably"); } // "255 retains ought to be enough for anybody" // // We use `checked_add` to ensure we don't overflow our ref // counter. This is ensured even in production builds because // it's infeasible for consumers of this API to actually enforce // this. That said, it's unlikely that anyone would need to // have more than 255 outstanding retains at one time. // // This also protects us in the event of balanced, out-of-order // retain/release code. If an out-of-order `release` causes the // ref counter to wrap around below zero, the subsequent // `retain` will panic here. match refs.checked_add(1) { Some(v) => self.refs.set(v), None if self.is_locked() => panic!("secrets: out-of-order retain/release detected"), None => panic!("secrets: retained too many times"), }; } /// Removes one outsdanding retain, and changes the memory /// protection level back to [`Prot::NoAccess`] when the number of /// outstanding retains reaches zero. fn release(&self) { // When releasing, we should always have at least one retain // outstanding. This is enforced by all users through // refcounting on allocation and drop. proven!(self.refs.get()!= 0, "secrets: releases exceeded retains"); // When releasing, our protection level must allow some kind of // access. If this condition isn't true, it was already // [`Prot::NoAccess`] so at least the memory was protected. proven!(self.prot.get()!= Prot::NoAccess, "secrets: releasing memory that's already locked"); // Deciding whether or not to use `checked_sub` or // `wrapping_sub` here has pros and cons. The `proven!`s above // help us catch this kind of accident in development, but if // a released library has a bug that has imbalanced // retains/releases, `wrapping_sub` will cause the refcount to // underflow and wrap. // // `checked_sub` ensures that wrapping won't happen, but will // cause consistency issues in the event of balanced but // *out-of-order* calls to retain/release. In such a scenario, // this will cause the retain count to be nonzero at drop time, // leaving the memory unlocked for an indeterminate period of // time. // // We choose `wrapped_sub` here because, by undeflowing, it will // ensure that a subsequent `retain` will not unlock the memory // and will trigger a `checked_add` runtime panic which we find // preferable for safety purposes. let refs = self.refs.get().wrapping_sub(1); self.refs.set(refs); if refs == 0 { mprotect(self.ptr.as_ptr(), Prot::NoAccess); self.prot.set(Prot::NoAccess); } } /// Returns true if the protection level is [`NoAccess`]. Ignores /// ref count. fn is_locked(&self) -> bool { self.prot.get() == Prot::NoAccess } } impl<T: Bytes + Randomizable> Box<T> { /// Instantiates a new [`Box`] with crypotgraphically-randomized /// contents. pub(crate) fn random(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().randomize()) } } impl<T: Bytes + Zeroable> Box<T> { /// Instantiates a new [`Box`] whose backing memory is zeroed. pub(crate) fn zero(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().zero()) } } impl<T: Bytes> Drop for Box<T> { fn drop(&mut self) { // [`Drop::drop`] is called during stack unwinding, so we may be // in a panic already. if!thread::panicking() { // If this value is being dropped, we want to ensure that // every retain has been balanced with a release. If this // is not true in release, the memory will be freed // momentarily so we don't need to worry about it. proven!(self.refs.get() == 0, "secrets: retains exceeded releases"); // Similarly, any dropped value should have previously been // set to deny any access. proven!(self.prot.get() == Prot::NoAccess, "secrets: dropped secret was still accessible"); } unsafe { sodium::free(self.ptr.as_mut()) } } } impl<T: Bytes> Debug for Box<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{{ {} bytes redacted }}", self.size()) } } impl<T: Bytes> Clone for Box<T> { fn clone(&self) -> Self { Self::new(self.len, |b| { b.as_mut_slice().copy_from_slice(self.unlock().as_slice()); self.lock(); }) } } impl<T: Bytes + ConstantEq> PartialEq for Box<T> { fn eq(&self, other: &Self) -> bool { if self.len!= other.len { return false; } let lhs = self.unlock().as_slice(); let rhs = other.unlock().as_slice(); let ret = lhs.constant_eq(rhs); self.lock(); other.lock(); ret } } impl<T: Bytes + Zeroable> From<&mut T> for Box<T> { fn from(data: &mut T) -> Self { // this is safe since the secret and data can never overlap Self::new(1, |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut()) } }) } } impl<T: Bytes + Zeroable> From<&mut [T]> for Box<T> { fn from(data: &mut [T]) -> Self { // this is safe since the secret and data can never overlap Self::new(data.len(), |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut_slice()) } }) } } unsafe impl<T: Bytes + Send> Send for Box<T> {} /// Immediately changes the page protection level on `ptr` to `prot`. fn mprotect<T>(ptr: *mut T, prot: Prot) { if!match prot { Prot::NoAccess => unsafe { sodium::mprotect_noaccess(ptr) }, Prot::ReadOnly => unsafe { sodium::mprotect_readonly(ptr) }, Prot::ReadWrite => unsafe { sodium::mprotect_readwrite(ptr) }, } { panic!("secrets: error setting memory protection to {:?}", prot); } } // LCOV_EXCL_START #[cfg(test)] mod tests { use super::*; #[test] fn it_allows_custom_initialization() { let boxed = Box::<u8>::new(1, |secret| { secret.as_mut_slice().clone_from_slice(b"\x04"); }); assert_eq!(boxed.unlock().as_slice(), [0x04]); boxed.lock(); } #[test] fn it_initializes_with_garbage() { let boxed = Box::<u8>::new(4, |_| {}); let unboxed = boxed.unlock().as_slice(); // sodium changed the value of the garbage byte they used, so we // allocate a byte and see what's inside to probe for the // specific value let garbage = unsafe { let garbage_ptr = sodium::allocarray::<u8>(1); let garbage_byte = *garbage_ptr; sodium::free(garbage_ptr); vec![garbage_byte; unboxed.len()] }; // sanity-check the garbage byte in case we have a bug in how we // probe for it assert_ne!(garbage, vec![0; garbage.len()]); assert_eq!(unboxed, &garbage[..]); boxed.lock(); } #[test] fn it_initializes_with_zero() { let boxed = Box::<u32>::zero(4); assert_eq!(boxed.unlock().as_slice(), [0, 0, 0, 0]); boxed.lock(); } #[test] fn it_initializes_from_values() { let mut value = [4_u64]; let boxed = Box::from(&mut value[..]); assert_eq!(value, [0]); assert_eq!(boxed.unlock().as_slice(), [4]); boxed.lock(); } #[test] fn it_compares_equality() { let boxed_1 = Box::<u8>::random(1); let boxed_2 = boxed_1.clone(); assert_eq!(boxed_1, boxed_2); assert_eq!(boxed_2, boxed_1); } #[test] fn it_compares_inequality() { let boxed_1 = Box::<u128>::random(32); let boxed_2 = Box::<u128>::random(32); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_compares_inequality_using_size() { let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]); let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_initializes_with_zero_refs() { let boxed = Box::<u8>::zero(10); assert_eq!(0, boxed.refs.get()); } #[test] fn it_tracks_ref_counts_accurately() { let mut boxed = Box::<u8>::random(10); let _ = boxed.unlock(); let _ = boxed.unlock(); let _ = boxed.unlock(); assert_eq!(3, boxed.refs.get()); boxed.lock(); boxed.lock(); boxed.lock(); assert_eq!(0, boxed.refs.get()); let _ = boxed.unlock_mut(); assert_eq!(1, boxed.refs.get()); boxed.lock(); assert_eq!(0, boxed.refs.get()); } #[test] fn it_doesnt_overflow_early() { let boxed = Box::<u64>::zero(4); for _ in 0..u8::max_value() { let _ = boxed.unlock(); } for _ in 0..u8::max_value() { boxed.lock(); } } #[test] fn it_allows_arbitrary_readers() { let boxed = Box::<u8>::zero(1); let mut count = 0_u8; sodium::memrandom(count.as_mut_bytes()); for _ in 0..count { let _ = boxed.unlock(); } for _ in 0..count { boxed.lock() } } #[test] fn it_can_be_sent_between_threads() { use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let child = thread::spawn(move || { let boxed = Box::<u64>::random(1); let value = boxed.unlock().as_slice().to_vec(); // here we send an *unlocked* Box to the rx side; this lets // us make sure that the sent Box isn't dropped when this // thread exits, and that the other thread gets an unlocked // Box that it's responsible for locking tx.send((boxed, value)).expect("failed to send to channel"); }); let (boxed, value) = rx.recv().expect("failed to read from channel"); assert_eq!(Prot::ReadOnly, boxed.prot.get()); assert_eq!(value, boxed.as_slice()); child.join().expect("child terminated"); boxed.lock(); } #[test] #[should_panic(expected = "secrets: retained too many times")] fn it_doesnt_allow_overflowing_readers() { let boxed = Box::<[u64; 8]>::zero(4); for _ in 0..=u8::max_value() { let _ = boxed.unlock(); } // this ensures that we *don't* inadvertently panic if we // somehow made it through the above statement for _ in 0..boxed.refs.get() { boxed.lock() } } #[test] #[should_panic(expected = "secrets: out-of-order retain/release detected")] fn it_detects_out_of_order_retains_and_releases_that_underflow() { let boxed = Box::<u8>::zero(5); // manually set up this condition, since doing it using the // wrappers will cause other panics to happen boxed.refs.set(boxed.refs.get().wrapping_sub(1)); boxed.prot.set(Prot::NoAccess); boxed.retain(Prot::ReadOnly); } #[test] #[should_panic(expected = "secrets: failed to initialize libsodium")] fn it_detects_sodium_init_failure() { sodium::fail(); let _ = Box::<u8>::zero(0); } #[test] #[should_panic(expected = "secrets: error setting memory protection to NoAccess")] fn it_detects_sodium_mprotect_failure() { sodium::fail(); mprotect(std::ptr::null_mut::<u8>(), Prot::NoAccess); } } // There isn't a great way to run these tests on systems that don't have a native `fork()` call, so // we'll just skip them for now. #[cfg(all(test, target_family = "unix"))] mod tests_sigsegv { use super::*; use std::process; fn assert_sigsegv<F>(f: F) where F: FnOnce(), { unsafe { let pid : libc::pid_t = libc::fork(); let mut stat : libc::c_int = 0; match pid { -1 => panic!("`fork(2)` failed"), 0 => { f(); process::exit(0) }, _ => { if libc::waitpid(pid, &mut stat, 0) == -1 { panic!("`waitpid(2)` failed"); }; // assert that the process terminated due to a signal assert!(libc::WIFSIGNALED(stat)); // assert that we received a SIGBUS or SIGSEGV, // either of which can be sent by an attempt to // access protected memory regions assert!( libc::WTERMSIG(stat) == libc::SIGBUS || libc::WTERMSIG(stat) == libc::SIGSEGV ); } } } } #[test] fn it_kills_attempts_to_read_while_locked() { assert_sigsegv(|| { let val = unsafe { Box::<u32>::zero(1).ptr.as_ptr().read() }; // TODO: replace with [`test::black_box`] when stable let _ = sodium::memcmp(val.as_bytes(), val.as_bytes()); }); } #[test] fn it_kills_attempts_to_write_while_locked() { assert_sigsegv(|| { unsafe { Box::<u64>::zero(1).ptr.as_ptr().write(1) }; }); } #[test] fn it_kills_attempts_to_read_after_explicitly_locked() { assert_sigsegv(|| { let boxed = Box::<u32>::random(4); let val = boxed.unlock().as_slice(); let _ = boxed.unlock(); boxed.lock(); boxed.lock(); let _ = sodium::memcmp( val.as_bytes(), val.as_bytes(), ); }); } } #[cfg(all(test, profile = "debug"))] mod tests_proven_statements { use super::*; #[test] #[should_panic(expected = "secrets: attempted to dereference a zero-length pointer")] fn it_doesnt_allow_referencing_zero_length() { let boxed = Box::<u8>::new_unlocked(0); let _ = boxed.as_ref(); } #[test] #[should_panic(expected = "secrets: cannot unlock mutably more than once")] fn it_doesnt_allow_multiple_writers() { let mut boxed = Box::<u64>::zero(1); let _ = boxed.unlock_mut(); let _ = boxed.unlock_mut(); } #[test]
#[should_panic(expected = "secrets: releases exceeded retains")] fn it_doesnt_allow_negative_users() { Box::<u64>::zero(10).lock(); }
random_line_split
boxed.rs
const_for_fn)] // not usable on min supported Rust pub(crate) fn is_empty(&self) -> bool { self.len == 0 } /// Returns the size in bytes of the data contained in the [`Box`]. /// This does not include incidental metadata used in the /// implementation of [`Box`] itself, only the size of the data /// allocated on behalf of the user. /// /// It is the maximum number of bytes that can be read from the /// internal pointer. pub(crate) fn size(&self) -> usize { self.len * T::size() } /// Allows the contents of the [`Box`] to be read from. Any call to /// this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock(&self) -> &Self { self.retain(Prot::ReadOnly); self } /// Allows the contents of the [`Box`] to be read from and written /// to. Any call to this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock_mut(&mut self) -> &mut Self { self.retain(Prot::ReadWrite); self } /// Disables all access to the underlying memory. Must only be /// called to precisely balance prior calls to [`unlock`](Box::unlock) /// and [`unlock_mut`](Box::unlock_mut). /// /// Calling this method in excess of the number of outstanding /// unlocks will result in a runtime panic. Omitting a call to this /// method and leaving an outstanding unlock will result in a /// runtime panic when this object is dropped. pub(crate) fn lock(&self) { self.release(); } /// Converts the [`Box`]'s contents into a reference. This must only /// happen while it is unlocked, and the reference must go out of /// scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_ref(&self) -> &T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get()!= Prot::NoAccess, "secrets: may not call Box::as_ref while locked"); unsafe { self.ptr.as_ref() } } /// Converts the [`Box`]'s contents into a mutable reference. This /// must only happen while it is mutably unlocked, and the slice /// must go out of scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_mut(&mut self) -> &mut T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut unless mutably unlocked"); unsafe { self.ptr.as_mut() } } /// Converts the [`Box`]'s contents into a slice. This must only /// happen while it is unlocked, and the slice must go out of scope /// before it is locked. pub(crate) fn as_slice(&self) -> &[T] { // NOTE: after some consideration, I've decided that this method // and its as_mut_slice() sister *are* safe. // // Using the retuned ref might cause a SIGSEGV, but this is not // UB (in fact, it's explicitly defined behavior!), cannot cause // a data race, cannot produce an invalid primitive, nor can it // break any other guarantee of "safe Rust". Just a SIGSEGV. // // However, as currently used by wrappers in this crate, these // methods are *never* called on unlocked data. Doing so would // be indicative of a bug, so we want to detect this during // development. If it happens in release mode, it's not // explicitly unsafe so we don't need to enable this check. proven!(self.prot.get()!= Prot::NoAccess, "secrets: may not call Box::as_slice while locked"); unsafe { slice::from_raw_parts( self.ptr.as_ptr(), self.len, ) } } /// Converts the [`Box`]'s contents into a mutable slice. This must /// only happen while it is mutably unlocked, and the slice must go /// out of scope before it is locked. pub(crate) fn as_mut_slice(&mut self) -> &mut [T] { proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut_slice unless mutably unlocked"); unsafe { slice::from_raw_parts_mut( self.ptr.as_ptr(), self.len, ) } } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. This [`Box`] will be unlocked and *must* be locked before /// it is dropped. /// /// TODO: make `len` a `NonZero` when it's stabilized and remove the /// related panic. fn new_unlocked(len: usize) -> Self { tested!(len == 0); tested!(std::mem::size_of::<T>() == 0); assert!(sodium::init(), "secrets: failed to initialize libsodium"); // `sodium::allocarray` returns a memory location that already // allows r/w access let ptr = NonNull::new(unsafe { sodium::allocarray::<T>(len) }) .expect("secrets: failed to allocate memory"); // NOTE: We technically could save a little extra work here by // initializing the struct with [`Prot::NoAccess`] and a zero // refcount, and manually calling `mprotect` when finished with // initialization. However, the `as_mut()` call performs sanity // checks that ensure it's [`Prot::ReadWrite`] so it's easier to // just send everything through the "normal" code paths. Self { ptr, len, prot: Cell::new(Prot::ReadWrite), refs: Cell::new(1), } } /// Performs the underlying retain half of the retain/release logic /// for monitoring outstanding calls to unlock. fn retain(&self, prot: Prot) { let refs = self.refs.get(); tested!(refs == RefCount::min_value()); tested!(refs == RefCount::max_value()); tested!(prot == Prot::NoAccess); if refs == 0 { // when retaining, we must retain to a protection level with // some access proven!(prot!= Prot::NoAccess, "secrets: must retain readably or writably"); // allow access to the pointer and record what level of // access is being permitted // // ordering probably doesn't matter here, but we set our // internal protection flag first so we never run the risk // of believing that memory is protected when it isn't self.prot.set(prot); mprotect(self.ptr.as_ptr(), prot); } else { // if we have a nonzero retain count, there is nothing to // change, but we can assert some invariants: // // * our current protection level *must not* be // [`Prot::NoAccess`] or we have underflowed the ref // counter // * our current protection level *must not* be // [`Prot::ReadWrite`] because that would imply non- // exclusive mutable access // * our target protection level *must* be `ReadOnly` // since otherwise would involve changing the protection // level of a currently-borrowed resource proven!(Prot::NoAccess!= self.prot.get(), "secrets: out-of-order retain/release detected"); proven!(Prot::ReadWrite!= self.prot.get(), "secrets: cannot unlock mutably more than once"); proven!(Prot::ReadOnly == prot, "secrets: cannot unlock mutably while unlocked immutably"); } // "255 retains ought to be enough for anybody" // // We use `checked_add` to ensure we don't overflow our ref // counter. This is ensured even in production builds because // it's infeasible for consumers of this API to actually enforce // this. That said, it's unlikely that anyone would need to // have more than 255 outstanding retains at one time. // // This also protects us in the event of balanced, out-of-order // retain/release code. If an out-of-order `release` causes the // ref counter to wrap around below zero, the subsequent // `retain` will panic here. match refs.checked_add(1) { Some(v) => self.refs.set(v), None if self.is_locked() => panic!("secrets: out-of-order retain/release detected"), None => panic!("secrets: retained too many times"), }; } /// Removes one outsdanding retain, and changes the memory /// protection level back to [`Prot::NoAccess`] when the number of /// outstanding retains reaches zero. fn release(&self) { // When releasing, we should always have at least one retain // outstanding. This is enforced by all users through // refcounting on allocation and drop. proven!(self.refs.get()!= 0, "secrets: releases exceeded retains"); // When releasing, our protection level must allow some kind of // access. If this condition isn't true, it was already // [`Prot::NoAccess`] so at least the memory was protected. proven!(self.prot.get()!= Prot::NoAccess, "secrets: releasing memory that's already locked"); // Deciding whether or not to use `checked_sub` or // `wrapping_sub` here has pros and cons. The `proven!`s above // help us catch this kind of accident in development, but if // a released library has a bug that has imbalanced // retains/releases, `wrapping_sub` will cause the refcount to // underflow and wrap. // // `checked_sub` ensures that wrapping won't happen, but will // cause consistency issues in the event of balanced but // *out-of-order* calls to retain/release. In such a scenario, // this will cause the retain count to be nonzero at drop time, // leaving the memory unlocked for an indeterminate period of // time. // // We choose `wrapped_sub` here because, by undeflowing, it will // ensure that a subsequent `retain` will not unlock the memory // and will trigger a `checked_add` runtime panic which we find // preferable for safety purposes. let refs = self.refs.get().wrapping_sub(1); self.refs.set(refs); if refs == 0 { mprotect(self.ptr.as_ptr(), Prot::NoAccess); self.prot.set(Prot::NoAccess); } } /// Returns true if the protection level is [`NoAccess`]. Ignores /// ref count. fn is_locked(&self) -> bool { self.prot.get() == Prot::NoAccess } } impl<T: Bytes + Randomizable> Box<T> { /// Instantiates a new [`Box`] with crypotgraphically-randomized /// contents. pub(crate) fn random(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().randomize()) } } impl<T: Bytes + Zeroable> Box<T> { /// Instantiates a new [`Box`] whose backing memory is zeroed. pub(crate) fn zero(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().zero()) } } impl<T: Bytes> Drop for Box<T> { fn drop(&mut self) { // [`Drop::drop`] is called during stack unwinding, so we may be // in a panic already. if!thread::panicking() { // If this value is being dropped, we want to ensure that // every retain has been balanced with a release. If this // is not true in release, the memory will be freed // momentarily so we don't need to worry about it. proven!(self.refs.get() == 0, "secrets: retains exceeded releases"); // Similarly, any dropped value should have previously been // set to deny any access. proven!(self.prot.get() == Prot::NoAccess, "secrets: dropped secret was still accessible"); } unsafe { sodium::free(self.ptr.as_mut()) } } } impl<T: Bytes> Debug for Box<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{{ {} bytes redacted }}", self.size()) } } impl<T: Bytes> Clone for Box<T> { fn clone(&self) -> Self { Self::new(self.len, |b| { b.as_mut_slice().copy_from_slice(self.unlock().as_slice()); self.lock(); }) } } impl<T: Bytes + ConstantEq> PartialEq for Box<T> { fn eq(&self, other: &Self) -> bool { if self.len!= other.len { return false; } let lhs = self.unlock().as_slice(); let rhs = other.unlock().as_slice(); let ret = lhs.constant_eq(rhs); self.lock(); other.lock(); ret } } impl<T: Bytes + Zeroable> From<&mut T> for Box<T> { fn from(data: &mut T) -> Self { // this is safe since the secret and data can never overlap Self::new(1, |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut()) } }) } } impl<T: Bytes + Zeroable> From<&mut [T]> for Box<T> { fn from(data: &mut [T]) -> Self { // this is safe since the secret and data can never overlap Self::new(data.len(), |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut_slice()) } }) } } unsafe impl<T: Bytes + Send> Send for Box<T> {} /// Immediately changes the page protection level on `ptr` to `prot`. fn mprotect<T>(ptr: *mut T, prot: Prot) { if!match prot { Prot::NoAccess => unsafe { sodium::mprotect_noaccess(ptr) }, Prot::ReadOnly => unsafe { sodium::mprotect_readonly(ptr) }, Prot::ReadWrite => unsafe { sodium::mprotect_readwrite(ptr) }, } { panic!("secrets: error setting memory protection to {:?}", prot); } } // LCOV_EXCL_START #[cfg(test)] mod tests { use super::*; #[test] fn it_allows_custom_initialization() { let boxed = Box::<u8>::new(1, |secret| { secret.as_mut_slice().clone_from_slice(b"\x04"); }); assert_eq!(boxed.unlock().as_slice(), [0x04]); boxed.lock(); } #[test] fn it_initializes_with_garbage() { let boxed = Box::<u8>::new(4, |_| {}); let unboxed = boxed.unlock().as_slice(); // sodium changed the value of the garbage byte they used, so we // allocate a byte and see what's inside to probe for the // specific value let garbage = unsafe { let garbage_ptr = sodium::allocarray::<u8>(1); let garbage_byte = *garbage_ptr; sodium::free(garbage_ptr); vec![garbage_byte; unboxed.len()] }; // sanity-check the garbage byte in case we have a bug in how we // probe for it assert_ne!(garbage, vec![0; garbage.len()]); assert_eq!(unboxed, &garbage[..]); boxed.lock(); } #[test] fn it_initializes_with_zero() { let boxed = Box::<u32>::zero(4); assert_eq!(boxed.unlock().as_slice(), [0, 0, 0, 0]); boxed.lock(); } #[test] fn it_initializes_from_values() { let mut value = [4_u64]; let boxed = Box::from(&mut value[..]); assert_eq!(value, [0]); assert_eq!(boxed.unlock().as_slice(), [4]); boxed.lock(); } #[test] fn it_compares_equality() { let boxed_1 = Box::<u8>::random(1); let boxed_2 = boxed_1.clone(); assert_eq!(boxed_1, boxed_2); assert_eq!(boxed_2, boxed_1); } #[test] fn it_compares_inequality() { let boxed_1 = Box::<u128>::random(32); let boxed_2 = Box::<u128>::random(32); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_compares_inequality_using_size()
#[test] fn it_initializes_with_zero_refs() { let boxed = Box::<u8>::zero(10); assert_eq!(0, boxed.refs.get()); } #[test] fn it_tracks_ref_counts_accurately() { let mut boxed = Box::<u8>::random(10); let _ = boxed.unlock(); let _ = boxed.unlock(); let _ = boxed.unlock(); assert_eq!(3, boxed.refs.get()); boxed.lock(); boxed.lock(); boxed.lock(); assert_eq!(0, boxed.refs.get()); let _ = boxed.unlock_mut(); assert_eq!(1, boxed.refs.get()); boxed.lock(); assert_eq!(0, boxed.refs.get()); } #[test] fn it_doesnt_overflow_early() { let boxed = Box::<u64>::zero(4); for _ in 0..u8::max_value() { let _ = boxed.unlock(); } for _ in 0..u8::max_value() { boxed.lock(); } } #[test] fn it_allows_arbitrary_readers() { let boxed = Box::<u8>::zero(1); let mut count = 0_u8; sodium::memrandom(count.as_mut_bytes()); for _ in 0..count { let _ = boxed.unlock(); } for _ in 0..count { boxed.lock() } } #[test] fn it_can_be_sent_between_threads() { use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let child = thread::spawn(move || { let boxed = Box::<u64>::random(1); let value = boxed.unlock().as_slice().to_vec(); // here we send an *unlocked* Box to the rx side; this lets // us make sure that the sent Box isn't dropped when this // thread exits, and that the other thread gets an unlocked // Box that it's responsible for locking tx.send((boxed, value)).expect("failed to send to channel"); }); let (boxed, value) = rx.recv().expect("failed to read from channel"); assert_eq!(Prot::ReadOnly, boxed.prot.get()); assert_eq!(value, boxed.as_slice()); child.join().expect("child terminated"); boxed.lock(); } #[test] #[should_panic(expected = "secrets: retained too many times")] fn it_doesnt_allow_overflowing_readers() { let boxed = Box::<[u64; 8]>::zero(4); for _ in 0..=u8::max_value() { let _ = boxed.unlock(); } // this ensures that we *don't* inadvertently panic if we // somehow made it through the above statement for _ in 0..boxed.refs.get() { boxed.lock() }
{ let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]); let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); }
identifier_body
boxed.rs
const_for_fn)] // not usable on min supported Rust pub(crate) fn is_empty(&self) -> bool { self.len == 0 } /// Returns the size in bytes of the data contained in the [`Box`]. /// This does not include incidental metadata used in the /// implementation of [`Box`] itself, only the size of the data /// allocated on behalf of the user. /// /// It is the maximum number of bytes that can be read from the /// internal pointer. pub(crate) fn size(&self) -> usize { self.len * T::size() } /// Allows the contents of the [`Box`] to be read from. Any call to /// this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock(&self) -> &Self { self.retain(Prot::ReadOnly); self } /// Allows the contents of the [`Box`] to be read from and written /// to. Any call to this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock_mut(&mut self) -> &mut Self { self.retain(Prot::ReadWrite); self } /// Disables all access to the underlying memory. Must only be /// called to precisely balance prior calls to [`unlock`](Box::unlock) /// and [`unlock_mut`](Box::unlock_mut). /// /// Calling this method in excess of the number of outstanding /// unlocks will result in a runtime panic. Omitting a call to this /// method and leaving an outstanding unlock will result in a /// runtime panic when this object is dropped. pub(crate) fn lock(&self) { self.release(); } /// Converts the [`Box`]'s contents into a reference. This must only /// happen while it is unlocked, and the reference must go out of /// scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_ref(&self) -> &T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get()!= Prot::NoAccess, "secrets: may not call Box::as_ref while locked"); unsafe { self.ptr.as_ref() } } /// Converts the [`Box`]'s contents into a mutable reference. This /// must only happen while it is mutably unlocked, and the slice /// must go out of scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_mut(&mut self) -> &mut T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut unless mutably unlocked"); unsafe { self.ptr.as_mut() } } /// Converts the [`Box`]'s contents into a slice. This must only /// happen while it is unlocked, and the slice must go out of scope /// before it is locked. pub(crate) fn as_slice(&self) -> &[T] { // NOTE: after some consideration, I've decided that this method // and its as_mut_slice() sister *are* safe. // // Using the retuned ref might cause a SIGSEGV, but this is not // UB (in fact, it's explicitly defined behavior!), cannot cause // a data race, cannot produce an invalid primitive, nor can it // break any other guarantee of "safe Rust". Just a SIGSEGV. // // However, as currently used by wrappers in this crate, these // methods are *never* called on unlocked data. Doing so would // be indicative of a bug, so we want to detect this during // development. If it happens in release mode, it's not // explicitly unsafe so we don't need to enable this check. proven!(self.prot.get()!= Prot::NoAccess, "secrets: may not call Box::as_slice while locked"); unsafe { slice::from_raw_parts( self.ptr.as_ptr(), self.len, ) } } /// Converts the [`Box`]'s contents into a mutable slice. This must /// only happen while it is mutably unlocked, and the slice must go /// out of scope before it is locked. pub(crate) fn as_mut_slice(&mut self) -> &mut [T] { proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut_slice unless mutably unlocked"); unsafe { slice::from_raw_parts_mut( self.ptr.as_ptr(), self.len, ) } } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. This [`Box`] will be unlocked and *must* be locked before /// it is dropped. /// /// TODO: make `len` a `NonZero` when it's stabilized and remove the /// related panic. fn new_unlocked(len: usize) -> Self { tested!(len == 0); tested!(std::mem::size_of::<T>() == 0); assert!(sodium::init(), "secrets: failed to initialize libsodium"); // `sodium::allocarray` returns a memory location that already // allows r/w access let ptr = NonNull::new(unsafe { sodium::allocarray::<T>(len) }) .expect("secrets: failed to allocate memory"); // NOTE: We technically could save a little extra work here by // initializing the struct with [`Prot::NoAccess`] and a zero // refcount, and manually calling `mprotect` when finished with // initialization. However, the `as_mut()` call performs sanity // checks that ensure it's [`Prot::ReadWrite`] so it's easier to // just send everything through the "normal" code paths. Self { ptr, len, prot: Cell::new(Prot::ReadWrite), refs: Cell::new(1), } } /// Performs the underlying retain half of the retain/release logic /// for monitoring outstanding calls to unlock. fn retain(&self, prot: Prot) { let refs = self.refs.get(); tested!(refs == RefCount::min_value()); tested!(refs == RefCount::max_value()); tested!(prot == Prot::NoAccess); if refs == 0 { // when retaining, we must retain to a protection level with // some access proven!(prot!= Prot::NoAccess, "secrets: must retain readably or writably"); // allow access to the pointer and record what level of // access is being permitted // // ordering probably doesn't matter here, but we set our // internal protection flag first so we never run the risk // of believing that memory is protected when it isn't self.prot.set(prot); mprotect(self.ptr.as_ptr(), prot); } else { // if we have a nonzero retain count, there is nothing to // change, but we can assert some invariants: // // * our current protection level *must not* be // [`Prot::NoAccess`] or we have underflowed the ref // counter // * our current protection level *must not* be // [`Prot::ReadWrite`] because that would imply non- // exclusive mutable access // * our target protection level *must* be `ReadOnly` // since otherwise would involve changing the protection // level of a currently-borrowed resource proven!(Prot::NoAccess!= self.prot.get(), "secrets: out-of-order retain/release detected"); proven!(Prot::ReadWrite!= self.prot.get(), "secrets: cannot unlock mutably more than once"); proven!(Prot::ReadOnly == prot, "secrets: cannot unlock mutably while unlocked immutably"); } // "255 retains ought to be enough for anybody" // // We use `checked_add` to ensure we don't overflow our ref // counter. This is ensured even in production builds because // it's infeasible for consumers of this API to actually enforce // this. That said, it's unlikely that anyone would need to // have more than 255 outstanding retains at one time. // // This also protects us in the event of balanced, out-of-order // retain/release code. If an out-of-order `release` causes the // ref counter to wrap around below zero, the subsequent // `retain` will panic here. match refs.checked_add(1) { Some(v) => self.refs.set(v), None if self.is_locked() => panic!("secrets: out-of-order retain/release detected"), None => panic!("secrets: retained too many times"), }; } /// Removes one outsdanding retain, and changes the memory /// protection level back to [`Prot::NoAccess`] when the number of /// outstanding retains reaches zero. fn
(&self) { // When releasing, we should always have at least one retain // outstanding. This is enforced by all users through // refcounting on allocation and drop. proven!(self.refs.get()!= 0, "secrets: releases exceeded retains"); // When releasing, our protection level must allow some kind of // access. If this condition isn't true, it was already // [`Prot::NoAccess`] so at least the memory was protected. proven!(self.prot.get()!= Prot::NoAccess, "secrets: releasing memory that's already locked"); // Deciding whether or not to use `checked_sub` or // `wrapping_sub` here has pros and cons. The `proven!`s above // help us catch this kind of accident in development, but if // a released library has a bug that has imbalanced // retains/releases, `wrapping_sub` will cause the refcount to // underflow and wrap. // // `checked_sub` ensures that wrapping won't happen, but will // cause consistency issues in the event of balanced but // *out-of-order* calls to retain/release. In such a scenario, // this will cause the retain count to be nonzero at drop time, // leaving the memory unlocked for an indeterminate period of // time. // // We choose `wrapped_sub` here because, by undeflowing, it will // ensure that a subsequent `retain` will not unlock the memory // and will trigger a `checked_add` runtime panic which we find // preferable for safety purposes. let refs = self.refs.get().wrapping_sub(1); self.refs.set(refs); if refs == 0 { mprotect(self.ptr.as_ptr(), Prot::NoAccess); self.prot.set(Prot::NoAccess); } } /// Returns true if the protection level is [`NoAccess`]. Ignores /// ref count. fn is_locked(&self) -> bool { self.prot.get() == Prot::NoAccess } } impl<T: Bytes + Randomizable> Box<T> { /// Instantiates a new [`Box`] with crypotgraphically-randomized /// contents. pub(crate) fn random(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().randomize()) } } impl<T: Bytes + Zeroable> Box<T> { /// Instantiates a new [`Box`] whose backing memory is zeroed. pub(crate) fn zero(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().zero()) } } impl<T: Bytes> Drop for Box<T> { fn drop(&mut self) { // [`Drop::drop`] is called during stack unwinding, so we may be // in a panic already. if!thread::panicking() { // If this value is being dropped, we want to ensure that // every retain has been balanced with a release. If this // is not true in release, the memory will be freed // momentarily so we don't need to worry about it. proven!(self.refs.get() == 0, "secrets: retains exceeded releases"); // Similarly, any dropped value should have previously been // set to deny any access. proven!(self.prot.get() == Prot::NoAccess, "secrets: dropped secret was still accessible"); } unsafe { sodium::free(self.ptr.as_mut()) } } } impl<T: Bytes> Debug for Box<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{{ {} bytes redacted }}", self.size()) } } impl<T: Bytes> Clone for Box<T> { fn clone(&self) -> Self { Self::new(self.len, |b| { b.as_mut_slice().copy_from_slice(self.unlock().as_slice()); self.lock(); }) } } impl<T: Bytes + ConstantEq> PartialEq for Box<T> { fn eq(&self, other: &Self) -> bool { if self.len!= other.len { return false; } let lhs = self.unlock().as_slice(); let rhs = other.unlock().as_slice(); let ret = lhs.constant_eq(rhs); self.lock(); other.lock(); ret } } impl<T: Bytes + Zeroable> From<&mut T> for Box<T> { fn from(data: &mut T) -> Self { // this is safe since the secret and data can never overlap Self::new(1, |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut()) } }) } } impl<T: Bytes + Zeroable> From<&mut [T]> for Box<T> { fn from(data: &mut [T]) -> Self { // this is safe since the secret and data can never overlap Self::new(data.len(), |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut_slice()) } }) } } unsafe impl<T: Bytes + Send> Send for Box<T> {} /// Immediately changes the page protection level on `ptr` to `prot`. fn mprotect<T>(ptr: *mut T, prot: Prot) { if!match prot { Prot::NoAccess => unsafe { sodium::mprotect_noaccess(ptr) }, Prot::ReadOnly => unsafe { sodium::mprotect_readonly(ptr) }, Prot::ReadWrite => unsafe { sodium::mprotect_readwrite(ptr) }, } { panic!("secrets: error setting memory protection to {:?}", prot); } } // LCOV_EXCL_START #[cfg(test)] mod tests { use super::*; #[test] fn it_allows_custom_initialization() { let boxed = Box::<u8>::new(1, |secret| { secret.as_mut_slice().clone_from_slice(b"\x04"); }); assert_eq!(boxed.unlock().as_slice(), [0x04]); boxed.lock(); } #[test] fn it_initializes_with_garbage() { let boxed = Box::<u8>::new(4, |_| {}); let unboxed = boxed.unlock().as_slice(); // sodium changed the value of the garbage byte they used, so we // allocate a byte and see what's inside to probe for the // specific value let garbage = unsafe { let garbage_ptr = sodium::allocarray::<u8>(1); let garbage_byte = *garbage_ptr; sodium::free(garbage_ptr); vec![garbage_byte; unboxed.len()] }; // sanity-check the garbage byte in case we have a bug in how we // probe for it assert_ne!(garbage, vec![0; garbage.len()]); assert_eq!(unboxed, &garbage[..]); boxed.lock(); } #[test] fn it_initializes_with_zero() { let boxed = Box::<u32>::zero(4); assert_eq!(boxed.unlock().as_slice(), [0, 0, 0, 0]); boxed.lock(); } #[test] fn it_initializes_from_values() { let mut value = [4_u64]; let boxed = Box::from(&mut value[..]); assert_eq!(value, [0]); assert_eq!(boxed.unlock().as_slice(), [4]); boxed.lock(); } #[test] fn it_compares_equality() { let boxed_1 = Box::<u8>::random(1); let boxed_2 = boxed_1.clone(); assert_eq!(boxed_1, boxed_2); assert_eq!(boxed_2, boxed_1); } #[test] fn it_compares_inequality() { let boxed_1 = Box::<u128>::random(32); let boxed_2 = Box::<u128>::random(32); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_compares_inequality_using_size() { let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]); let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_initializes_with_zero_refs() { let boxed = Box::<u8>::zero(10); assert_eq!(0, boxed.refs.get()); } #[test] fn it_tracks_ref_counts_accurately() { let mut boxed = Box::<u8>::random(10); let _ = boxed.unlock(); let _ = boxed.unlock(); let _ = boxed.unlock(); assert_eq!(3, boxed.refs.get()); boxed.lock(); boxed.lock(); boxed.lock(); assert_eq!(0, boxed.refs.get()); let _ = boxed.unlock_mut(); assert_eq!(1, boxed.refs.get()); boxed.lock(); assert_eq!(0, boxed.refs.get()); } #[test] fn it_doesnt_overflow_early() { let boxed = Box::<u64>::zero(4); for _ in 0..u8::max_value() { let _ = boxed.unlock(); } for _ in 0..u8::max_value() { boxed.lock(); } } #[test] fn it_allows_arbitrary_readers() { let boxed = Box::<u8>::zero(1); let mut count = 0_u8; sodium::memrandom(count.as_mut_bytes()); for _ in 0..count { let _ = boxed.unlock(); } for _ in 0..count { boxed.lock() } } #[test] fn it_can_be_sent_between_threads() { use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let child = thread::spawn(move || { let boxed = Box::<u64>::random(1); let value = boxed.unlock().as_slice().to_vec(); // here we send an *unlocked* Box to the rx side; this lets // us make sure that the sent Box isn't dropped when this // thread exits, and that the other thread gets an unlocked // Box that it's responsible for locking tx.send((boxed, value)).expect("failed to send to channel"); }); let (boxed, value) = rx.recv().expect("failed to read from channel"); assert_eq!(Prot::ReadOnly, boxed.prot.get()); assert_eq!(value, boxed.as_slice()); child.join().expect("child terminated"); boxed.lock(); } #[test] #[should_panic(expected = "secrets: retained too many times")] fn it_doesnt_allow_overflowing_readers() { let boxed = Box::<[u64; 8]>::zero(4); for _ in 0..=u8::max_value() { let _ = boxed.unlock(); } // this ensures that we *don't* inadvertently panic if we // somehow made it through the above statement for _ in 0..boxed.refs.get() { boxed.lock() }
release
identifier_name
boxed.rs
const_for_fn)] // not usable on min supported Rust pub(crate) fn is_empty(&self) -> bool { self.len == 0 } /// Returns the size in bytes of the data contained in the [`Box`]. /// This does not include incidental metadata used in the /// implementation of [`Box`] itself, only the size of the data /// allocated on behalf of the user. /// /// It is the maximum number of bytes that can be read from the /// internal pointer. pub(crate) fn size(&self) -> usize { self.len * T::size() } /// Allows the contents of the [`Box`] to be read from. Any call to /// this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock(&self) -> &Self { self.retain(Prot::ReadOnly); self } /// Allows the contents of the [`Box`] to be read from and written /// to. Any call to this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock_mut(&mut self) -> &mut Self { self.retain(Prot::ReadWrite); self } /// Disables all access to the underlying memory. Must only be /// called to precisely balance prior calls to [`unlock`](Box::unlock) /// and [`unlock_mut`](Box::unlock_mut). /// /// Calling this method in excess of the number of outstanding /// unlocks will result in a runtime panic. Omitting a call to this /// method and leaving an outstanding unlock will result in a /// runtime panic when this object is dropped. pub(crate) fn lock(&self) { self.release(); } /// Converts the [`Box`]'s contents into a reference. This must only /// happen while it is unlocked, and the reference must go out of /// scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_ref(&self) -> &T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get()!= Prot::NoAccess, "secrets: may not call Box::as_ref while locked"); unsafe { self.ptr.as_ref() } } /// Converts the [`Box`]'s contents into a mutable reference. This /// must only happen while it is mutably unlocked, and the slice /// must go out of scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_mut(&mut self) -> &mut T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut unless mutably unlocked"); unsafe { self.ptr.as_mut() } } /// Converts the [`Box`]'s contents into a slice. This must only /// happen while it is unlocked, and the slice must go out of scope /// before it is locked. pub(crate) fn as_slice(&self) -> &[T] { // NOTE: after some consideration, I've decided that this method // and its as_mut_slice() sister *are* safe. // // Using the retuned ref might cause a SIGSEGV, but this is not // UB (in fact, it's explicitly defined behavior!), cannot cause // a data race, cannot produce an invalid primitive, nor can it // break any other guarantee of "safe Rust". Just a SIGSEGV. // // However, as currently used by wrappers in this crate, these // methods are *never* called on unlocked data. Doing so would // be indicative of a bug, so we want to detect this during // development. If it happens in release mode, it's not // explicitly unsafe so we don't need to enable this check. proven!(self.prot.get()!= Prot::NoAccess, "secrets: may not call Box::as_slice while locked"); unsafe { slice::from_raw_parts( self.ptr.as_ptr(), self.len, ) } } /// Converts the [`Box`]'s contents into a mutable slice. This must /// only happen while it is mutably unlocked, and the slice must go /// out of scope before it is locked. pub(crate) fn as_mut_slice(&mut self) -> &mut [T] { proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut_slice unless mutably unlocked"); unsafe { slice::from_raw_parts_mut( self.ptr.as_ptr(), self.len, ) } } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. This [`Box`] will be unlocked and *must* be locked before /// it is dropped. /// /// TODO: make `len` a `NonZero` when it's stabilized and remove the /// related panic. fn new_unlocked(len: usize) -> Self { tested!(len == 0); tested!(std::mem::size_of::<T>() == 0); assert!(sodium::init(), "secrets: failed to initialize libsodium"); // `sodium::allocarray` returns a memory location that already // allows r/w access let ptr = NonNull::new(unsafe { sodium::allocarray::<T>(len) }) .expect("secrets: failed to allocate memory"); // NOTE: We technically could save a little extra work here by // initializing the struct with [`Prot::NoAccess`] and a zero // refcount, and manually calling `mprotect` when finished with // initialization. However, the `as_mut()` call performs sanity // checks that ensure it's [`Prot::ReadWrite`] so it's easier to // just send everything through the "normal" code paths. Self { ptr, len, prot: Cell::new(Prot::ReadWrite), refs: Cell::new(1), } } /// Performs the underlying retain half of the retain/release logic /// for monitoring outstanding calls to unlock. fn retain(&self, prot: Prot) { let refs = self.refs.get(); tested!(refs == RefCount::min_value()); tested!(refs == RefCount::max_value()); tested!(prot == Prot::NoAccess); if refs == 0 { // when retaining, we must retain to a protection level with // some access proven!(prot!= Prot::NoAccess, "secrets: must retain readably or writably"); // allow access to the pointer and record what level of // access is being permitted // // ordering probably doesn't matter here, but we set our // internal protection flag first so we never run the risk // of believing that memory is protected when it isn't self.prot.set(prot); mprotect(self.ptr.as_ptr(), prot); } else { // if we have a nonzero retain count, there is nothing to // change, but we can assert some invariants: // // * our current protection level *must not* be // [`Prot::NoAccess`] or we have underflowed the ref // counter // * our current protection level *must not* be // [`Prot::ReadWrite`] because that would imply non- // exclusive mutable access // * our target protection level *must* be `ReadOnly` // since otherwise would involve changing the protection // level of a currently-borrowed resource proven!(Prot::NoAccess!= self.prot.get(), "secrets: out-of-order retain/release detected"); proven!(Prot::ReadWrite!= self.prot.get(), "secrets: cannot unlock mutably more than once"); proven!(Prot::ReadOnly == prot, "secrets: cannot unlock mutably while unlocked immutably"); } // "255 retains ought to be enough for anybody" // // We use `checked_add` to ensure we don't overflow our ref // counter. This is ensured even in production builds because // it's infeasible for consumers of this API to actually enforce // this. That said, it's unlikely that anyone would need to // have more than 255 outstanding retains at one time. // // This also protects us in the event of balanced, out-of-order // retain/release code. If an out-of-order `release` causes the // ref counter to wrap around below zero, the subsequent // `retain` will panic here. match refs.checked_add(1) { Some(v) => self.refs.set(v), None if self.is_locked() => panic!("secrets: out-of-order retain/release detected"), None => panic!("secrets: retained too many times"), }; } /// Removes one outsdanding retain, and changes the memory /// protection level back to [`Prot::NoAccess`] when the number of /// outstanding retains reaches zero. fn release(&self) { // When releasing, we should always have at least one retain // outstanding. This is enforced by all users through // refcounting on allocation and drop. proven!(self.refs.get()!= 0, "secrets: releases exceeded retains"); // When releasing, our protection level must allow some kind of // access. If this condition isn't true, it was already // [`Prot::NoAccess`] so at least the memory was protected. proven!(self.prot.get()!= Prot::NoAccess, "secrets: releasing memory that's already locked"); // Deciding whether or not to use `checked_sub` or // `wrapping_sub` here has pros and cons. The `proven!`s above // help us catch this kind of accident in development, but if // a released library has a bug that has imbalanced // retains/releases, `wrapping_sub` will cause the refcount to // underflow and wrap. // // `checked_sub` ensures that wrapping won't happen, but will // cause consistency issues in the event of balanced but // *out-of-order* calls to retain/release. In such a scenario, // this will cause the retain count to be nonzero at drop time, // leaving the memory unlocked for an indeterminate period of // time. // // We choose `wrapped_sub` here because, by undeflowing, it will // ensure that a subsequent `retain` will not unlock the memory // and will trigger a `checked_add` runtime panic which we find // preferable for safety purposes. let refs = self.refs.get().wrapping_sub(1); self.refs.set(refs); if refs == 0
} /// Returns true if the protection level is [`NoAccess`]. Ignores /// ref count. fn is_locked(&self) -> bool { self.prot.get() == Prot::NoAccess } } impl<T: Bytes + Randomizable> Box<T> { /// Instantiates a new [`Box`] with crypotgraphically-randomized /// contents. pub(crate) fn random(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().randomize()) } } impl<T: Bytes + Zeroable> Box<T> { /// Instantiates a new [`Box`] whose backing memory is zeroed. pub(crate) fn zero(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().zero()) } } impl<T: Bytes> Drop for Box<T> { fn drop(&mut self) { // [`Drop::drop`] is called during stack unwinding, so we may be // in a panic already. if!thread::panicking() { // If this value is being dropped, we want to ensure that // every retain has been balanced with a release. If this // is not true in release, the memory will be freed // momentarily so we don't need to worry about it. proven!(self.refs.get() == 0, "secrets: retains exceeded releases"); // Similarly, any dropped value should have previously been // set to deny any access. proven!(self.prot.get() == Prot::NoAccess, "secrets: dropped secret was still accessible"); } unsafe { sodium::free(self.ptr.as_mut()) } } } impl<T: Bytes> Debug for Box<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{{ {} bytes redacted }}", self.size()) } } impl<T: Bytes> Clone for Box<T> { fn clone(&self) -> Self { Self::new(self.len, |b| { b.as_mut_slice().copy_from_slice(self.unlock().as_slice()); self.lock(); }) } } impl<T: Bytes + ConstantEq> PartialEq for Box<T> { fn eq(&self, other: &Self) -> bool { if self.len!= other.len { return false; } let lhs = self.unlock().as_slice(); let rhs = other.unlock().as_slice(); let ret = lhs.constant_eq(rhs); self.lock(); other.lock(); ret } } impl<T: Bytes + Zeroable> From<&mut T> for Box<T> { fn from(data: &mut T) -> Self { // this is safe since the secret and data can never overlap Self::new(1, |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut()) } }) } } impl<T: Bytes + Zeroable> From<&mut [T]> for Box<T> { fn from(data: &mut [T]) -> Self { // this is safe since the secret and data can never overlap Self::new(data.len(), |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut_slice()) } }) } } unsafe impl<T: Bytes + Send> Send for Box<T> {} /// Immediately changes the page protection level on `ptr` to `prot`. fn mprotect<T>(ptr: *mut T, prot: Prot) { if!match prot { Prot::NoAccess => unsafe { sodium::mprotect_noaccess(ptr) }, Prot::ReadOnly => unsafe { sodium::mprotect_readonly(ptr) }, Prot::ReadWrite => unsafe { sodium::mprotect_readwrite(ptr) }, } { panic!("secrets: error setting memory protection to {:?}", prot); } } // LCOV_EXCL_START #[cfg(test)] mod tests { use super::*; #[test] fn it_allows_custom_initialization() { let boxed = Box::<u8>::new(1, |secret| { secret.as_mut_slice().clone_from_slice(b"\x04"); }); assert_eq!(boxed.unlock().as_slice(), [0x04]); boxed.lock(); } #[test] fn it_initializes_with_garbage() { let boxed = Box::<u8>::new(4, |_| {}); let unboxed = boxed.unlock().as_slice(); // sodium changed the value of the garbage byte they used, so we // allocate a byte and see what's inside to probe for the // specific value let garbage = unsafe { let garbage_ptr = sodium::allocarray::<u8>(1); let garbage_byte = *garbage_ptr; sodium::free(garbage_ptr); vec![garbage_byte; unboxed.len()] }; // sanity-check the garbage byte in case we have a bug in how we // probe for it assert_ne!(garbage, vec![0; garbage.len()]); assert_eq!(unboxed, &garbage[..]); boxed.lock(); } #[test] fn it_initializes_with_zero() { let boxed = Box::<u32>::zero(4); assert_eq!(boxed.unlock().as_slice(), [0, 0, 0, 0]); boxed.lock(); } #[test] fn it_initializes_from_values() { let mut value = [4_u64]; let boxed = Box::from(&mut value[..]); assert_eq!(value, [0]); assert_eq!(boxed.unlock().as_slice(), [4]); boxed.lock(); } #[test] fn it_compares_equality() { let boxed_1 = Box::<u8>::random(1); let boxed_2 = boxed_1.clone(); assert_eq!(boxed_1, boxed_2); assert_eq!(boxed_2, boxed_1); } #[test] fn it_compares_inequality() { let boxed_1 = Box::<u128>::random(32); let boxed_2 = Box::<u128>::random(32); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_compares_inequality_using_size() { let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]); let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_initializes_with_zero_refs() { let boxed = Box::<u8>::zero(10); assert_eq!(0, boxed.refs.get()); } #[test] fn it_tracks_ref_counts_accurately() { let mut boxed = Box::<u8>::random(10); let _ = boxed.unlock(); let _ = boxed.unlock(); let _ = boxed.unlock(); assert_eq!(3, boxed.refs.get()); boxed.lock(); boxed.lock(); boxed.lock(); assert_eq!(0, boxed.refs.get()); let _ = boxed.unlock_mut(); assert_eq!(1, boxed.refs.get()); boxed.lock(); assert_eq!(0, boxed.refs.get()); } #[test] fn it_doesnt_overflow_early() { let boxed = Box::<u64>::zero(4); for _ in 0..u8::max_value() { let _ = boxed.unlock(); } for _ in 0..u8::max_value() { boxed.lock(); } } #[test] fn it_allows_arbitrary_readers() { let boxed = Box::<u8>::zero(1); let mut count = 0_u8; sodium::memrandom(count.as_mut_bytes()); for _ in 0..count { let _ = boxed.unlock(); } for _ in 0..count { boxed.lock() } } #[test] fn it_can_be_sent_between_threads() { use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let child = thread::spawn(move || { let boxed = Box::<u64>::random(1); let value = boxed.unlock().as_slice().to_vec(); // here we send an *unlocked* Box to the rx side; this lets // us make sure that the sent Box isn't dropped when this // thread exits, and that the other thread gets an unlocked // Box that it's responsible for locking tx.send((boxed, value)).expect("failed to send to channel"); }); let (boxed, value) = rx.recv().expect("failed to read from channel"); assert_eq!(Prot::ReadOnly, boxed.prot.get()); assert_eq!(value, boxed.as_slice()); child.join().expect("child terminated"); boxed.lock(); } #[test] #[should_panic(expected = "secrets: retained too many times")] fn it_doesnt_allow_overflowing_readers() { let boxed = Box::<[u64; 8]>::zero(4); for _ in 0..=u8::max_value() { let _ = boxed.unlock(); } // this ensures that we *don't* inadvertently panic if we // somehow made it through the above statement for _ in 0..boxed.refs.get() { boxed.lock() }
{ mprotect(self.ptr.as_ptr(), Prot::NoAccess); self.prot.set(Prot::NoAccess); }
conditional_block
mod.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::{ command_utils::get_worker_api_direct, get_layer_two_nonce, trusted_command_utils::{ decode_balance, get_identifiers, get_keystore_path, get_pair_from_str, }, trusted_commands::TrustedArgs, trusted_operation::{get_json_request, get_state, perform_trusted_operation, wait_until}, Cli, }; use codec::Decode; use hdrhistogram::Histogram; use ita_stf::{Getter, Index, KeyPair, TrustedCall, TrustedGetter, TrustedOperation}; use itc_rpc_client::direct_client::{DirectApi, DirectClient}; use itp_types::{ Balance, ShardIdentifier, TrustedOperationStatus, TrustedOperationStatus::{InSidechainBlock, Submitted}, }; use log::*; use rand::Rng; use rayon::prelude::*; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_application_crypto::sr25519; use sp_core::{sr25519 as sr25519_core, Pair}; use std::{ string::ToString, sync::mpsc::{channel, Receiver}, thread, time, time::Instant, vec::Vec, }; use substrate_client_keystore::{KeystoreExt, LocalKeystore}; // Needs to be above the existential deposit minimum, otherwise an account will not // be created and the state is not increased. const EXISTENTIAL_DEPOSIT: Balance = 1000; #[derive(Parser)] pub struct BenchmarkCommands { /// The number of clients (=threads) to be used in the benchmark #[clap(default_value_t = 10)] number_clients: u32, /// The number of iterations to execute for each client #[clap(default_value_t = 30)] number_iterations: u32, /// Adds a random wait before each transaction. This is the lower bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_min_ms: u32, /// Adds a random wait before each transaction. This is the upper bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_max_ms: u32, /// Whether to wait for "InSidechainBlock" confirmation for each transaction #[clap(short, long)] wait_for_confirmation: bool, /// Account to be used for initial funding of generated accounts used in benchmark #[clap(default_value_t = String::from("//Alice"))] funding_account: String, } struct BenchmarkClient { account: sr25519_core::Pair, current_balance: u128, client_api: DirectClient, receiver: Receiver<String>, } impl BenchmarkClient { fn new( account: sr25519_core::Pair, initial_balance: u128, initial_request: String, cli: &Cli, ) -> Self { debug!("get direct api"); let client_api = get_worker_api_direct(cli); debug!("setup sender and receiver"); let (sender, receiver) = channel(); client_api.watch(initial_request, sender); BenchmarkClient { account, current_balance: initial_balance, client_api, receiver } } } /// Stores timing information about a specific transaction struct BenchmarkTransaction { started: Instant, submitted: Instant, confirmed: Option<Instant>, } impl BenchmarkCommands { pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedArgs) { let random_wait_before_transaction_ms: (u32, u32) = ( self.random_wait_before_transaction_min_ms, self.random_wait_before_transaction_max_ms, ); let store = LocalKeystore::open(get_keystore_path(trusted_args), None).unwrap(); let funding_account_keys = get_pair_from_str(trusted_args, &self.funding_account); let (mrenclave, shard) = get_identifiers(trusted_args); // Get shielding pubkey. let worker_api_direct = get_worker_api_direct(cli); let shielding_pubkey: Rsa3072PubKey = match worker_api_direct.get_rsa_pubkey() { Ok(key) => key, Err(err_msg) => panic!("{}", err_msg.to_string()), }; let nonce_start = get_layer_two_nonce!(funding_account_keys, cli, trusted_args); println!("Nonce for account {}: {}", self.funding_account, nonce_start); let mut accounts = Vec::new(); // Setup new accounts and initialize them with money from Alice. for i in 0..self.number_clients { let nonce = i + nonce_start; println!("Initializing account {}", i); // Create new account to use. let a: sr25519::AppPair = store.generate().unwrap(); let account = get_pair_from_str(trusted_args, a.public().to_string().as_str()); let initial_balance = 10000000; // Transfer amount from Alice to new account. let top: TrustedOperation = TrustedCall::balance_transfer( funding_account_keys.public().into(), account.public().into(), initial_balance, ) .sign(&KeyPair::Sr25519(funding_account_keys.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); // For the last account we wait for confirmation in order to ensure all accounts were setup correctly let wait_for_confirmation = i == self.number_clients - 1; let account_funding_request = get_json_request(shard, &top, shielding_pubkey); let client = BenchmarkClient::new(account, initial_balance, account_funding_request, cli); let _result = wait_for_top_confirmation(wait_for_confirmation, &client); accounts.push(client); } rayon::ThreadPoolBuilder::new() .num_threads(self.number_clients as usize) .build_global() .unwrap(); let overall_start = Instant::now(); // Run actual benchmark logic, in parallel, for each account initialized above. let outputs: Vec<Vec<BenchmarkTransaction>> = accounts .into_par_iter() .map(move |mut client| { let mut output: Vec<BenchmarkTransaction> = Vec::new(); for i in 0..self.number_iterations { println!("Iteration: {}", i); if random_wait_before_transaction_ms.1 > 0 { random_wait(random_wait_before_transaction_ms); } // Create new account. let account_keys: sr25519::AppPair = store.generate().unwrap(); let new_account = get_pair_from_str(trusted_args, account_keys.public().to_string().as_str()); println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT); println!(" From: {:?}", client.account.public()); println!(" To: {:?}", new_account.public()); // Get nonce of account. let nonce = get_nonce(client.account.clone(), shard, &client.client_api); // Transfer money from client account to new account. let top: TrustedOperation = TrustedCall::balance_transfer( client.account.public().into(), new_account.public().into(), EXISTENTIAL_DEPOSIT, ) .sign(&KeyPair::Sr25519(client.account.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); let last_iteration = i == self.number_iterations - 1; let jsonrpc_call = get_json_request(shard, &top, shielding_pubkey); client.client_api.send(&jsonrpc_call).unwrap(); let result = wait_for_top_confirmation( self.wait_for_confirmation || last_iteration, &client, ); client.current_balance -= EXISTENTIAL_DEPOSIT; let balance = get_balance(client.account.clone(), shard, &client.client_api); println!("Balance: {}", balance.unwrap_or_default()); assert_eq!(client.current_balance, balance.unwrap()); output.push(result); // FIXME: We probably should re-fund the account in this case. if client.current_balance <= EXISTENTIAL_DEPOSIT { error!("Account {:?} does not have enough balance anymore. Finishing benchmark early", client.account.public()); break; } } client.client_api.close().unwrap(); output }) .collect(); println!( "Finished benchmark with {} clients and {} transactions in {} ms", self.number_clients, self.number_iterations, overall_start.elapsed().as_millis() ); print_benchmark_statistic(outputs, self.wait_for_confirmation) } } fn get_balance( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Option<u128> { let getter = Getter::trusted( TrustedGetter::free_balance(account.public().into()) .sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let balance = decode_balance(getter_result); info!("Balance getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} Balance for {:?}", balance.unwrap_or_default(), account.public()); balance } fn
( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Index { let getter = Getter::trusted( TrustedGetter::nonce(account.public().into()).sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let nonce = match getter_result { Some(encoded_nonce) => Index::decode(&mut encoded_nonce.as_slice()).unwrap(), None => Default::default(), }; info!("Nonce getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} nonce for {:?}", nonce, account.public()); nonce } fn print_benchmark_statistic(outputs: Vec<Vec<BenchmarkTransaction>>, wait_for_confirmation: bool) { let mut hist = Histogram::<u64>::new(1).unwrap(); for output in outputs { for t in output { let benchmarked_timestamp = if wait_for_confirmation { t.confirmed } else { Some(t.submitted) }; if let Some(confirmed) = benchmarked_timestamp { hist += confirmed.duration_since(t.started).as_millis() as u64; } else { println!("Missing measurement data"); } } } for i in (5..=100).step_by(5) { let text = format!( "{} percent are done within {} ms", i, hist.value_at_quantile(i as f64 / 100.0) ); println!("{}", text); } } fn random_wait(random_wait_before_transaction_ms: (u32, u32)) { let mut rng = rand::thread_rng(); let sleep_time = time::Duration::from_millis( rng.gen_range(random_wait_before_transaction_ms.0..=random_wait_before_transaction_ms.1) .into(), ); println!("Sleep for: {}ms", sleep_time.as_millis()); thread::sleep(sleep_time); } fn wait_for_top_confirmation( wait_for_sidechain_block: bool, client: &BenchmarkClient, ) -> BenchmarkTransaction { let started = Instant::now(); let submitted = wait_until(&client.receiver, is_submitted); let confirmed = if wait_for_sidechain_block { // We wait for the transaction hash that actually matches the submitted hash loop { let transaction_information = wait_until(&client.receiver, is_sidechain_block); if let Some((hash, _)) = transaction_information { if hash == submitted.unwrap().0 { break transaction_information } } } } else { None }; if let (Some(s), Some(c)) = (submitted, confirmed) { // Assert the two hashes are identical assert_eq!(s.0, c.0); } BenchmarkTransaction { started, submitted: submitted.unwrap().1, confirmed: confirmed.map(|v| v.1), } } fn is_submitted(s: TrustedOperationStatus) -> bool { matches!(s, Submitted) } fn is_sidechain_block(s: TrustedOperationStatus) -> bool { matches!(s, InSidechainBlock(_)) }
get_nonce
identifier_name
mod.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::{ command_utils::get_worker_api_direct, get_layer_two_nonce, trusted_command_utils::{ decode_balance, get_identifiers, get_keystore_path, get_pair_from_str, }, trusted_commands::TrustedArgs, trusted_operation::{get_json_request, get_state, perform_trusted_operation, wait_until}, Cli, }; use codec::Decode; use hdrhistogram::Histogram; use ita_stf::{Getter, Index, KeyPair, TrustedCall, TrustedGetter, TrustedOperation}; use itc_rpc_client::direct_client::{DirectApi, DirectClient}; use itp_types::{ Balance, ShardIdentifier, TrustedOperationStatus, TrustedOperationStatus::{InSidechainBlock, Submitted}, }; use log::*; use rand::Rng; use rayon::prelude::*; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_application_crypto::sr25519; use sp_core::{sr25519 as sr25519_core, Pair}; use std::{ string::ToString, sync::mpsc::{channel, Receiver}, thread, time, time::Instant, vec::Vec, }; use substrate_client_keystore::{KeystoreExt, LocalKeystore}; // Needs to be above the existential deposit minimum, otherwise an account will not // be created and the state is not increased. const EXISTENTIAL_DEPOSIT: Balance = 1000; #[derive(Parser)] pub struct BenchmarkCommands { /// The number of clients (=threads) to be used in the benchmark #[clap(default_value_t = 10)] number_clients: u32, /// The number of iterations to execute for each client #[clap(default_value_t = 30)] number_iterations: u32, /// Adds a random wait before each transaction. This is the lower bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_min_ms: u32, /// Adds a random wait before each transaction. This is the upper bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_max_ms: u32, /// Whether to wait for "InSidechainBlock" confirmation for each transaction #[clap(short, long)] wait_for_confirmation: bool, /// Account to be used for initial funding of generated accounts used in benchmark #[clap(default_value_t = String::from("//Alice"))] funding_account: String, } struct BenchmarkClient { account: sr25519_core::Pair, current_balance: u128, client_api: DirectClient, receiver: Receiver<String>, } impl BenchmarkClient { fn new( account: sr25519_core::Pair, initial_balance: u128, initial_request: String, cli: &Cli, ) -> Self { debug!("get direct api"); let client_api = get_worker_api_direct(cli); debug!("setup sender and receiver"); let (sender, receiver) = channel(); client_api.watch(initial_request, sender); BenchmarkClient { account, current_balance: initial_balance, client_api, receiver } } } /// Stores timing information about a specific transaction struct BenchmarkTransaction { started: Instant, submitted: Instant, confirmed: Option<Instant>, } impl BenchmarkCommands { pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedArgs) { let random_wait_before_transaction_ms: (u32, u32) = ( self.random_wait_before_transaction_min_ms, self.random_wait_before_transaction_max_ms, ); let store = LocalKeystore::open(get_keystore_path(trusted_args), None).unwrap(); let funding_account_keys = get_pair_from_str(trusted_args, &self.funding_account); let (mrenclave, shard) = get_identifiers(trusted_args); // Get shielding pubkey. let worker_api_direct = get_worker_api_direct(cli); let shielding_pubkey: Rsa3072PubKey = match worker_api_direct.get_rsa_pubkey() { Ok(key) => key, Err(err_msg) => panic!("{}", err_msg.to_string()), }; let nonce_start = get_layer_two_nonce!(funding_account_keys, cli, trusted_args); println!("Nonce for account {}: {}", self.funding_account, nonce_start); let mut accounts = Vec::new(); // Setup new accounts and initialize them with money from Alice. for i in 0..self.number_clients { let nonce = i + nonce_start; println!("Initializing account {}", i); // Create new account to use. let a: sr25519::AppPair = store.generate().unwrap(); let account = get_pair_from_str(trusted_args, a.public().to_string().as_str()); let initial_balance = 10000000; // Transfer amount from Alice to new account. let top: TrustedOperation = TrustedCall::balance_transfer( funding_account_keys.public().into(), account.public().into(), initial_balance, ) .sign(&KeyPair::Sr25519(funding_account_keys.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); // For the last account we wait for confirmation in order to ensure all accounts were setup correctly let wait_for_confirmation = i == self.number_clients - 1; let account_funding_request = get_json_request(shard, &top, shielding_pubkey); let client = BenchmarkClient::new(account, initial_balance, account_funding_request, cli); let _result = wait_for_top_confirmation(wait_for_confirmation, &client); accounts.push(client); } rayon::ThreadPoolBuilder::new() .num_threads(self.number_clients as usize) .build_global() .unwrap(); let overall_start = Instant::now(); // Run actual benchmark logic, in parallel, for each account initialized above. let outputs: Vec<Vec<BenchmarkTransaction>> = accounts .into_par_iter() .map(move |mut client| { let mut output: Vec<BenchmarkTransaction> = Vec::new(); for i in 0..self.number_iterations { println!("Iteration: {}", i); if random_wait_before_transaction_ms.1 > 0
// Create new account. let account_keys: sr25519::AppPair = store.generate().unwrap(); let new_account = get_pair_from_str(trusted_args, account_keys.public().to_string().as_str()); println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT); println!(" From: {:?}", client.account.public()); println!(" To: {:?}", new_account.public()); // Get nonce of account. let nonce = get_nonce(client.account.clone(), shard, &client.client_api); // Transfer money from client account to new account. let top: TrustedOperation = TrustedCall::balance_transfer( client.account.public().into(), new_account.public().into(), EXISTENTIAL_DEPOSIT, ) .sign(&KeyPair::Sr25519(client.account.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); let last_iteration = i == self.number_iterations - 1; let jsonrpc_call = get_json_request(shard, &top, shielding_pubkey); client.client_api.send(&jsonrpc_call).unwrap(); let result = wait_for_top_confirmation( self.wait_for_confirmation || last_iteration, &client, ); client.current_balance -= EXISTENTIAL_DEPOSIT; let balance = get_balance(client.account.clone(), shard, &client.client_api); println!("Balance: {}", balance.unwrap_or_default()); assert_eq!(client.current_balance, balance.unwrap()); output.push(result); // FIXME: We probably should re-fund the account in this case. if client.current_balance <= EXISTENTIAL_DEPOSIT { error!("Account {:?} does not have enough balance anymore. Finishing benchmark early", client.account.public()); break; } } client.client_api.close().unwrap(); output }) .collect(); println!( "Finished benchmark with {} clients and {} transactions in {} ms", self.number_clients, self.number_iterations, overall_start.elapsed().as_millis() ); print_benchmark_statistic(outputs, self.wait_for_confirmation) } } fn get_balance( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Option<u128> { let getter = Getter::trusted( TrustedGetter::free_balance(account.public().into()) .sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let balance = decode_balance(getter_result); info!("Balance getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} Balance for {:?}", balance.unwrap_or_default(), account.public()); balance } fn get_nonce( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Index { let getter = Getter::trusted( TrustedGetter::nonce(account.public().into()).sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let nonce = match getter_result { Some(encoded_nonce) => Index::decode(&mut encoded_nonce.as_slice()).unwrap(), None => Default::default(), }; info!("Nonce getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} nonce for {:?}", nonce, account.public()); nonce } fn print_benchmark_statistic(outputs: Vec<Vec<BenchmarkTransaction>>, wait_for_confirmation: bool) { let mut hist = Histogram::<u64>::new(1).unwrap(); for output in outputs { for t in output { let benchmarked_timestamp = if wait_for_confirmation { t.confirmed } else { Some(t.submitted) }; if let Some(confirmed) = benchmarked_timestamp { hist += confirmed.duration_since(t.started).as_millis() as u64; } else { println!("Missing measurement data"); } } } for i in (5..=100).step_by(5) { let text = format!( "{} percent are done within {} ms", i, hist.value_at_quantile(i as f64 / 100.0) ); println!("{}", text); } } fn random_wait(random_wait_before_transaction_ms: (u32, u32)) { let mut rng = rand::thread_rng(); let sleep_time = time::Duration::from_millis( rng.gen_range(random_wait_before_transaction_ms.0..=random_wait_before_transaction_ms.1) .into(), ); println!("Sleep for: {}ms", sleep_time.as_millis()); thread::sleep(sleep_time); } fn wait_for_top_confirmation( wait_for_sidechain_block: bool, client: &BenchmarkClient, ) -> BenchmarkTransaction { let started = Instant::now(); let submitted = wait_until(&client.receiver, is_submitted); let confirmed = if wait_for_sidechain_block { // We wait for the transaction hash that actually matches the submitted hash loop { let transaction_information = wait_until(&client.receiver, is_sidechain_block); if let Some((hash, _)) = transaction_information { if hash == submitted.unwrap().0 { break transaction_information } } } } else { None }; if let (Some(s), Some(c)) = (submitted, confirmed) { // Assert the two hashes are identical assert_eq!(s.0, c.0); } BenchmarkTransaction { started, submitted: submitted.unwrap().1, confirmed: confirmed.map(|v| v.1), } } fn is_submitted(s: TrustedOperationStatus) -> bool { matches!(s, Submitted) } fn is_sidechain_block(s: TrustedOperationStatus) -> bool { matches!(s, InSidechainBlock(_)) }
{ random_wait(random_wait_before_transaction_ms); }
conditional_block
mod.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::{ command_utils::get_worker_api_direct, get_layer_two_nonce, trusted_command_utils::{ decode_balance, get_identifiers, get_keystore_path, get_pair_from_str, }, trusted_commands::TrustedArgs, trusted_operation::{get_json_request, get_state, perform_trusted_operation, wait_until}, Cli, }; use codec::Decode; use hdrhistogram::Histogram; use ita_stf::{Getter, Index, KeyPair, TrustedCall, TrustedGetter, TrustedOperation}; use itc_rpc_client::direct_client::{DirectApi, DirectClient}; use itp_types::{ Balance, ShardIdentifier, TrustedOperationStatus, TrustedOperationStatus::{InSidechainBlock, Submitted}, }; use log::*; use rand::Rng; use rayon::prelude::*; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_application_crypto::sr25519; use sp_core::{sr25519 as sr25519_core, Pair}; use std::{ string::ToString, sync::mpsc::{channel, Receiver}, thread, time, time::Instant, vec::Vec, }; use substrate_client_keystore::{KeystoreExt, LocalKeystore}; // Needs to be above the existential deposit minimum, otherwise an account will not // be created and the state is not increased. const EXISTENTIAL_DEPOSIT: Balance = 1000; #[derive(Parser)] pub struct BenchmarkCommands { /// The number of clients (=threads) to be used in the benchmark #[clap(default_value_t = 10)] number_clients: u32, /// The number of iterations to execute for each client #[clap(default_value_t = 30)] number_iterations: u32, /// Adds a random wait before each transaction. This is the lower bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_min_ms: u32, /// Adds a random wait before each transaction. This is the upper bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_max_ms: u32, /// Whether to wait for "InSidechainBlock" confirmation for each transaction #[clap(short, long)] wait_for_confirmation: bool, /// Account to be used for initial funding of generated accounts used in benchmark #[clap(default_value_t = String::from("//Alice"))] funding_account: String, } struct BenchmarkClient { account: sr25519_core::Pair, current_balance: u128, client_api: DirectClient, receiver: Receiver<String>, } impl BenchmarkClient { fn new( account: sr25519_core::Pair, initial_balance: u128, initial_request: String, cli: &Cli, ) -> Self { debug!("get direct api"); let client_api = get_worker_api_direct(cli); debug!("setup sender and receiver"); let (sender, receiver) = channel(); client_api.watch(initial_request, sender); BenchmarkClient { account, current_balance: initial_balance, client_api, receiver } } } /// Stores timing information about a specific transaction struct BenchmarkTransaction { started: Instant, submitted: Instant, confirmed: Option<Instant>, } impl BenchmarkCommands { pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedArgs) { let random_wait_before_transaction_ms: (u32, u32) = ( self.random_wait_before_transaction_min_ms, self.random_wait_before_transaction_max_ms, ); let store = LocalKeystore::open(get_keystore_path(trusted_args), None).unwrap(); let funding_account_keys = get_pair_from_str(trusted_args, &self.funding_account); let (mrenclave, shard) = get_identifiers(trusted_args); // Get shielding pubkey. let worker_api_direct = get_worker_api_direct(cli); let shielding_pubkey: Rsa3072PubKey = match worker_api_direct.get_rsa_pubkey() { Ok(key) => key, Err(err_msg) => panic!("{}", err_msg.to_string()), }; let nonce_start = get_layer_two_nonce!(funding_account_keys, cli, trusted_args); println!("Nonce for account {}: {}", self.funding_account, nonce_start); let mut accounts = Vec::new(); // Setup new accounts and initialize them with money from Alice. for i in 0..self.number_clients { let nonce = i + nonce_start; println!("Initializing account {}", i); // Create new account to use. let a: sr25519::AppPair = store.generate().unwrap(); let account = get_pair_from_str(trusted_args, a.public().to_string().as_str()); let initial_balance = 10000000; // Transfer amount from Alice to new account. let top: TrustedOperation = TrustedCall::balance_transfer( funding_account_keys.public().into(), account.public().into(), initial_balance, ) .sign(&KeyPair::Sr25519(funding_account_keys.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); // For the last account we wait for confirmation in order to ensure all accounts were setup correctly let wait_for_confirmation = i == self.number_clients - 1; let account_funding_request = get_json_request(shard, &top, shielding_pubkey); let client = BenchmarkClient::new(account, initial_balance, account_funding_request, cli); let _result = wait_for_top_confirmation(wait_for_confirmation, &client); accounts.push(client); } rayon::ThreadPoolBuilder::new() .num_threads(self.number_clients as usize) .build_global() .unwrap(); let overall_start = Instant::now(); // Run actual benchmark logic, in parallel, for each account initialized above. let outputs: Vec<Vec<BenchmarkTransaction>> = accounts .into_par_iter() .map(move |mut client| { let mut output: Vec<BenchmarkTransaction> = Vec::new(); for i in 0..self.number_iterations { println!("Iteration: {}", i); if random_wait_before_transaction_ms.1 > 0 { random_wait(random_wait_before_transaction_ms); } // Create new account. let account_keys: sr25519::AppPair = store.generate().unwrap(); let new_account = get_pair_from_str(trusted_args, account_keys.public().to_string().as_str()); println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT); println!(" From: {:?}", client.account.public()); println!(" To: {:?}", new_account.public()); // Get nonce of account. let nonce = get_nonce(client.account.clone(), shard, &client.client_api); // Transfer money from client account to new account. let top: TrustedOperation = TrustedCall::balance_transfer( client.account.public().into(), new_account.public().into(), EXISTENTIAL_DEPOSIT, ) .sign(&KeyPair::Sr25519(client.account.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); let last_iteration = i == self.number_iterations - 1; let jsonrpc_call = get_json_request(shard, &top, shielding_pubkey); client.client_api.send(&jsonrpc_call).unwrap(); let result = wait_for_top_confirmation( self.wait_for_confirmation || last_iteration, &client, ); client.current_balance -= EXISTENTIAL_DEPOSIT; let balance = get_balance(client.account.clone(), shard, &client.client_api); println!("Balance: {}", balance.unwrap_or_default()); assert_eq!(client.current_balance, balance.unwrap()); output.push(result); // FIXME: We probably should re-fund the account in this case. if client.current_balance <= EXISTENTIAL_DEPOSIT { error!("Account {:?} does not have enough balance anymore. Finishing benchmark early", client.account.public());
output }) .collect(); println!( "Finished benchmark with {} clients and {} transactions in {} ms", self.number_clients, self.number_iterations, overall_start.elapsed().as_millis() ); print_benchmark_statistic(outputs, self.wait_for_confirmation) } } fn get_balance( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Option<u128> { let getter = Getter::trusted( TrustedGetter::free_balance(account.public().into()) .sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let balance = decode_balance(getter_result); info!("Balance getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} Balance for {:?}", balance.unwrap_or_default(), account.public()); balance } fn get_nonce( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Index { let getter = Getter::trusted( TrustedGetter::nonce(account.public().into()).sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let nonce = match getter_result { Some(encoded_nonce) => Index::decode(&mut encoded_nonce.as_slice()).unwrap(), None => Default::default(), }; info!("Nonce getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} nonce for {:?}", nonce, account.public()); nonce } fn print_benchmark_statistic(outputs: Vec<Vec<BenchmarkTransaction>>, wait_for_confirmation: bool) { let mut hist = Histogram::<u64>::new(1).unwrap(); for output in outputs { for t in output { let benchmarked_timestamp = if wait_for_confirmation { t.confirmed } else { Some(t.submitted) }; if let Some(confirmed) = benchmarked_timestamp { hist += confirmed.duration_since(t.started).as_millis() as u64; } else { println!("Missing measurement data"); } } } for i in (5..=100).step_by(5) { let text = format!( "{} percent are done within {} ms", i, hist.value_at_quantile(i as f64 / 100.0) ); println!("{}", text); } } fn random_wait(random_wait_before_transaction_ms: (u32, u32)) { let mut rng = rand::thread_rng(); let sleep_time = time::Duration::from_millis( rng.gen_range(random_wait_before_transaction_ms.0..=random_wait_before_transaction_ms.1) .into(), ); println!("Sleep for: {}ms", sleep_time.as_millis()); thread::sleep(sleep_time); } fn wait_for_top_confirmation( wait_for_sidechain_block: bool, client: &BenchmarkClient, ) -> BenchmarkTransaction { let started = Instant::now(); let submitted = wait_until(&client.receiver, is_submitted); let confirmed = if wait_for_sidechain_block { // We wait for the transaction hash that actually matches the submitted hash loop { let transaction_information = wait_until(&client.receiver, is_sidechain_block); if let Some((hash, _)) = transaction_information { if hash == submitted.unwrap().0 { break transaction_information } } } } else { None }; if let (Some(s), Some(c)) = (submitted, confirmed) { // Assert the two hashes are identical assert_eq!(s.0, c.0); } BenchmarkTransaction { started, submitted: submitted.unwrap().1, confirmed: confirmed.map(|v| v.1), } } fn is_submitted(s: TrustedOperationStatus) -> bool { matches!(s, Submitted) } fn is_sidechain_block(s: TrustedOperationStatus) -> bool { matches!(s, InSidechainBlock(_)) }
break; } } client.client_api.close().unwrap();
random_line_split
lib.rs
//! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format). //! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies: //! //! * [`Config::get`] returns the last occurrence value, if config specifies the key more than once. //! * Whitespaces are not allowed at the start of lines, any line not starting with `[` character is treated as a comment. //! //! Other notable functionality is that the parser preserves all of the parsed string content, including blank lines and comments. //! //! # Examples //! //! ```no_run //! # use std::io; //! use std::fs::{read_to_string, write}; //! use dfconfig::Config; //! //! // Parse existing config //! let path = r"/path/to/df/data/init/init.txt"; //! let mut conf = Config::read_str(read_to_string(path)?); //! //! // Read some value //! let sound = conf.get("SOUND"); //! //! // Modify and save the config //! conf.set("VOLUME", "128"); //! write(path, conf.print())?; //! # Ok::<(), io::Error>(()) //! ``` #[macro_use] extern crate lazy_static; use std::collections::HashMap; use regex::Regex; #[derive(Clone, Debug)] enum Line { Blank, Comment(String), Entry(Entry), } #[derive(Clone, Debug)] struct Entry { key: String, value: String, } impl Entry { pub fn new(key: String, value: String) -> Self { Self { key, value } } pub fn
(&self) -> &str { &self.value } pub fn get_key(&self) -> &str { &self.key } pub fn set_value(&mut self, value: String) { self.value = value; } } /// The main struct of this crate. Represents DF config file, while also providing functions to parse and manipulate the data. /// See crate doc for example usage. #[doc(inline)] #[derive(Clone, Debug)] pub struct Config { lines: Vec<Line>, } impl Config { /// Creates an empty config. pub fn new() -> Self { Self { lines: vec![] } } /// Parse the config from a string. pub fn read_str<T: AsRef<str>>(input: T) -> Self { lazy_static! { static ref RE: Regex = Regex::new(r"^\[([\w\d]+):([\w\d:]+)\]$").unwrap(); } let mut lines = Vec::<Line>::new(); for l in input.as_ref().lines() { let lt = l.trim_end(); if lt.is_empty() { lines.push(Line::Blank); continue; } let captures = RE.captures(lt); match captures { Some(c) => lines.push(Line::Entry(Entry::new( c.get(1).unwrap().as_str().to_owned(), c.get(2).unwrap().as_str().to_owned(), ))), None => lines.push(Line::Comment(l.to_owned())), }; } Self { lines } } /// Tries to retrieve the value for `key`. /// If the key is defined more than once, returns the value of the last occurrence. pub fn get<T: AsRef<str>>(&self, key: T) -> Option<&str> { self.lines.iter().rev().find_map(|x| match x { Line::Entry(entry) => { if entry.get_key() == key.as_ref() { Some(entry.get_value()) } else { None } } _ => None, }) } /// Sets all the occurrences of `key` to `value` /// /// # Panics /// /// Panics if `key` or `value` is either empty or non-alphanumeric. pub fn set<T: AsRef<str>, U: Into<String>>(&mut self, key: T, value: U) { let key = key.as_ref(); let value = value.into(); if key.is_empty() ||!key.chars().all(|x| x.is_alphanumeric()) || value.is_empty() ||!value.chars().all(|x| x.is_alphanumeric()) { panic!("Both key and value have to be non-empty alphanumeric strings!") } let mut n = 0; for e in self.lines.iter_mut() { if let Line::Entry(entry) = e { if entry.get_key() == key { entry.set_value(value.clone()); n += 1; } } } if n == 0 { self.lines .push(Line::Entry(Entry::new(key.to_string(), value))); } } /// Removes all occurrences of `key` from this `Config`. Returns the number of keys removed. pub fn remove<T: AsRef<str>>(&mut self, key: T) -> usize { let mut n: usize = 0; loop { let to_remove = self.lines.iter().enumerate().find_map(|(i, x)| { if let Line::Entry(entry) = x { if entry.get_key() == key.as_ref() { return Some(i); } } None }); match to_remove { None => break, Some(i) => { self.lines.remove(i); n += 1; } }; } n } /// Returns number of configuration entries present in this `Config`. pub fn len(&self) -> usize { self.lines .iter() .filter(|&x| matches!(x, Line::Entry(_))) .count() } /// Returns true if there are no entries defined in this `Config`. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the `key` strings. pub fn keys_iter(&self) -> impl Iterator<Item = &str> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some(entry.get_key()) } else { None } }) } /// Returns an iterator over (`key`, `value`) tuples. pub fn keys_values_iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some((entry.get_key(), entry.get_value())) } else { None } }) } /// Returns the string representing the configuration in its current state (aka what you'd write to the file usually). pub fn print(&self) -> String { let mut buff = Vec::<String>::with_capacity(self.lines.len()); for l in self.lines.iter() { match l { Line::Blank => buff.push("".to_string()), Line::Comment(x) => buff.push(x.to_string()), Line::Entry(entry) => { buff.push(format!("[{}:{}]", entry.get_key(), entry.get_value())) } } } buff.join("\r\n") } } impl From<Config> for HashMap<String, String> { fn from(conf: Config) -> Self { let mut output = HashMap::new(); conf.keys_values_iter().for_each(|(key, value)| { output.insert(key.to_owned(), value.to_owned()); }); output } } impl Default for Config { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::fs::read_to_string; use std::iter; use super::*; fn random_alphanumeric() -> String { let mut rng = thread_rng(); iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .map(char::from) .take(thread_rng().gen_range(1..50)) .collect() } #[test] fn test_basic_parse() { let key = random_alphanumeric(); let key2 = random_alphanumeric(); let value: String = random_alphanumeric(); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); assert_eq!(c.get(key2), None); } #[test] fn test_multi_value() { let key = random_alphanumeric(); let value: String = format!("{}:{}", random_alphanumeric(), random_alphanumeric()); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_basic_set() { let key = random_alphanumeric(); let value: String = random_alphanumeric(); let mut c = Config::new(); c.set(&key, &value); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_read_modify() { let key_a = random_alphanumeric(); let value_b: String = random_alphanumeric(); let value_c: String = random_alphanumeric(); let key_d = random_alphanumeric(); let value_e: String = random_alphanumeric(); let mut c = Config::read_str(format!("[{}:{}]", key_a, value_b)); assert_eq!(c.get(&key_a).unwrap(), value_b); c.set(&key_a, &value_c); assert_eq!(c.get(&key_a).unwrap(), value_c); c.set(&key_d, &value_e); assert_eq!(c.get(&key_a).unwrap(), value_c); assert_eq!(c.get(&key_d).unwrap(), value_e); } #[test] fn test_read_file_smoke() { let s = read_to_string("test-data/test.init").unwrap(); let c = Config::read_str(&s); s.lines() .zip(c.print().lines()) .for_each(|(a, b)| assert_eq!(a, b)); } #[test] fn test_len() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let e: String = random_alphanumeric(); let f: String = random_alphanumeric(); let g: String = random_alphanumeric(); let mut conf = Config::read_str(format!("[{}:{}]\r\nfoo bar\r\n[{}:{}]", a, b, c, d)); assert_eq!(conf.len(), 2); conf.set(&e, &f); assert_eq!(conf.len(), 3); conf.set(&e, &g); assert_eq!(conf.len(), 3); } #[test] #[should_panic] fn panic_on_empty_set() { let mut c = Config::new(); c.set("", ""); } #[test] #[should_panic] fn panic_on_non_alphanumeric_set() { let mut c = Config::new(); c.set("\r", "\n"); } #[test] fn test_keys_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_iter(); assert_eq!(Some(a.as_ref()), iter.next()); assert_eq!(Some(b.as_ref()), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_remove() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let mut conf = Config::read_str(format!( "[{}:foo]\r\n[{}:bar]\r\n[{}:bar2]\r\n[{}:foobar]\r\n[{}:foobar2]", a, b, b, c, d )); assert_eq!(conf.len(), 5); assert_eq!(conf.remove(&b), 2); assert_eq!(conf.len(), 3); assert_eq!(conf.get(&b), None); assert_eq!(conf.remove(&a), 1); assert_eq!(conf.len(), 2); assert_eq!(conf.get(&a), None); assert_eq!(conf.remove(random_alphanumeric()), 0); } #[test] fn test_keys_values_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_values_iter(); assert_eq!(Some((a.as_ref(), "foo")), iter.next()); assert_eq!(Some((b.as_ref(), "bar")), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_hashmap() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let hash_map_owned: HashMap<String, String> = conf.into(); assert_eq!(hash_map_owned.len(), 2); assert_eq!(hash_map_owned.get(&a).unwrap(), "foo"); assert_eq!(hash_map_owned.get(&b).unwrap(), "bar"); } }
get_value
identifier_name
lib.rs
//! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format). //! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies: //! //! * [`Config::get`] returns the last occurrence value, if config specifies the key more than once. //! * Whitespaces are not allowed at the start of lines, any line not starting with `[` character is treated as a comment. //! //! Other notable functionality is that the parser preserves all of the parsed string content, including blank lines and comments. //! //! # Examples //! //! ```no_run //! # use std::io; //! use std::fs::{read_to_string, write}; //! use dfconfig::Config; //! //! // Parse existing config //! let path = r"/path/to/df/data/init/init.txt"; //! let mut conf = Config::read_str(read_to_string(path)?); //! //! // Read some value //! let sound = conf.get("SOUND"); //! //! // Modify and save the config //! conf.set("VOLUME", "128"); //! write(path, conf.print())?; //! # Ok::<(), io::Error>(()) //! ``` #[macro_use] extern crate lazy_static; use std::collections::HashMap; use regex::Regex; #[derive(Clone, Debug)] enum Line { Blank, Comment(String), Entry(Entry), } #[derive(Clone, Debug)] struct Entry { key: String, value: String, } impl Entry { pub fn new(key: String, value: String) -> Self { Self { key, value } } pub fn get_value(&self) -> &str { &self.value } pub fn get_key(&self) -> &str { &self.key } pub fn set_value(&mut self, value: String) { self.value = value; } } /// The main struct of this crate. Represents DF config file, while also providing functions to parse and manipulate the data. /// See crate doc for example usage. #[doc(inline)] #[derive(Clone, Debug)] pub struct Config { lines: Vec<Line>, } impl Config { /// Creates an empty config. pub fn new() -> Self { Self { lines: vec![] } } /// Parse the config from a string. pub fn read_str<T: AsRef<str>>(input: T) -> Self { lazy_static! { static ref RE: Regex = Regex::new(r"^\[([\w\d]+):([\w\d:]+)\]$").unwrap(); } let mut lines = Vec::<Line>::new(); for l in input.as_ref().lines() { let lt = l.trim_end(); if lt.is_empty() { lines.push(Line::Blank); continue; } let captures = RE.captures(lt); match captures { Some(c) => lines.push(Line::Entry(Entry::new( c.get(1).unwrap().as_str().to_owned(), c.get(2).unwrap().as_str().to_owned(), ))), None => lines.push(Line::Comment(l.to_owned())), }; } Self { lines } } /// Tries to retrieve the value for `key`. /// If the key is defined more than once, returns the value of the last occurrence. pub fn get<T: AsRef<str>>(&self, key: T) -> Option<&str> { self.lines.iter().rev().find_map(|x| match x { Line::Entry(entry) => { if entry.get_key() == key.as_ref() { Some(entry.get_value()) } else { None } } _ => None, }) } /// Sets all the occurrences of `key` to `value` /// /// # Panics /// /// Panics if `key` or `value` is either empty or non-alphanumeric. pub fn set<T: AsRef<str>, U: Into<String>>(&mut self, key: T, value: U) { let key = key.as_ref(); let value = value.into(); if key.is_empty() ||!key.chars().all(|x| x.is_alphanumeric()) || value.is_empty() ||!value.chars().all(|x| x.is_alphanumeric()) { panic!("Both key and value have to be non-empty alphanumeric strings!")
if let Line::Entry(entry) = e { if entry.get_key() == key { entry.set_value(value.clone()); n += 1; } } } if n == 0 { self.lines .push(Line::Entry(Entry::new(key.to_string(), value))); } } /// Removes all occurrences of `key` from this `Config`. Returns the number of keys removed. pub fn remove<T: AsRef<str>>(&mut self, key: T) -> usize { let mut n: usize = 0; loop { let to_remove = self.lines.iter().enumerate().find_map(|(i, x)| { if let Line::Entry(entry) = x { if entry.get_key() == key.as_ref() { return Some(i); } } None }); match to_remove { None => break, Some(i) => { self.lines.remove(i); n += 1; } }; } n } /// Returns number of configuration entries present in this `Config`. pub fn len(&self) -> usize { self.lines .iter() .filter(|&x| matches!(x, Line::Entry(_))) .count() } /// Returns true if there are no entries defined in this `Config`. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the `key` strings. pub fn keys_iter(&self) -> impl Iterator<Item = &str> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some(entry.get_key()) } else { None } }) } /// Returns an iterator over (`key`, `value`) tuples. pub fn keys_values_iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some((entry.get_key(), entry.get_value())) } else { None } }) } /// Returns the string representing the configuration in its current state (aka what you'd write to the file usually). pub fn print(&self) -> String { let mut buff = Vec::<String>::with_capacity(self.lines.len()); for l in self.lines.iter() { match l { Line::Blank => buff.push("".to_string()), Line::Comment(x) => buff.push(x.to_string()), Line::Entry(entry) => { buff.push(format!("[{}:{}]", entry.get_key(), entry.get_value())) } } } buff.join("\r\n") } } impl From<Config> for HashMap<String, String> { fn from(conf: Config) -> Self { let mut output = HashMap::new(); conf.keys_values_iter().for_each(|(key, value)| { output.insert(key.to_owned(), value.to_owned()); }); output } } impl Default for Config { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::fs::read_to_string; use std::iter; use super::*; fn random_alphanumeric() -> String { let mut rng = thread_rng(); iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .map(char::from) .take(thread_rng().gen_range(1..50)) .collect() } #[test] fn test_basic_parse() { let key = random_alphanumeric(); let key2 = random_alphanumeric(); let value: String = random_alphanumeric(); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); assert_eq!(c.get(key2), None); } #[test] fn test_multi_value() { let key = random_alphanumeric(); let value: String = format!("{}:{}", random_alphanumeric(), random_alphanumeric()); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_basic_set() { let key = random_alphanumeric(); let value: String = random_alphanumeric(); let mut c = Config::new(); c.set(&key, &value); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_read_modify() { let key_a = random_alphanumeric(); let value_b: String = random_alphanumeric(); let value_c: String = random_alphanumeric(); let key_d = random_alphanumeric(); let value_e: String = random_alphanumeric(); let mut c = Config::read_str(format!("[{}:{}]", key_a, value_b)); assert_eq!(c.get(&key_a).unwrap(), value_b); c.set(&key_a, &value_c); assert_eq!(c.get(&key_a).unwrap(), value_c); c.set(&key_d, &value_e); assert_eq!(c.get(&key_a).unwrap(), value_c); assert_eq!(c.get(&key_d).unwrap(), value_e); } #[test] fn test_read_file_smoke() { let s = read_to_string("test-data/test.init").unwrap(); let c = Config::read_str(&s); s.lines() .zip(c.print().lines()) .for_each(|(a, b)| assert_eq!(a, b)); } #[test] fn test_len() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let e: String = random_alphanumeric(); let f: String = random_alphanumeric(); let g: String = random_alphanumeric(); let mut conf = Config::read_str(format!("[{}:{}]\r\nfoo bar\r\n[{}:{}]", a, b, c, d)); assert_eq!(conf.len(), 2); conf.set(&e, &f); assert_eq!(conf.len(), 3); conf.set(&e, &g); assert_eq!(conf.len(), 3); } #[test] #[should_panic] fn panic_on_empty_set() { let mut c = Config::new(); c.set("", ""); } #[test] #[should_panic] fn panic_on_non_alphanumeric_set() { let mut c = Config::new(); c.set("\r", "\n"); } #[test] fn test_keys_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_iter(); assert_eq!(Some(a.as_ref()), iter.next()); assert_eq!(Some(b.as_ref()), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_remove() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let mut conf = Config::read_str(format!( "[{}:foo]\r\n[{}:bar]\r\n[{}:bar2]\r\n[{}:foobar]\r\n[{}:foobar2]", a, b, b, c, d )); assert_eq!(conf.len(), 5); assert_eq!(conf.remove(&b), 2); assert_eq!(conf.len(), 3); assert_eq!(conf.get(&b), None); assert_eq!(conf.remove(&a), 1); assert_eq!(conf.len(), 2); assert_eq!(conf.get(&a), None); assert_eq!(conf.remove(random_alphanumeric()), 0); } #[test] fn test_keys_values_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_values_iter(); assert_eq!(Some((a.as_ref(), "foo")), iter.next()); assert_eq!(Some((b.as_ref(), "bar")), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_hashmap() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let hash_map_owned: HashMap<String, String> = conf.into(); assert_eq!(hash_map_owned.len(), 2); assert_eq!(hash_map_owned.get(&a).unwrap(), "foo"); assert_eq!(hash_map_owned.get(&b).unwrap(), "bar"); } }
} let mut n = 0; for e in self.lines.iter_mut() {
random_line_split
lib.rs
//! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format). //! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies: //! //! * [`Config::get`] returns the last occurrence value, if config specifies the key more than once. //! * Whitespaces are not allowed at the start of lines, any line not starting with `[` character is treated as a comment. //! //! Other notable functionality is that the parser preserves all of the parsed string content, including blank lines and comments. //! //! # Examples //! //! ```no_run //! # use std::io; //! use std::fs::{read_to_string, write}; //! use dfconfig::Config; //! //! // Parse existing config //! let path = r"/path/to/df/data/init/init.txt"; //! let mut conf = Config::read_str(read_to_string(path)?); //! //! // Read some value //! let sound = conf.get("SOUND"); //! //! // Modify and save the config //! conf.set("VOLUME", "128"); //! write(path, conf.print())?; //! # Ok::<(), io::Error>(()) //! ``` #[macro_use] extern crate lazy_static; use std::collections::HashMap; use regex::Regex; #[derive(Clone, Debug)] enum Line { Blank, Comment(String), Entry(Entry), } #[derive(Clone, Debug)] struct Entry { key: String, value: String, } impl Entry { pub fn new(key: String, value: String) -> Self { Self { key, value } } pub fn get_value(&self) -> &str { &self.value } pub fn get_key(&self) -> &str { &self.key } pub fn set_value(&mut self, value: String) { self.value = value; } } /// The main struct of this crate. Represents DF config file, while also providing functions to parse and manipulate the data. /// See crate doc for example usage. #[doc(inline)] #[derive(Clone, Debug)] pub struct Config { lines: Vec<Line>, } impl Config { /// Creates an empty config. pub fn new() -> Self { Self { lines: vec![] } } /// Parse the config from a string. pub fn read_str<T: AsRef<str>>(input: T) -> Self { lazy_static! { static ref RE: Regex = Regex::new(r"^\[([\w\d]+):([\w\d:]+)\]$").unwrap(); } let mut lines = Vec::<Line>::new(); for l in input.as_ref().lines() { let lt = l.trim_end(); if lt.is_empty() { lines.push(Line::Blank); continue; } let captures = RE.captures(lt); match captures { Some(c) => lines.push(Line::Entry(Entry::new( c.get(1).unwrap().as_str().to_owned(), c.get(2).unwrap().as_str().to_owned(), ))), None => lines.push(Line::Comment(l.to_owned())), }; } Self { lines } } /// Tries to retrieve the value for `key`. /// If the key is defined more than once, returns the value of the last occurrence. pub fn get<T: AsRef<str>>(&self, key: T) -> Option<&str> { self.lines.iter().rev().find_map(|x| match x { Line::Entry(entry) => { if entry.get_key() == key.as_ref() { Some(entry.get_value()) } else { None } } _ => None, }) } /// Sets all the occurrences of `key` to `value` /// /// # Panics /// /// Panics if `key` or `value` is either empty or non-alphanumeric. pub fn set<T: AsRef<str>, U: Into<String>>(&mut self, key: T, value: U) { let key = key.as_ref(); let value = value.into(); if key.is_empty() ||!key.chars().all(|x| x.is_alphanumeric()) || value.is_empty() ||!value.chars().all(|x| x.is_alphanumeric()) { panic!("Both key and value have to be non-empty alphanumeric strings!") } let mut n = 0; for e in self.lines.iter_mut() { if let Line::Entry(entry) = e { if entry.get_key() == key { entry.set_value(value.clone()); n += 1; } } } if n == 0 { self.lines .push(Line::Entry(Entry::new(key.to_string(), value))); } } /// Removes all occurrences of `key` from this `Config`. Returns the number of keys removed. pub fn remove<T: AsRef<str>>(&mut self, key: T) -> usize { let mut n: usize = 0; loop { let to_remove = self.lines.iter().enumerate().find_map(|(i, x)| { if let Line::Entry(entry) = x { if entry.get_key() == key.as_ref() { return Some(i); } } None }); match to_remove { None => break, Some(i) => { self.lines.remove(i); n += 1; } }; } n } /// Returns number of configuration entries present in this `Config`. pub fn len(&self) -> usize { self.lines .iter() .filter(|&x| matches!(x, Line::Entry(_))) .count() } /// Returns true if there are no entries defined in this `Config`. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the `key` strings. pub fn keys_iter(&self) -> impl Iterator<Item = &str> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some(entry.get_key()) } else { None } }) } /// Returns an iterator over (`key`, `value`) tuples. pub fn keys_values_iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some((entry.get_key(), entry.get_value())) } else { None } }) } /// Returns the string representing the configuration in its current state (aka what you'd write to the file usually). pub fn print(&self) -> String { let mut buff = Vec::<String>::with_capacity(self.lines.len()); for l in self.lines.iter() { match l { Line::Blank => buff.push("".to_string()), Line::Comment(x) => buff.push(x.to_string()), Line::Entry(entry) => { buff.push(format!("[{}:{}]", entry.get_key(), entry.get_value())) } } } buff.join("\r\n") } } impl From<Config> for HashMap<String, String> { fn from(conf: Config) -> Self
} impl Default for Config { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::fs::read_to_string; use std::iter; use super::*; fn random_alphanumeric() -> String { let mut rng = thread_rng(); iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .map(char::from) .take(thread_rng().gen_range(1..50)) .collect() } #[test] fn test_basic_parse() { let key = random_alphanumeric(); let key2 = random_alphanumeric(); let value: String = random_alphanumeric(); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); assert_eq!(c.get(key2), None); } #[test] fn test_multi_value() { let key = random_alphanumeric(); let value: String = format!("{}:{}", random_alphanumeric(), random_alphanumeric()); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_basic_set() { let key = random_alphanumeric(); let value: String = random_alphanumeric(); let mut c = Config::new(); c.set(&key, &value); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_read_modify() { let key_a = random_alphanumeric(); let value_b: String = random_alphanumeric(); let value_c: String = random_alphanumeric(); let key_d = random_alphanumeric(); let value_e: String = random_alphanumeric(); let mut c = Config::read_str(format!("[{}:{}]", key_a, value_b)); assert_eq!(c.get(&key_a).unwrap(), value_b); c.set(&key_a, &value_c); assert_eq!(c.get(&key_a).unwrap(), value_c); c.set(&key_d, &value_e); assert_eq!(c.get(&key_a).unwrap(), value_c); assert_eq!(c.get(&key_d).unwrap(), value_e); } #[test] fn test_read_file_smoke() { let s = read_to_string("test-data/test.init").unwrap(); let c = Config::read_str(&s); s.lines() .zip(c.print().lines()) .for_each(|(a, b)| assert_eq!(a, b)); } #[test] fn test_len() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let e: String = random_alphanumeric(); let f: String = random_alphanumeric(); let g: String = random_alphanumeric(); let mut conf = Config::read_str(format!("[{}:{}]\r\nfoo bar\r\n[{}:{}]", a, b, c, d)); assert_eq!(conf.len(), 2); conf.set(&e, &f); assert_eq!(conf.len(), 3); conf.set(&e, &g); assert_eq!(conf.len(), 3); } #[test] #[should_panic] fn panic_on_empty_set() { let mut c = Config::new(); c.set("", ""); } #[test] #[should_panic] fn panic_on_non_alphanumeric_set() { let mut c = Config::new(); c.set("\r", "\n"); } #[test] fn test_keys_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_iter(); assert_eq!(Some(a.as_ref()), iter.next()); assert_eq!(Some(b.as_ref()), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_remove() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let mut conf = Config::read_str(format!( "[{}:foo]\r\n[{}:bar]\r\n[{}:bar2]\r\n[{}:foobar]\r\n[{}:foobar2]", a, b, b, c, d )); assert_eq!(conf.len(), 5); assert_eq!(conf.remove(&b), 2); assert_eq!(conf.len(), 3); assert_eq!(conf.get(&b), None); assert_eq!(conf.remove(&a), 1); assert_eq!(conf.len(), 2); assert_eq!(conf.get(&a), None); assert_eq!(conf.remove(random_alphanumeric()), 0); } #[test] fn test_keys_values_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_values_iter(); assert_eq!(Some((a.as_ref(), "foo")), iter.next()); assert_eq!(Some((b.as_ref(), "bar")), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_hashmap() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let hash_map_owned: HashMap<String, String> = conf.into(); assert_eq!(hash_map_owned.len(), 2); assert_eq!(hash_map_owned.get(&a).unwrap(), "foo"); assert_eq!(hash_map_owned.get(&b).unwrap(), "bar"); } }
{ let mut output = HashMap::new(); conf.keys_values_iter().for_each(|(key, value)| { output.insert(key.to_owned(), value.to_owned()); }); output }
identifier_body
ctrl_map.rs
//! Maps MIDI controllers to synth parameters. use super::{ParamId, MenuItem}; use super::SoundData; use super::SynthParam; use super::ValueRange; use log::{info, trace}; use serde::{Serialize, Deserialize}; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum MappingType { None, Absolute, Relative } #[derive(Clone, Copy, Debug)] pub struct CtrlMapEntry { id: ParamId, map_type: MappingType, val_range: &'static ValueRange, } /// ValueRange contains a reference, so it can't be stored easily. Instead we /// store only ParamId and MappingType and rely on the TUI to look up the /// value range when loading the data. /// #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub struct CtrlMapStorageEntry { id: ParamId, map_type: MappingType, } type CtrlHashMap = HashMap<u64, CtrlMapEntry>; type CtrlHashMapStorage = HashMap<u64, CtrlMapStorageEntry>; pub struct CtrlMap { map: Vec<CtrlHashMap> } impl CtrlMap { pub fn new() -> CtrlMap { // 36 sets of controller mappings (0-9, a-z) CtrlMap{map: vec!(CtrlHashMap::new(); 36)} } /// Reset the map, removing all controller assignments. pub fn reset(&mut self) { for m in &mut self.map { m.clear(); } } /// Add a new mapping entry for a controller. /// /// set: The selected controller map set /// controller: The controller number to add /// map_type: Type of value change (absolute or relative) /// parameter: The parameter changed with this controller /// val_range: The valid values for the parameter /// pub fn add_mapping(&mut self, set: usize, controller: u64, map_type: MappingType, parameter: ParamId, val_range: &'static ValueRange) { trace!("add_mapping: Set {}, ctrl {}, type {:?}, param {:?}, val range {:?}", set, controller, map_type, parameter, val_range); self.map[set].insert(controller, CtrlMapEntry{id: parameter, map_type, val_range}); } /// Delete all mappings for a parameter. /// /// Returns true if one or more mappings were deleted, false otherwise pub fn delete_mapping(&mut self, set: usize, parameter: ParamId) -> bool { trace!("delete_mapping: Set {}, param {:?}", set, parameter); let mut controller: u64; let mut found = false; loop { controller = 0; for (key, val) in self.map[set].iter() { if val.id == parameter { controller = *key; } } if controller > 0 { self.map[set].remove(&controller); found = true; } else { break; } } found } /// Update a value according to the controller value. /// /// Uses the parameter's val_range to translate the controller value into /// a valid parameter value. /// /// set: The selected controller map set /// controller: The controller number to look up /// value: New value of the controller /// sound: Currently active sound /// result: SynthParam that receives the changed value /// /// Return true if result was updated, false otherwise /// pub fn get_value(&self, set: usize, controller: u64, value: u64, sound: &SoundData) -> Result<SynthParam, ()> { // Get mapping if!self.map[set].contains_key(&controller) { return Err(()); } let mapping = &self.map[set][&controller]; let mut result = SynthParam::new_from(&mapping.id); match mapping.map_type { MappingType::Absolute => { // For absolute: Translate value let trans_val = mapping.val_range.translate_value(value); result.value = trans_val; } MappingType::Relative => { // For relative: Increase/ decrease value let sound_value = sound.get_value(&mapping.id); let delta = if value >= 64 { -1 } else { 1 }; result.value = mapping.val_range.add_value(sound_value, delta); } MappingType::None => panic!(), }; Ok(result) } // Load controller mappings from file pub fn load(&mut self, filename: &str) -> std::io::Result<()> { info!("Reading controller mapping from {}", filename); let file = File::open(filename)?; let mut reader = BufReader::new(file); self.reset(); let mut serialized = String::new(); reader.read_to_string(&mut serialized)?; let storage_map: Vec<CtrlHashMapStorage> = serde_json::from_str(&serialized).unwrap(); for (i, item) in storage_map.iter().enumerate() { for (key, value) in item { let val_range = MenuItem::get_val_range(value.id.function, value.id.parameter); self.map[i].insert(*key, CtrlMapEntry{id: value.id, map_type: value.map_type, val_range}); } } Ok(()) } // Store controller mappings to file pub fn save(&self, filename: &str) -> std::io::Result<()> { info!("Writing controller mapping to {}", filename); // Transfer data into serializable format let mut storage_map = vec!(CtrlHashMapStorage::new(); 36); for (i, item) in self.map.iter().enumerate() { for (key, value) in item { storage_map[i].insert(*key, CtrlMapStorageEntry{id: value.id, map_type: value.map_type}); } } let mut file = File::create(filename)?; let serialized = serde_json::to_string_pretty(&storage_map).unwrap(); file.write_all(serialized.as_bytes())?; Ok(()) } } // ---------------------------------------------- // Unit tests // ---------------------------------------------- #[cfg(test)] mod tests { use super::{CtrlMap, MappingType}; use super::super::Float; use super::super::{Parameter, ParamId, ParameterValue, MenuItem}; use super::super::{SoundData, SoundPatch}; use super::super::SynthParam; use std::cell::RefCell; use std::rc::Rc; struct TestContext { map: CtrlMap, sound: SoundPatch, sound_data: Rc<RefCell<SoundData>>, param_id: ParamId, synth_param: SynthParam, } impl TestContext { fn new() -> TestContext { let map = CtrlMap::new(); let sound = SoundPatch::new(); let sound_data = Rc::new(RefCell::new(sound.data)); let param_id = ParamId::new(Parameter::Oscillator, 1, Parameter::Level); let synth_param = SynthParam::new(Parameter::Oscillator, 1, Parameter::Level, ParameterValue::Float(0.0)); TestContext{map, sound, sound_data, param_id, synth_param} } pub fn
(&mut self, ctrl_no: u64, ctrl_type: MappingType) { let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter); self.map.add_mapping(1, ctrl_no, ctrl_type, self.param_id, val_range); } pub fn handle_controller(&mut self, ctrl_no: u64, value: u64) -> bool { let sound_data = &mut self.sound_data.borrow_mut(); match self.map.get_value(1, ctrl_no, value, sound_data) { Ok(result) => { sound_data.set_parameter(&result); true } Err(()) => false } } pub fn has_value(&mut self, value: Float) -> bool { let pval = self.sound_data.borrow().get_value(&self.param_id); if let ParameterValue::Float(x) = pval { println!("\nIs: {} Expected: {}", x, value); x == value } else { false } } pub fn delete_controller(&mut self) -> bool { self.map.delete_mapping(1, self.param_id) } } #[test] fn controller_without_mapping_returns_no_value() { let mut context = TestContext::new(); assert_eq!(context.handle_controller(1, 50), false); } #[test] fn absolute_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_absolute() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(0.0), true); } #[test] fn relative_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_relative() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Relative); // Increase value assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(51.0), true); // Decrease value assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.has_value(50.0), true); } #[test] fn mapping_can_be_deleted() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.delete_controller(), true); assert_eq!(context.handle_controller(1, 127), false); } #[test] fn nonexisting_mapping_isnt_deleted() { let mut context = TestContext::new(); assert_eq!(context.delete_controller(), false); } } // mod tests
add_controller
identifier_name
ctrl_map.rs
//! Maps MIDI controllers to synth parameters. use super::{ParamId, MenuItem}; use super::SoundData; use super::SynthParam; use super::ValueRange; use log::{info, trace}; use serde::{Serialize, Deserialize}; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum MappingType { None, Absolute, Relative } #[derive(Clone, Copy, Debug)] pub struct CtrlMapEntry { id: ParamId, map_type: MappingType, val_range: &'static ValueRange, } /// ValueRange contains a reference, so it can't be stored easily. Instead we /// store only ParamId and MappingType and rely on the TUI to look up the /// value range when loading the data. /// #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub struct CtrlMapStorageEntry { id: ParamId, map_type: MappingType, } type CtrlHashMap = HashMap<u64, CtrlMapEntry>; type CtrlHashMapStorage = HashMap<u64, CtrlMapStorageEntry>; pub struct CtrlMap { map: Vec<CtrlHashMap> } impl CtrlMap { pub fn new() -> CtrlMap { // 36 sets of controller mappings (0-9, a-z) CtrlMap{map: vec!(CtrlHashMap::new(); 36)} } /// Reset the map, removing all controller assignments. pub fn reset(&mut self) { for m in &mut self.map { m.clear(); } } /// Add a new mapping entry for a controller. /// /// set: The selected controller map set /// controller: The controller number to add /// map_type: Type of value change (absolute or relative) /// parameter: The parameter changed with this controller /// val_range: The valid values for the parameter /// pub fn add_mapping(&mut self, set: usize, controller: u64, map_type: MappingType, parameter: ParamId, val_range: &'static ValueRange) { trace!("add_mapping: Set {}, ctrl {}, type {:?}, param {:?}, val range {:?}", set, controller, map_type, parameter, val_range); self.map[set].insert(controller, CtrlMapEntry{id: parameter, map_type, val_range}); } /// Delete all mappings for a parameter. /// /// Returns true if one or more mappings were deleted, false otherwise pub fn delete_mapping(&mut self, set: usize, parameter: ParamId) -> bool { trace!("delete_mapping: Set {}, param {:?}", set, parameter); let mut controller: u64; let mut found = false; loop { controller = 0; for (key, val) in self.map[set].iter() { if val.id == parameter { controller = *key; } } if controller > 0 { self.map[set].remove(&controller); found = true; } else { break; } } found } /// Update a value according to the controller value. /// /// Uses the parameter's val_range to translate the controller value into /// a valid parameter value. /// /// set: The selected controller map set /// controller: The controller number to look up /// value: New value of the controller /// sound: Currently active sound /// result: SynthParam that receives the changed value /// /// Return true if result was updated, false otherwise /// pub fn get_value(&self, set: usize, controller: u64, value: u64, sound: &SoundData) -> Result<SynthParam, ()> { // Get mapping if!self.map[set].contains_key(&controller) { return Err(()); } let mapping = &self.map[set][&controller]; let mut result = SynthParam::new_from(&mapping.id); match mapping.map_type { MappingType::Absolute => { // For absolute: Translate value let trans_val = mapping.val_range.translate_value(value); result.value = trans_val; } MappingType::Relative =>
MappingType::None => panic!(), }; Ok(result) } // Load controller mappings from file pub fn load(&mut self, filename: &str) -> std::io::Result<()> { info!("Reading controller mapping from {}", filename); let file = File::open(filename)?; let mut reader = BufReader::new(file); self.reset(); let mut serialized = String::new(); reader.read_to_string(&mut serialized)?; let storage_map: Vec<CtrlHashMapStorage> = serde_json::from_str(&serialized).unwrap(); for (i, item) in storage_map.iter().enumerate() { for (key, value) in item { let val_range = MenuItem::get_val_range(value.id.function, value.id.parameter); self.map[i].insert(*key, CtrlMapEntry{id: value.id, map_type: value.map_type, val_range}); } } Ok(()) } // Store controller mappings to file pub fn save(&self, filename: &str) -> std::io::Result<()> { info!("Writing controller mapping to {}", filename); // Transfer data into serializable format let mut storage_map = vec!(CtrlHashMapStorage::new(); 36); for (i, item) in self.map.iter().enumerate() { for (key, value) in item { storage_map[i].insert(*key, CtrlMapStorageEntry{id: value.id, map_type: value.map_type}); } } let mut file = File::create(filename)?; let serialized = serde_json::to_string_pretty(&storage_map).unwrap(); file.write_all(serialized.as_bytes())?; Ok(()) } } // ---------------------------------------------- // Unit tests // ---------------------------------------------- #[cfg(test)] mod tests { use super::{CtrlMap, MappingType}; use super::super::Float; use super::super::{Parameter, ParamId, ParameterValue, MenuItem}; use super::super::{SoundData, SoundPatch}; use super::super::SynthParam; use std::cell::RefCell; use std::rc::Rc; struct TestContext { map: CtrlMap, sound: SoundPatch, sound_data: Rc<RefCell<SoundData>>, param_id: ParamId, synth_param: SynthParam, } impl TestContext { fn new() -> TestContext { let map = CtrlMap::new(); let sound = SoundPatch::new(); let sound_data = Rc::new(RefCell::new(sound.data)); let param_id = ParamId::new(Parameter::Oscillator, 1, Parameter::Level); let synth_param = SynthParam::new(Parameter::Oscillator, 1, Parameter::Level, ParameterValue::Float(0.0)); TestContext{map, sound, sound_data, param_id, synth_param} } pub fn add_controller(&mut self, ctrl_no: u64, ctrl_type: MappingType) { let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter); self.map.add_mapping(1, ctrl_no, ctrl_type, self.param_id, val_range); } pub fn handle_controller(&mut self, ctrl_no: u64, value: u64) -> bool { let sound_data = &mut self.sound_data.borrow_mut(); match self.map.get_value(1, ctrl_no, value, sound_data) { Ok(result) => { sound_data.set_parameter(&result); true } Err(()) => false } } pub fn has_value(&mut self, value: Float) -> bool { let pval = self.sound_data.borrow().get_value(&self.param_id); if let ParameterValue::Float(x) = pval { println!("\nIs: {} Expected: {}", x, value); x == value } else { false } } pub fn delete_controller(&mut self) -> bool { self.map.delete_mapping(1, self.param_id) } } #[test] fn controller_without_mapping_returns_no_value() { let mut context = TestContext::new(); assert_eq!(context.handle_controller(1, 50), false); } #[test] fn absolute_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_absolute() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(0.0), true); } #[test] fn relative_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_relative() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Relative); // Increase value assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(51.0), true); // Decrease value assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.has_value(50.0), true); } #[test] fn mapping_can_be_deleted() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.delete_controller(), true); assert_eq!(context.handle_controller(1, 127), false); } #[test] fn nonexisting_mapping_isnt_deleted() { let mut context = TestContext::new(); assert_eq!(context.delete_controller(), false); } } // mod tests
{ // For relative: Increase/ decrease value let sound_value = sound.get_value(&mapping.id); let delta = if value >= 64 { -1 } else { 1 }; result.value = mapping.val_range.add_value(sound_value, delta); }
conditional_block
ctrl_map.rs
//! Maps MIDI controllers to synth parameters. use super::{ParamId, MenuItem}; use super::SoundData; use super::SynthParam; use super::ValueRange; use log::{info, trace}; use serde::{Serialize, Deserialize}; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum MappingType { None, Absolute, Relative } #[derive(Clone, Copy, Debug)] pub struct CtrlMapEntry { id: ParamId, map_type: MappingType, val_range: &'static ValueRange, } /// ValueRange contains a reference, so it can't be stored easily. Instead we /// store only ParamId and MappingType and rely on the TUI to look up the /// value range when loading the data. /// #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub struct CtrlMapStorageEntry { id: ParamId, map_type: MappingType, } type CtrlHashMap = HashMap<u64, CtrlMapEntry>; type CtrlHashMapStorage = HashMap<u64, CtrlMapStorageEntry>; pub struct CtrlMap { map: Vec<CtrlHashMap> } impl CtrlMap { pub fn new() -> CtrlMap { // 36 sets of controller mappings (0-9, a-z) CtrlMap{map: vec!(CtrlHashMap::new(); 36)} } /// Reset the map, removing all controller assignments. pub fn reset(&mut self) { for m in &mut self.map { m.clear(); } } /// Add a new mapping entry for a controller. /// /// set: The selected controller map set /// controller: The controller number to add /// map_type: Type of value change (absolute or relative) /// parameter: The parameter changed with this controller /// val_range: The valid values for the parameter /// pub fn add_mapping(&mut self, set: usize, controller: u64, map_type: MappingType, parameter: ParamId, val_range: &'static ValueRange) { trace!("add_mapping: Set {}, ctrl {}, type {:?}, param {:?}, val range {:?}", set, controller, map_type, parameter, val_range); self.map[set].insert(controller, CtrlMapEntry{id: parameter, map_type, val_range}); } /// Delete all mappings for a parameter. /// /// Returns true if one or more mappings were deleted, false otherwise pub fn delete_mapping(&mut self, set: usize, parameter: ParamId) -> bool { trace!("delete_mapping: Set {}, param {:?}", set, parameter); let mut controller: u64; let mut found = false; loop { controller = 0; for (key, val) in self.map[set].iter() { if val.id == parameter { controller = *key; } } if controller > 0 { self.map[set].remove(&controller); found = true; } else { break; } } found } /// Update a value according to the controller value. /// /// Uses the parameter's val_range to translate the controller value into /// a valid parameter value. /// /// set: The selected controller map set /// controller: The controller number to look up /// value: New value of the controller /// sound: Currently active sound /// result: SynthParam that receives the changed value /// /// Return true if result was updated, false otherwise /// pub fn get_value(&self,
controller: u64, value: u64, sound: &SoundData) -> Result<SynthParam, ()> { // Get mapping if!self.map[set].contains_key(&controller) { return Err(()); } let mapping = &self.map[set][&controller]; let mut result = SynthParam::new_from(&mapping.id); match mapping.map_type { MappingType::Absolute => { // For absolute: Translate value let trans_val = mapping.val_range.translate_value(value); result.value = trans_val; } MappingType::Relative => { // For relative: Increase/ decrease value let sound_value = sound.get_value(&mapping.id); let delta = if value >= 64 { -1 } else { 1 }; result.value = mapping.val_range.add_value(sound_value, delta); } MappingType::None => panic!(), }; Ok(result) } // Load controller mappings from file pub fn load(&mut self, filename: &str) -> std::io::Result<()> { info!("Reading controller mapping from {}", filename); let file = File::open(filename)?; let mut reader = BufReader::new(file); self.reset(); let mut serialized = String::new(); reader.read_to_string(&mut serialized)?; let storage_map: Vec<CtrlHashMapStorage> = serde_json::from_str(&serialized).unwrap(); for (i, item) in storage_map.iter().enumerate() { for (key, value) in item { let val_range = MenuItem::get_val_range(value.id.function, value.id.parameter); self.map[i].insert(*key, CtrlMapEntry{id: value.id, map_type: value.map_type, val_range}); } } Ok(()) } // Store controller mappings to file pub fn save(&self, filename: &str) -> std::io::Result<()> { info!("Writing controller mapping to {}", filename); // Transfer data into serializable format let mut storage_map = vec!(CtrlHashMapStorage::new(); 36); for (i, item) in self.map.iter().enumerate() { for (key, value) in item { storage_map[i].insert(*key, CtrlMapStorageEntry{id: value.id, map_type: value.map_type}); } } let mut file = File::create(filename)?; let serialized = serde_json::to_string_pretty(&storage_map).unwrap(); file.write_all(serialized.as_bytes())?; Ok(()) } } // ---------------------------------------------- // Unit tests // ---------------------------------------------- #[cfg(test)] mod tests { use super::{CtrlMap, MappingType}; use super::super::Float; use super::super::{Parameter, ParamId, ParameterValue, MenuItem}; use super::super::{SoundData, SoundPatch}; use super::super::SynthParam; use std::cell::RefCell; use std::rc::Rc; struct TestContext { map: CtrlMap, sound: SoundPatch, sound_data: Rc<RefCell<SoundData>>, param_id: ParamId, synth_param: SynthParam, } impl TestContext { fn new() -> TestContext { let map = CtrlMap::new(); let sound = SoundPatch::new(); let sound_data = Rc::new(RefCell::new(sound.data)); let param_id = ParamId::new(Parameter::Oscillator, 1, Parameter::Level); let synth_param = SynthParam::new(Parameter::Oscillator, 1, Parameter::Level, ParameterValue::Float(0.0)); TestContext{map, sound, sound_data, param_id, synth_param} } pub fn add_controller(&mut self, ctrl_no: u64, ctrl_type: MappingType) { let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter); self.map.add_mapping(1, ctrl_no, ctrl_type, self.param_id, val_range); } pub fn handle_controller(&mut self, ctrl_no: u64, value: u64) -> bool { let sound_data = &mut self.sound_data.borrow_mut(); match self.map.get_value(1, ctrl_no, value, sound_data) { Ok(result) => { sound_data.set_parameter(&result); true } Err(()) => false } } pub fn has_value(&mut self, value: Float) -> bool { let pval = self.sound_data.borrow().get_value(&self.param_id); if let ParameterValue::Float(x) = pval { println!("\nIs: {} Expected: {}", x, value); x == value } else { false } } pub fn delete_controller(&mut self) -> bool { self.map.delete_mapping(1, self.param_id) } } #[test] fn controller_without_mapping_returns_no_value() { let mut context = TestContext::new(); assert_eq!(context.handle_controller(1, 50), false); } #[test] fn absolute_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_absolute() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(0.0), true); } #[test] fn relative_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_relative() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Relative); // Increase value assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(51.0), true); // Decrease value assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.has_value(50.0), true); } #[test] fn mapping_can_be_deleted() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.delete_controller(), true); assert_eq!(context.handle_controller(1, 127), false); } #[test] fn nonexisting_mapping_isnt_deleted() { let mut context = TestContext::new(); assert_eq!(context.delete_controller(), false); } } // mod tests
set: usize,
random_line_split
ctrl_map.rs
//! Maps MIDI controllers to synth parameters. use super::{ParamId, MenuItem}; use super::SoundData; use super::SynthParam; use super::ValueRange; use log::{info, trace}; use serde::{Serialize, Deserialize}; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum MappingType { None, Absolute, Relative } #[derive(Clone, Copy, Debug)] pub struct CtrlMapEntry { id: ParamId, map_type: MappingType, val_range: &'static ValueRange, } /// ValueRange contains a reference, so it can't be stored easily. Instead we /// store only ParamId and MappingType and rely on the TUI to look up the /// value range when loading the data. /// #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub struct CtrlMapStorageEntry { id: ParamId, map_type: MappingType, } type CtrlHashMap = HashMap<u64, CtrlMapEntry>; type CtrlHashMapStorage = HashMap<u64, CtrlMapStorageEntry>; pub struct CtrlMap { map: Vec<CtrlHashMap> } impl CtrlMap { pub fn new() -> CtrlMap { // 36 sets of controller mappings (0-9, a-z) CtrlMap{map: vec!(CtrlHashMap::new(); 36)} } /// Reset the map, removing all controller assignments. pub fn reset(&mut self) { for m in &mut self.map { m.clear(); } } /// Add a new mapping entry for a controller. /// /// set: The selected controller map set /// controller: The controller number to add /// map_type: Type of value change (absolute or relative) /// parameter: The parameter changed with this controller /// val_range: The valid values for the parameter /// pub fn add_mapping(&mut self, set: usize, controller: u64, map_type: MappingType, parameter: ParamId, val_range: &'static ValueRange) { trace!("add_mapping: Set {}, ctrl {}, type {:?}, param {:?}, val range {:?}", set, controller, map_type, parameter, val_range); self.map[set].insert(controller, CtrlMapEntry{id: parameter, map_type, val_range}); } /// Delete all mappings for a parameter. /// /// Returns true if one or more mappings were deleted, false otherwise pub fn delete_mapping(&mut self, set: usize, parameter: ParamId) -> bool { trace!("delete_mapping: Set {}, param {:?}", set, parameter); let mut controller: u64; let mut found = false; loop { controller = 0; for (key, val) in self.map[set].iter() { if val.id == parameter { controller = *key; } } if controller > 0 { self.map[set].remove(&controller); found = true; } else { break; } } found } /// Update a value according to the controller value. /// /// Uses the parameter's val_range to translate the controller value into /// a valid parameter value. /// /// set: The selected controller map set /// controller: The controller number to look up /// value: New value of the controller /// sound: Currently active sound /// result: SynthParam that receives the changed value /// /// Return true if result was updated, false otherwise /// pub fn get_value(&self, set: usize, controller: u64, value: u64, sound: &SoundData) -> Result<SynthParam, ()> { // Get mapping if!self.map[set].contains_key(&controller) { return Err(()); } let mapping = &self.map[set][&controller]; let mut result = SynthParam::new_from(&mapping.id); match mapping.map_type { MappingType::Absolute => { // For absolute: Translate value let trans_val = mapping.val_range.translate_value(value); result.value = trans_val; } MappingType::Relative => { // For relative: Increase/ decrease value let sound_value = sound.get_value(&mapping.id); let delta = if value >= 64 { -1 } else { 1 }; result.value = mapping.val_range.add_value(sound_value, delta); } MappingType::None => panic!(), }; Ok(result) } // Load controller mappings from file pub fn load(&mut self, filename: &str) -> std::io::Result<()> { info!("Reading controller mapping from {}", filename); let file = File::open(filename)?; let mut reader = BufReader::new(file); self.reset(); let mut serialized = String::new(); reader.read_to_string(&mut serialized)?; let storage_map: Vec<CtrlHashMapStorage> = serde_json::from_str(&serialized).unwrap(); for (i, item) in storage_map.iter().enumerate() { for (key, value) in item { let val_range = MenuItem::get_val_range(value.id.function, value.id.parameter); self.map[i].insert(*key, CtrlMapEntry{id: value.id, map_type: value.map_type, val_range}); } } Ok(()) } // Store controller mappings to file pub fn save(&self, filename: &str) -> std::io::Result<()> { info!("Writing controller mapping to {}", filename); // Transfer data into serializable format let mut storage_map = vec!(CtrlHashMapStorage::new(); 36); for (i, item) in self.map.iter().enumerate() { for (key, value) in item { storage_map[i].insert(*key, CtrlMapStorageEntry{id: value.id, map_type: value.map_type}); } } let mut file = File::create(filename)?; let serialized = serde_json::to_string_pretty(&storage_map).unwrap(); file.write_all(serialized.as_bytes())?; Ok(()) } } // ---------------------------------------------- // Unit tests // ---------------------------------------------- #[cfg(test)] mod tests { use super::{CtrlMap, MappingType}; use super::super::Float; use super::super::{Parameter, ParamId, ParameterValue, MenuItem}; use super::super::{SoundData, SoundPatch}; use super::super::SynthParam; use std::cell::RefCell; use std::rc::Rc; struct TestContext { map: CtrlMap, sound: SoundPatch, sound_data: Rc<RefCell<SoundData>>, param_id: ParamId, synth_param: SynthParam, } impl TestContext { fn new() -> TestContext { let map = CtrlMap::new(); let sound = SoundPatch::new(); let sound_data = Rc::new(RefCell::new(sound.data)); let param_id = ParamId::new(Parameter::Oscillator, 1, Parameter::Level); let synth_param = SynthParam::new(Parameter::Oscillator, 1, Parameter::Level, ParameterValue::Float(0.0)); TestContext{map, sound, sound_data, param_id, synth_param} } pub fn add_controller(&mut self, ctrl_no: u64, ctrl_type: MappingType) { let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter); self.map.add_mapping(1, ctrl_no, ctrl_type, self.param_id, val_range); } pub fn handle_controller(&mut self, ctrl_no: u64, value: u64) -> bool { let sound_data = &mut self.sound_data.borrow_mut(); match self.map.get_value(1, ctrl_no, value, sound_data) { Ok(result) => { sound_data.set_parameter(&result); true } Err(()) => false } } pub fn has_value(&mut self, value: Float) -> bool { let pval = self.sound_data.borrow().get_value(&self.param_id); if let ParameterValue::Float(x) = pval { println!("\nIs: {} Expected: {}", x, value); x == value } else { false } } pub fn delete_controller(&mut self) -> bool { self.map.delete_mapping(1, self.param_id) } } #[test] fn controller_without_mapping_returns_no_value() { let mut context = TestContext::new(); assert_eq!(context.handle_controller(1, 50), false); } #[test] fn absolute_controller_can_be_added()
#[test] fn value_can_be_changed_absolute() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(0.0), true); } #[test] fn relative_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_relative() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Relative); // Increase value assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(51.0), true); // Decrease value assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.has_value(50.0), true); } #[test] fn mapping_can_be_deleted() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.delete_controller(), true); assert_eq!(context.handle_controller(1, 127), false); } #[test] fn nonexisting_mapping_isnt_deleted() { let mut context = TestContext::new(); assert_eq!(context.delete_controller(), false); } } // mod tests
{ let mut context = TestContext::new(); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 50), true); }
identifier_body
random.rs
/// /// TODO: We should disallow re-seeding this RNG. pub fn global_rng() -> GlobalRng { GLOBAL_RNG_STATE.clone() } /// Call me if you want a cheap but insecure RNG seeded by the current system /// time. pub fn clocked_rng() -> MersenneTwisterRng { let mut rng = MersenneTwisterRng::mt19937(); let seed = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .subsec_nanos(); rng.seed_u32(seed); rng } /// Generates secure random bytes suitable for cryptographic key generation. /// This will wait for sufficient entropy to accumulate in the system. /// /// Once done, the provided buffer will be filled with the random bytes to the /// end. pub async fn secure_random_bytes(buf: &mut [u8]) -> Result<()> { // See http://man7.org/linux/man-pages/man7/random.7.html // TODO: Reuse the file handle across calls. let mut f = LocalFile::open("/dev/random")?; f.read_exact(buf).await?; Ok(()) } /// Securely generates a random value in the range '[lower, upper)'. /// /// This is implemented to give every integer in the range the same probabiity /// of being output. /// /// NOTE: Both the 'lower' and 'upper' numbers should be publicly known for this /// to be secure. /// /// The output integer will have the same width as the 'upper' integer. pub async fn secure_random_range( lower: &SecureBigUint, upper: &SecureBigUint, ) -> Result<SecureBigUint> { if upper.byte_width() == 0 || upper <= lower { return Err(err_msg("Invalid upper/lower range")); } let mut buf = vec![]; buf.resize(upper.byte_width(), 0); let mut num_bytes = ceil_div(upper.value_bits(), 8); let msb_mask: u8 = { let r = upper.value_bits() % 8; if r == 0 { 0xff } else { !((1 << (8 - r)) - 1) } }; // TODO: Refactor out retrying. Instead shift to 0 loop { secure_random_bytes(&mut buf[0..num_bytes]).await?; buf[num_bytes - 1] &= msb_mask; let n = SecureBigUint::from_le_bytes(&buf); // TODO: This *must* be a secure comparison (which it isn't right now). if &n >= lower && &n < upper { return Ok(n); } } } pub trait Rng { fn seed_size(&self) -> usize; fn seed(&mut self, new_seed: &[u8]); fn generate_bytes(&mut self, output: &mut [u8]); } #[async_trait] pub trait SharedRng:'static + Send + Sync { /// Number of bytes used to seed this RNG. fn seed_size(&self) -> usize; /// Should reset the state of the RNG based on the provided seed. /// Calling generate_bytes after calling reseed with the same seed should /// always produce the same result. async fn seed(&self, new_seed: &[u8]); async fn generate_bytes(&self, output: &mut [u8]); } #[derive(Clone)] pub struct GlobalRng { state: Arc<GlobalRngState>, } struct GlobalRngState { bytes_since_reseed: Mutex<usize>, rng: ChaCha20RNG, } impl GlobalRng { fn new() -> Self { Self { state: Arc::new(GlobalRngState { bytes_since_reseed: Mutex::new(std::usize::MAX), rng: ChaCha20RNG::new(), }), } } } #[async_trait] impl SharedRng for GlobalRng { fn seed_size(&self) -> usize { 0 } async fn seed(&self, _new_seed: &[u8]) { // Global RNG can't be manually reseeding panic!(); } async fn generate_bytes(&self, output: &mut [u8]) { { let mut counter = self.state.bytes_since_reseed.lock().await; if *counter > MAX_BYTES_BEFORE_RESEED { let mut new_seed = vec![0u8; self.state.rng.seed_size()]; secure_random_bytes(&mut new_seed).await.unwrap(); self.state.rng.seed(&new_seed).await; *counter = 0; } // NOTE: For now we ignore the case of a user requesting a quantity that // partially exceeds our max threshold. *counter += output.len(); } self.state.rng.generate_bytes(output).await } } #[async_trait] impl<R: Rng + Send +?Sized +'static> SharedRng for Mutex<R> { fn seed_size(&self) -> usize { todo!() // self.lock().await.seed_size() } async fn seed(&self, new_seed: &[u8]) { self.lock().await.seed(new_seed) } async fn generate_bytes(&self, output: &mut [u8]) { self.lock().await.generate_bytes(output) } } /// Sample random number generator based on ChaCha20 /// /// - During initialization and periodically afterwards, we (re-)generate the /// 256-bit key from a 'true random' source (/dev/random). /// - When a key is selected, we reset the nonce to 0. /// - The nonce is incremented by 1 for each block we encrypt. /// - The plaintext to be encrypted is the system time at key creation in /// nanoseconds. /// - All of the above are re-seeding in the background every 30 seconds. /// - Random bytes are generated by encrypting the plaintext with the current /// nonce and key. pub struct ChaCha20RNG { state: Mutex<ChaCha20RNGState>, } #[derive(Clone)] struct ChaCha20RNGState { key: [u8; CHACHA20_KEY_SIZE], nonce: u64, plaintext: [u8; CHACHA20_BLOCK_SIZE], } impl ChaCha20RNG { /// Creates a new instance of the rng with a fixed 'zero' seed. pub fn new() -> Self { Self { state: Mutex::new(ChaCha20RNGState { key: [0u8; CHACHA20_KEY_SIZE], nonce: 0, plaintext: [0u8; CHACHA20_BLOCK_SIZE], }), } } } #[async_trait] impl SharedRng for ChaCha20RNG { fn seed_size(&self) -> usize { CHACHA20_KEY_SIZE + CHACHA20_BLOCK_SIZE } async fn seed(&self, new_seed: &[u8]) { let mut state = self.state.lock().await; state.nonce = 0; state.key.copy_from_slice(&new_seed[0..CHACHA20_KEY_SIZE]); state .plaintext .copy_from_slice(&new_seed[CHACHA20_KEY_SIZE..]); } async fn generate_bytes(&self, mut output: &mut [u8]) { let state = { let mut guard = self.state.lock().await; let cur_state = guard.clone(); guard.nonce += 1; cur_state }; let mut nonce = [0u8; CHACHA20_NONCE_SIZE]; nonce[0..8].copy_from_slice(&state.nonce.to_ne_bytes()); let mut chacha = ChaCha20::new(&state.key, &nonce); while!output.is_empty() { let mut output_block = [0u8; CHACHA20_BLOCK_SIZE]; chacha.encrypt(&state.plaintext, &mut output_block); let n = std::cmp::min(output_block.len(), output.len()); output[0..n].copy_from_slice(&output_block[0..n]); output = &mut output[n..]; } } } #[async_trait] pub trait SharedRngExt { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]); async fn uniform<T: RngNumber>(&self) -> T; async fn between<T: RngNumber>(&self, min: T, max: T) -> T; } #[async_trait] impl<R: SharedRng +?Sized> SharedRngExt for Arc<R> { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { self.as_ref().shuffle(elements).await } async fn uniform<T: RngNumber>(&self) -> T { self.as_ref().uniform().await } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { self.as_ref().between(min, max).await } } #[async_trait] impl<R: SharedRng +?Sized> SharedRngExt for R { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>().await % elements.len(); elements.swap(i, j); } } async fn uniform<T: RngNumber>(&self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::uniform_buffer(buf) } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::between_buffer(buf, min, max) } } pub trait RngNumber: Send + Sync +'static { type Buffer: Send + Sync + Sized + Default + AsMut<[u8]>; fn uniform_buffer(random: Self::Buffer) -> Self; fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self; } macro_rules! ensure_positive { ($value:ident, I) => { if $value < 0 { $value * -1 } else { $value } }; ($value:ident, U) => { $value }; } macro_rules! impl_rng_number_integer { ($num:ident, $type_prefix:ident) => { impl RngNumber for $num { type Buffer = [u8; std::mem::size_of::<$num>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = Self::uniform_buffer(random); // In rust (negative_number % positive_number) = negative_number num = ensure_positive!(num, $type_prefix); // Convert to [0, range) let range = max - min; num = num % range; // Convert to [min, max) num += min; num } } }; } impl_rng_number_integer!(u8, U); impl_rng_number_integer!(i8, I); impl_rng_number_integer!(u16, U); impl_rng_number_integer!(i16, I); impl_rng_number_integer!(u32, U); impl_rng_number_integer!(i32, I); impl_rng_number_integer!(u64, U); impl_rng_number_integer!(i64, I); impl_rng_number_integer!(usize, U); impl_rng_number_integer!(isize, I); macro_rules! impl_rng_number_float { ($float_type:ident, $int_type:ident, $fraction_bits:expr, $zero_exponent:expr) => { impl RngNumber for $float_type { type Buffer = [u8; std::mem::size_of::<$float_type>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(mut random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = $int_type::from_le_bytes(random); // Clear the sign and exponent bits. num &= (1 << $fraction_bits) - 1; // Set the exponent to '0'. So the number will be (1 + fraction) * 2^0 num |= $zero_exponent << $fraction_bits; random = num.to_le_bytes(); // This will in the range [0, 1). let f = Self::from_le_bytes(random) - 1.0; // Convert to [min, max). let range = max - min; f * range + min } } }; } impl_rng_number_float!(f32, u32, 23, 127); impl_rng_number_float!(f64, u64, 52, 1023); pub trait RngExt { fn shuffle<T>(&mut self, elements: &mut [T]); fn uniform<T: RngNumber>(&mut self) -> T; fn between<T: RngNumber>(&mut self, min: T, max: T) -> T; fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T; } impl<R: Rng +?Sized> RngExt for R { fn shuffle<T>(&mut self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>() % elements.len(); elements.swap(i, j); } } /// Returns a completely random number anywhere in the range of the number /// type. Every number is equally probably of occuring. fn uniform<T: RngNumber>(&mut self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::uniform_buffer(buf) } /// Returns a uniform random number in the range [min, max). /// /// Limitations: /// -'max' must be >='min'. /// - For signed integer types for N bits,'max' -'min' must fit in N-1 /// bits. fn between<T: RngNumber>(&mut self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::between_buffer(buf, min, max) } fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T { assert!(!elements.is_empty(), "Choosing from empty list"); let n = self.uniform::<usize>(); &elements[n % elements.len()] } } pub const MT_DEFAULT_SEED: u32 = 5489; pub struct MersenneTwisterRng { w: u32, n: usize, m: usize, r: u32, a: u32, // b: u32, c: u32, s: u32, t: u32, u: u32, d: u32, l: u32, f: u32, x: Vec<u32>, index: usize, } impl MersenneTwisterRng { // TODO: Add a simple time seeded implementation. pub fn mt19937() -> Self
} pub fn seed_u32(&mut self, seed: u32) { self.x.resize(self.n, 0); self.index = self.n; self.x[0] = seed; for i in 1..self.n { self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2))) .wrapping_mul(self.f) .wrapping_add(i as u32); } } pub fn next_u32(&mut self) -> u32 { if self.x.is_empty() { self.seed_u32(MT_DEFAULT_SEED); } if self.index >= self.n { self.twist(); } let mut y = self.x[self.index]; y ^= (y >> self.u) & self.d; y ^= (y << self.s) & self.b; y ^= (y << self.t) & self.c; y ^= y >> self.l; self.index += 1; y } fn twist(&mut self) { let w_mask = 1u32.checked_shl(self.w).unwrap_or(0).wrapping_sub(1); let upper_mask = (w_mask << self.r) & w_mask; let lower_mask = (!upper_mask) & w_mask; self.index = 0; for i in 0..self.n { let x = (self.x[i] & upper_mask) | (self.x[(i + 1) % self.x.len()] & lower_mask); let mut x_a = x >> 1; if x & 1!= 0 { x_a = x_a ^ self.a; } self.x[i] = self.x[(i + self.m) % self.x.len()] ^ x_a; } } } impl Rng for MersenneTwisterRng { fn seed_size(&self) -> usize { std::mem::size_of::<u32>() } fn seed(&mut self, new_seed: &[u8]) { assert_eq!(new_seed.len(), std::mem::size_of::<u32>()); let seed_num = u32::from_le_bytes(*array_ref![new_seed, 0, 4]); self.seed_u32(seed_num); } fn generate_bytes(&mut self, output: &mut [u8]) { // NOTE: All of the 4's in here are std::mem::size_of::<u32>() let n = output.len() / 4; let r = output.len() % 4; for i in 0..n { *array_mut_ref![output, 4 * i, 4] = self.next_u32().to_le_bytes(); } if r!= 0 { let v = self.next_u32().to_le_bytes(); let i = output.len() - r; output[i..].copy_from_slice(&v[0..r]); } } } pub struct FixedBytesRng { data: Bytes, } impl FixedBytesRng { pub fn new<T: Into<Bytes>>(data: T) -> Self { Self { data: data.into() } } } impl Rng for FixedBytesRng { fn seed_size(&self) -> usize { panic!(); } fn seed(&mut self, _new_seed: &[u8]) { panic!(); } fn generate_bytes(&mut self, output: &mut [u8]) { if output.len() > self.data.len() { panic!(); } output.copy_from_slice(&self.data[0..output.len()]); self.data.advance(output.len()); } } pub struct NormalDistribution { mean: f64, stddev: f64, next_number: Option<f64>, } impl NormalDistribution { pub fn new(mean: f64, stddev: f64) -> Self { Self { mean, stddev, next_number: None, } } /// Given two uniformly sampled random numbers in the range [0, 1], computes /// two independent random values with a normal/gaussian distribution /// with mean of 0 and standard deviation of 1. /// See https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform fn box_muller_transform(u1: f64, u2: f64) -> (f64, f64) { let theta = 2.0 * PI * u2; let (sin, cos) = theta.sin_cos(); let r = (-2.0 * u1.ln()).sqrt(); (r * sin, r * cos) } } pub trait NormalDistributionRngExt { fn next(&mut self, rng: &mut dyn Rng) -> f64; } impl NormalDistributionRngExt for NormalDistribution { fn next(&mut self, rng: &mut dyn Rng) -> f64 { if let Some(v) = self.next_number.take() { return v; } let u1 = rng.between(0.0, 1.0); let u2 = rng.between(0.0, 1.0); let (z1, z2) = Self::box_muller_transform(u1, u2); self.next_number = Some(z2); z1 } } #[cfg(test)] mod tests { use super::*; #[test] fn mersenne_twister_test() -> Result<()> { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); let data = std::fs::read_to_string(project_path!("testdata/mt19937.txt"))?; for (i, line) in data.lines().enumerate() { let expected = line.parse::<u32>()?; assert_eq!(rng.next_u32(),
{ Self { w: 32, n: 624, m: 397, r: 31, a: 0x9908B0DF, u: 11, d: 0xffffffff, s: 7, b: 0x9D2C5680, t: 15, c: 0xEFC60000, l: 18, f: 1812433253, x: vec![], index: 0, }
identifier_body
random.rs
} let mut buf = vec![]; buf.resize(upper.byte_width(), 0); let mut num_bytes = ceil_div(upper.value_bits(), 8); let msb_mask: u8 = { let r = upper.value_bits() % 8; if r == 0 { 0xff } else { !((1 << (8 - r)) - 1) } }; // TODO: Refactor out retrying. Instead shift to 0 loop { secure_random_bytes(&mut buf[0..num_bytes]).await?; buf[num_bytes - 1] &= msb_mask; let n = SecureBigUint::from_le_bytes(&buf); // TODO: This *must* be a secure comparison (which it isn't right now). if &n >= lower && &n < upper { return Ok(n); } } } pub trait Rng { fn seed_size(&self) -> usize; fn seed(&mut self, new_seed: &[u8]); fn generate_bytes(&mut self, output: &mut [u8]); } #[async_trait] pub trait SharedRng:'static + Send + Sync { /// Number of bytes used to seed this RNG. fn seed_size(&self) -> usize; /// Should reset the state of the RNG based on the provided seed. /// Calling generate_bytes after calling reseed with the same seed should /// always produce the same result. async fn seed(&self, new_seed: &[u8]); async fn generate_bytes(&self, output: &mut [u8]); } #[derive(Clone)] pub struct GlobalRng { state: Arc<GlobalRngState>, } struct GlobalRngState { bytes_since_reseed: Mutex<usize>, rng: ChaCha20RNG, } impl GlobalRng { fn new() -> Self { Self { state: Arc::new(GlobalRngState { bytes_since_reseed: Mutex::new(std::usize::MAX), rng: ChaCha20RNG::new(), }), } } } #[async_trait] impl SharedRng for GlobalRng { fn seed_size(&self) -> usize { 0 } async fn seed(&self, _new_seed: &[u8]) { // Global RNG can't be manually reseeding panic!(); } async fn generate_bytes(&self, output: &mut [u8]) { { let mut counter = self.state.bytes_since_reseed.lock().await; if *counter > MAX_BYTES_BEFORE_RESEED { let mut new_seed = vec![0u8; self.state.rng.seed_size()]; secure_random_bytes(&mut new_seed).await.unwrap(); self.state.rng.seed(&new_seed).await; *counter = 0; } // NOTE: For now we ignore the case of a user requesting a quantity that // partially exceeds our max threshold. *counter += output.len(); } self.state.rng.generate_bytes(output).await } } #[async_trait] impl<R: Rng + Send +?Sized +'static> SharedRng for Mutex<R> { fn seed_size(&self) -> usize { todo!() // self.lock().await.seed_size() } async fn seed(&self, new_seed: &[u8]) { self.lock().await.seed(new_seed) } async fn generate_bytes(&self, output: &mut [u8]) { self.lock().await.generate_bytes(output) } } /// Sample random number generator based on ChaCha20 /// /// - During initialization and periodically afterwards, we (re-)generate the /// 256-bit key from a 'true random' source (/dev/random). /// - When a key is selected, we reset the nonce to 0. /// - The nonce is incremented by 1 for each block we encrypt. /// - The plaintext to be encrypted is the system time at key creation in /// nanoseconds. /// - All of the above are re-seeding in the background every 30 seconds. /// - Random bytes are generated by encrypting the plaintext with the current /// nonce and key. pub struct ChaCha20RNG { state: Mutex<ChaCha20RNGState>, } #[derive(Clone)] struct ChaCha20RNGState { key: [u8; CHACHA20_KEY_SIZE], nonce: u64, plaintext: [u8; CHACHA20_BLOCK_SIZE], } impl ChaCha20RNG { /// Creates a new instance of the rng with a fixed 'zero' seed. pub fn new() -> Self { Self { state: Mutex::new(ChaCha20RNGState { key: [0u8; CHACHA20_KEY_SIZE], nonce: 0, plaintext: [0u8; CHACHA20_BLOCK_SIZE], }), } } } #[async_trait] impl SharedRng for ChaCha20RNG { fn seed_size(&self) -> usize { CHACHA20_KEY_SIZE + CHACHA20_BLOCK_SIZE } async fn seed(&self, new_seed: &[u8]) { let mut state = self.state.lock().await; state.nonce = 0; state.key.copy_from_slice(&new_seed[0..CHACHA20_KEY_SIZE]); state .plaintext .copy_from_slice(&new_seed[CHACHA20_KEY_SIZE..]); } async fn generate_bytes(&self, mut output: &mut [u8]) { let state = { let mut guard = self.state.lock().await; let cur_state = guard.clone(); guard.nonce += 1; cur_state }; let mut nonce = [0u8; CHACHA20_NONCE_SIZE]; nonce[0..8].copy_from_slice(&state.nonce.to_ne_bytes()); let mut chacha = ChaCha20::new(&state.key, &nonce); while!output.is_empty() { let mut output_block = [0u8; CHACHA20_BLOCK_SIZE]; chacha.encrypt(&state.plaintext, &mut output_block); let n = std::cmp::min(output_block.len(), output.len()); output[0..n].copy_from_slice(&output_block[0..n]); output = &mut output[n..]; } } } #[async_trait] pub trait SharedRngExt { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]); async fn uniform<T: RngNumber>(&self) -> T; async fn between<T: RngNumber>(&self, min: T, max: T) -> T; } #[async_trait] impl<R: SharedRng +?Sized> SharedRngExt for Arc<R> { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { self.as_ref().shuffle(elements).await } async fn uniform<T: RngNumber>(&self) -> T { self.as_ref().uniform().await } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { self.as_ref().between(min, max).await } } #[async_trait] impl<R: SharedRng +?Sized> SharedRngExt for R { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>().await % elements.len(); elements.swap(i, j); } } async fn uniform<T: RngNumber>(&self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::uniform_buffer(buf) } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::between_buffer(buf, min, max) } } pub trait RngNumber: Send + Sync +'static { type Buffer: Send + Sync + Sized + Default + AsMut<[u8]>; fn uniform_buffer(random: Self::Buffer) -> Self; fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self; } macro_rules! ensure_positive { ($value:ident, I) => { if $value < 0 { $value * -1 } else { $value } }; ($value:ident, U) => { $value }; } macro_rules! impl_rng_number_integer { ($num:ident, $type_prefix:ident) => { impl RngNumber for $num { type Buffer = [u8; std::mem::size_of::<$num>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = Self::uniform_buffer(random); // In rust (negative_number % positive_number) = negative_number num = ensure_positive!(num, $type_prefix); // Convert to [0, range) let range = max - min; num = num % range; // Convert to [min, max) num += min; num } } }; } impl_rng_number_integer!(u8, U); impl_rng_number_integer!(i8, I); impl_rng_number_integer!(u16, U); impl_rng_number_integer!(i16, I); impl_rng_number_integer!(u32, U); impl_rng_number_integer!(i32, I); impl_rng_number_integer!(u64, U); impl_rng_number_integer!(i64, I); impl_rng_number_integer!(usize, U); impl_rng_number_integer!(isize, I); macro_rules! impl_rng_number_float { ($float_type:ident, $int_type:ident, $fraction_bits:expr, $zero_exponent:expr) => { impl RngNumber for $float_type { type Buffer = [u8; std::mem::size_of::<$float_type>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(mut random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = $int_type::from_le_bytes(random); // Clear the sign and exponent bits. num &= (1 << $fraction_bits) - 1; // Set the exponent to '0'. So the number will be (1 + fraction) * 2^0 num |= $zero_exponent << $fraction_bits; random = num.to_le_bytes(); // This will in the range [0, 1). let f = Self::from_le_bytes(random) - 1.0; // Convert to [min, max). let range = max - min; f * range + min } } }; } impl_rng_number_float!(f32, u32, 23, 127); impl_rng_number_float!(f64, u64, 52, 1023); pub trait RngExt { fn shuffle<T>(&mut self, elements: &mut [T]); fn uniform<T: RngNumber>(&mut self) -> T; fn between<T: RngNumber>(&mut self, min: T, max: T) -> T; fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T; } impl<R: Rng +?Sized> RngExt for R { fn shuffle<T>(&mut self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>() % elements.len(); elements.swap(i, j); } } /// Returns a completely random number anywhere in the range of the number /// type. Every number is equally probably of occuring. fn uniform<T: RngNumber>(&mut self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::uniform_buffer(buf) } /// Returns a uniform random number in the range [min, max). /// /// Limitations: /// -'max' must be >='min'. /// - For signed integer types for N bits,'max' -'min' must fit in N-1 /// bits. fn between<T: RngNumber>(&mut self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::between_buffer(buf, min, max) } fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T { assert!(!elements.is_empty(), "Choosing from empty list"); let n = self.uniform::<usize>(); &elements[n % elements.len()] } } pub const MT_DEFAULT_SEED: u32 = 5489; pub struct MersenneTwisterRng { w: u32, n: usize, m: usize, r: u32, a: u32, // b: u32, c: u32, s: u32, t: u32, u: u32, d: u32, l: u32, f: u32, x: Vec<u32>, index: usize, } impl MersenneTwisterRng { // TODO: Add a simple time seeded implementation. pub fn mt19937() -> Self { Self { w: 32, n: 624, m: 397, r: 31, a: 0x9908B0DF, u: 11, d: 0xffffffff, s: 7, b: 0x9D2C5680, t: 15, c: 0xEFC60000, l: 18, f: 1812433253, x: vec![], index: 0, } } pub fn seed_u32(&mut self, seed: u32) { self.x.resize(self.n, 0); self.index = self.n; self.x[0] = seed; for i in 1..self.n { self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2))) .wrapping_mul(self.f) .wrapping_add(i as u32); } } pub fn next_u32(&mut self) -> u32 { if self.x.is_empty() { self.seed_u32(MT_DEFAULT_SEED); } if self.index >= self.n { self.twist(); } let mut y = self.x[self.index]; y ^= (y >> self.u) & self.d; y ^= (y << self.s) & self.b; y ^= (y << self.t) & self.c; y ^= y >> self.l; self.index += 1; y } fn twist(&mut self) { let w_mask = 1u32.checked_shl(self.w).unwrap_or(0).wrapping_sub(1); let upper_mask = (w_mask << self.r) & w_mask; let lower_mask = (!upper_mask) & w_mask; self.index = 0; for i in 0..self.n { let x = (self.x[i] & upper_mask) | (self.x[(i + 1) % self.x.len()] & lower_mask); let mut x_a = x >> 1; if x & 1!= 0 { x_a = x_a ^ self.a; } self.x[i] = self.x[(i + self.m) % self.x.len()] ^ x_a; } } } impl Rng for MersenneTwisterRng { fn seed_size(&self) -> usize { std::mem::size_of::<u32>() } fn seed(&mut self, new_seed: &[u8]) { assert_eq!(new_seed.len(), std::mem::size_of::<u32>()); let seed_num = u32::from_le_bytes(*array_ref![new_seed, 0, 4]); self.seed_u32(seed_num); } fn generate_bytes(&mut self, output: &mut [u8]) { // NOTE: All of the 4's in here are std::mem::size_of::<u32>() let n = output.len() / 4; let r = output.len() % 4; for i in 0..n { *array_mut_ref![output, 4 * i, 4] = self.next_u32().to_le_bytes(); } if r!= 0 { let v = self.next_u32().to_le_bytes(); let i = output.len() - r; output[i..].copy_from_slice(&v[0..r]); } } } pub struct FixedBytesRng { data: Bytes, } impl FixedBytesRng { pub fn new<T: Into<Bytes>>(data: T) -> Self { Self { data: data.into() } } } impl Rng for FixedBytesRng { fn seed_size(&self) -> usize { panic!(); } fn seed(&mut self, _new_seed: &[u8]) { panic!(); } fn generate_bytes(&mut self, output: &mut [u8]) { if output.len() > self.data.len() { panic!(); } output.copy_from_slice(&self.data[0..output.len()]); self.data.advance(output.len()); } } pub struct NormalDistribution { mean: f64, stddev: f64, next_number: Option<f64>, } impl NormalDistribution { pub fn new(mean: f64, stddev: f64) -> Self { Self { mean, stddev, next_number: None, } } /// Given two uniformly sampled random numbers in the range [0, 1], computes /// two independent random values with a normal/gaussian distribution /// with mean of 0 and standard deviation of 1. /// See https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform fn box_muller_transform(u1: f64, u2: f64) -> (f64, f64) { let theta = 2.0 * PI * u2; let (sin, cos) = theta.sin_cos(); let r = (-2.0 * u1.ln()).sqrt(); (r * sin, r * cos) } } pub trait NormalDistributionRngExt { fn next(&mut self, rng: &mut dyn Rng) -> f64; } impl NormalDistributionRngExt for NormalDistribution { fn next(&mut self, rng: &mut dyn Rng) -> f64 { if let Some(v) = self.next_number.take() { return v; } let u1 = rng.between(0.0, 1.0); let u2 = rng.between(0.0, 1.0); let (z1, z2) = Self::box_muller_transform(u1, u2); self.next_number = Some(z2); z1 } } #[cfg(test)] mod tests { use super::*; #[test] fn mersenne_twister_test() -> Result<()> { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); let data = std::fs::read_to_string(project_path!("testdata/mt19937.txt"))?; for (i, line) in data.lines().enumerate() { let expected = line.parse::<u32>()?; assert_eq!(rng.next_u32(), expected, "Mismatch at index {}", i); } Ok(()) } #[test] fn between_inclusive_test() { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); for _ in 0..100 { let f = rng.between::<f32>(0.0, 1.0); assert!(f >= 0.0 && f < 1.0); } for _ in 0..100 { let f = rng.between::<f64>(0.0, 0.25); assert!(f >= 0.0 && f < 0.25); } let min = 427; let max = 674; let num_iter = 20000000; let mut buckets = [0usize; 247]; for _ in 0..num_iter { let n = rng.between::<i32>(min, max); assert!(n >= min && n < max); buckets[(n - min) as usize] += 1; } for bucket in buckets { // Ideal value is num_iter / range = ~80971 // We'll accept a 1% deviation.
assert!(bucket > 71254 && bucket < 81780, "Bucket is {}", bucket);
random_line_split
random.rs
/// /// TODO: We should disallow re-seeding this RNG. pub fn global_rng() -> GlobalRng { GLOBAL_RNG_STATE.clone() } /// Call me if you want a cheap but insecure RNG seeded by the current system /// time. pub fn clocked_rng() -> MersenneTwisterRng { let mut rng = MersenneTwisterRng::mt19937(); let seed = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .subsec_nanos(); rng.seed_u32(seed); rng } /// Generates secure random bytes suitable for cryptographic key generation. /// This will wait for sufficient entropy to accumulate in the system. /// /// Once done, the provided buffer will be filled with the random bytes to the /// end. pub async fn secure_random_bytes(buf: &mut [u8]) -> Result<()> { // See http://man7.org/linux/man-pages/man7/random.7.html // TODO: Reuse the file handle across calls. let mut f = LocalFile::open("/dev/random")?; f.read_exact(buf).await?; Ok(()) } /// Securely generates a random value in the range '[lower, upper)'. /// /// This is implemented to give every integer in the range the same probabiity /// of being output. /// /// NOTE: Both the 'lower' and 'upper' numbers should be publicly known for this /// to be secure. /// /// The output integer will have the same width as the 'upper' integer. pub async fn secure_random_range( lower: &SecureBigUint, upper: &SecureBigUint, ) -> Result<SecureBigUint> { if upper.byte_width() == 0 || upper <= lower { return Err(err_msg("Invalid upper/lower range")); } let mut buf = vec![]; buf.resize(upper.byte_width(), 0); let mut num_bytes = ceil_div(upper.value_bits(), 8); let msb_mask: u8 = { let r = upper.value_bits() % 8; if r == 0 { 0xff } else { !((1 << (8 - r)) - 1) } }; // TODO: Refactor out retrying. Instead shift to 0 loop { secure_random_bytes(&mut buf[0..num_bytes]).await?; buf[num_bytes - 1] &= msb_mask; let n = SecureBigUint::from_le_bytes(&buf); // TODO: This *must* be a secure comparison (which it isn't right now). if &n >= lower && &n < upper { return Ok(n); } } } pub trait Rng { fn seed_size(&self) -> usize; fn seed(&mut self, new_seed: &[u8]); fn generate_bytes(&mut self, output: &mut [u8]); } #[async_trait] pub trait SharedRng:'static + Send + Sync { /// Number of bytes used to seed this RNG. fn seed_size(&self) -> usize; /// Should reset the state of the RNG based on the provided seed. /// Calling generate_bytes after calling reseed with the same seed should /// always produce the same result. async fn seed(&self, new_seed: &[u8]); async fn generate_bytes(&self, output: &mut [u8]); } #[derive(Clone)] pub struct GlobalRng { state: Arc<GlobalRngState>, } struct GlobalRngState { bytes_since_reseed: Mutex<usize>, rng: ChaCha20RNG, } impl GlobalRng { fn new() -> Self { Self { state: Arc::new(GlobalRngState { bytes_since_reseed: Mutex::new(std::usize::MAX), rng: ChaCha20RNG::new(), }), } } } #[async_trait] impl SharedRng for GlobalRng { fn seed_size(&self) -> usize { 0 } async fn seed(&self, _new_seed: &[u8]) { // Global RNG can't be manually reseeding panic!(); } async fn generate_bytes(&self, output: &mut [u8]) { { let mut counter = self.state.bytes_since_reseed.lock().await; if *counter > MAX_BYTES_BEFORE_RESEED { let mut new_seed = vec![0u8; self.state.rng.seed_size()]; secure_random_bytes(&mut new_seed).await.unwrap(); self.state.rng.seed(&new_seed).await; *counter = 0; } // NOTE: For now we ignore the case of a user requesting a quantity that // partially exceeds our max threshold. *counter += output.len(); } self.state.rng.generate_bytes(output).await } } #[async_trait] impl<R: Rng + Send +?Sized +'static> SharedRng for Mutex<R> { fn seed_size(&self) -> usize { todo!() // self.lock().await.seed_size() } async fn seed(&self, new_seed: &[u8]) { self.lock().await.seed(new_seed) } async fn generate_bytes(&self, output: &mut [u8]) { self.lock().await.generate_bytes(output) } } /// Sample random number generator based on ChaCha20 /// /// - During initialization and periodically afterwards, we (re-)generate the /// 256-bit key from a 'true random' source (/dev/random). /// - When a key is selected, we reset the nonce to 0. /// - The nonce is incremented by 1 for each block we encrypt. /// - The plaintext to be encrypted is the system time at key creation in /// nanoseconds. /// - All of the above are re-seeding in the background every 30 seconds. /// - Random bytes are generated by encrypting the plaintext with the current /// nonce and key. pub struct ChaCha20RNG { state: Mutex<ChaCha20RNGState>, } #[derive(Clone)] struct ChaCha20RNGState { key: [u8; CHACHA20_KEY_SIZE], nonce: u64, plaintext: [u8; CHACHA20_BLOCK_SIZE], } impl ChaCha20RNG { /// Creates a new instance of the rng with a fixed 'zero' seed. pub fn
() -> Self { Self { state: Mutex::new(ChaCha20RNGState { key: [0u8; CHACHA20_KEY_SIZE], nonce: 0, plaintext: [0u8; CHACHA20_BLOCK_SIZE], }), } } } #[async_trait] impl SharedRng for ChaCha20RNG { fn seed_size(&self) -> usize { CHACHA20_KEY_SIZE + CHACHA20_BLOCK_SIZE } async fn seed(&self, new_seed: &[u8]) { let mut state = self.state.lock().await; state.nonce = 0; state.key.copy_from_slice(&new_seed[0..CHACHA20_KEY_SIZE]); state .plaintext .copy_from_slice(&new_seed[CHACHA20_KEY_SIZE..]); } async fn generate_bytes(&self, mut output: &mut [u8]) { let state = { let mut guard = self.state.lock().await; let cur_state = guard.clone(); guard.nonce += 1; cur_state }; let mut nonce = [0u8; CHACHA20_NONCE_SIZE]; nonce[0..8].copy_from_slice(&state.nonce.to_ne_bytes()); let mut chacha = ChaCha20::new(&state.key, &nonce); while!output.is_empty() { let mut output_block = [0u8; CHACHA20_BLOCK_SIZE]; chacha.encrypt(&state.plaintext, &mut output_block); let n = std::cmp::min(output_block.len(), output.len()); output[0..n].copy_from_slice(&output_block[0..n]); output = &mut output[n..]; } } } #[async_trait] pub trait SharedRngExt { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]); async fn uniform<T: RngNumber>(&self) -> T; async fn between<T: RngNumber>(&self, min: T, max: T) -> T; } #[async_trait] impl<R: SharedRng +?Sized> SharedRngExt for Arc<R> { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { self.as_ref().shuffle(elements).await } async fn uniform<T: RngNumber>(&self) -> T { self.as_ref().uniform().await } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { self.as_ref().between(min, max).await } } #[async_trait] impl<R: SharedRng +?Sized> SharedRngExt for R { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>().await % elements.len(); elements.swap(i, j); } } async fn uniform<T: RngNumber>(&self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::uniform_buffer(buf) } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::between_buffer(buf, min, max) } } pub trait RngNumber: Send + Sync +'static { type Buffer: Send + Sync + Sized + Default + AsMut<[u8]>; fn uniform_buffer(random: Self::Buffer) -> Self; fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self; } macro_rules! ensure_positive { ($value:ident, I) => { if $value < 0 { $value * -1 } else { $value } }; ($value:ident, U) => { $value }; } macro_rules! impl_rng_number_integer { ($num:ident, $type_prefix:ident) => { impl RngNumber for $num { type Buffer = [u8; std::mem::size_of::<$num>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = Self::uniform_buffer(random); // In rust (negative_number % positive_number) = negative_number num = ensure_positive!(num, $type_prefix); // Convert to [0, range) let range = max - min; num = num % range; // Convert to [min, max) num += min; num } } }; } impl_rng_number_integer!(u8, U); impl_rng_number_integer!(i8, I); impl_rng_number_integer!(u16, U); impl_rng_number_integer!(i16, I); impl_rng_number_integer!(u32, U); impl_rng_number_integer!(i32, I); impl_rng_number_integer!(u64, U); impl_rng_number_integer!(i64, I); impl_rng_number_integer!(usize, U); impl_rng_number_integer!(isize, I); macro_rules! impl_rng_number_float { ($float_type:ident, $int_type:ident, $fraction_bits:expr, $zero_exponent:expr) => { impl RngNumber for $float_type { type Buffer = [u8; std::mem::size_of::<$float_type>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(mut random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = $int_type::from_le_bytes(random); // Clear the sign and exponent bits. num &= (1 << $fraction_bits) - 1; // Set the exponent to '0'. So the number will be (1 + fraction) * 2^0 num |= $zero_exponent << $fraction_bits; random = num.to_le_bytes(); // This will in the range [0, 1). let f = Self::from_le_bytes(random) - 1.0; // Convert to [min, max). let range = max - min; f * range + min } } }; } impl_rng_number_float!(f32, u32, 23, 127); impl_rng_number_float!(f64, u64, 52, 1023); pub trait RngExt { fn shuffle<T>(&mut self, elements: &mut [T]); fn uniform<T: RngNumber>(&mut self) -> T; fn between<T: RngNumber>(&mut self, min: T, max: T) -> T; fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T; } impl<R: Rng +?Sized> RngExt for R { fn shuffle<T>(&mut self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>() % elements.len(); elements.swap(i, j); } } /// Returns a completely random number anywhere in the range of the number /// type. Every number is equally probably of occuring. fn uniform<T: RngNumber>(&mut self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::uniform_buffer(buf) } /// Returns a uniform random number in the range [min, max). /// /// Limitations: /// -'max' must be >='min'. /// - For signed integer types for N bits,'max' -'min' must fit in N-1 /// bits. fn between<T: RngNumber>(&mut self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::between_buffer(buf, min, max) } fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T { assert!(!elements.is_empty(), "Choosing from empty list"); let n = self.uniform::<usize>(); &elements[n % elements.len()] } } pub const MT_DEFAULT_SEED: u32 = 5489; pub struct MersenneTwisterRng { w: u32, n: usize, m: usize, r: u32, a: u32, // b: u32, c: u32, s: u32, t: u32, u: u32, d: u32, l: u32, f: u32, x: Vec<u32>, index: usize, } impl MersenneTwisterRng { // TODO: Add a simple time seeded implementation. pub fn mt19937() -> Self { Self { w: 32, n: 624, m: 397, r: 31, a: 0x9908B0DF, u: 11, d: 0xffffffff, s: 7, b: 0x9D2C5680, t: 15, c: 0xEFC60000, l: 18, f: 1812433253, x: vec![], index: 0, } } pub fn seed_u32(&mut self, seed: u32) { self.x.resize(self.n, 0); self.index = self.n; self.x[0] = seed; for i in 1..self.n { self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2))) .wrapping_mul(self.f) .wrapping_add(i as u32); } } pub fn next_u32(&mut self) -> u32 { if self.x.is_empty() { self.seed_u32(MT_DEFAULT_SEED); } if self.index >= self.n { self.twist(); } let mut y = self.x[self.index]; y ^= (y >> self.u) & self.d; y ^= (y << self.s) & self.b; y ^= (y << self.t) & self.c; y ^= y >> self.l; self.index += 1; y } fn twist(&mut self) { let w_mask = 1u32.checked_shl(self.w).unwrap_or(0).wrapping_sub(1); let upper_mask = (w_mask << self.r) & w_mask; let lower_mask = (!upper_mask) & w_mask; self.index = 0; for i in 0..self.n { let x = (self.x[i] & upper_mask) | (self.x[(i + 1) % self.x.len()] & lower_mask); let mut x_a = x >> 1; if x & 1!= 0 { x_a = x_a ^ self.a; } self.x[i] = self.x[(i + self.m) % self.x.len()] ^ x_a; } } } impl Rng for MersenneTwisterRng { fn seed_size(&self) -> usize { std::mem::size_of::<u32>() } fn seed(&mut self, new_seed: &[u8]) { assert_eq!(new_seed.len(), std::mem::size_of::<u32>()); let seed_num = u32::from_le_bytes(*array_ref![new_seed, 0, 4]); self.seed_u32(seed_num); } fn generate_bytes(&mut self, output: &mut [u8]) { // NOTE: All of the 4's in here are std::mem::size_of::<u32>() let n = output.len() / 4; let r = output.len() % 4; for i in 0..n { *array_mut_ref![output, 4 * i, 4] = self.next_u32().to_le_bytes(); } if r!= 0 { let v = self.next_u32().to_le_bytes(); let i = output.len() - r; output[i..].copy_from_slice(&v[0..r]); } } } pub struct FixedBytesRng { data: Bytes, } impl FixedBytesRng { pub fn new<T: Into<Bytes>>(data: T) -> Self { Self { data: data.into() } } } impl Rng for FixedBytesRng { fn seed_size(&self) -> usize { panic!(); } fn seed(&mut self, _new_seed: &[u8]) { panic!(); } fn generate_bytes(&mut self, output: &mut [u8]) { if output.len() > self.data.len() { panic!(); } output.copy_from_slice(&self.data[0..output.len()]); self.data.advance(output.len()); } } pub struct NormalDistribution { mean: f64, stddev: f64, next_number: Option<f64>, } impl NormalDistribution { pub fn new(mean: f64, stddev: f64) -> Self { Self { mean, stddev, next_number: None, } } /// Given two uniformly sampled random numbers in the range [0, 1], computes /// two independent random values with a normal/gaussian distribution /// with mean of 0 and standard deviation of 1. /// See https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform fn box_muller_transform(u1: f64, u2: f64) -> (f64, f64) { let theta = 2.0 * PI * u2; let (sin, cos) = theta.sin_cos(); let r = (-2.0 * u1.ln()).sqrt(); (r * sin, r * cos) } } pub trait NormalDistributionRngExt { fn next(&mut self, rng: &mut dyn Rng) -> f64; } impl NormalDistributionRngExt for NormalDistribution { fn next(&mut self, rng: &mut dyn Rng) -> f64 { if let Some(v) = self.next_number.take() { return v; } let u1 = rng.between(0.0, 1.0); let u2 = rng.between(0.0, 1.0); let (z1, z2) = Self::box_muller_transform(u1, u2); self.next_number = Some(z2); z1 } } #[cfg(test)] mod tests { use super::*; #[test] fn mersenne_twister_test() -> Result<()> { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); let data = std::fs::read_to_string(project_path!("testdata/mt19937.txt"))?; for (i, line) in data.lines().enumerate() { let expected = line.parse::<u32>()?; assert_eq!(rng.next_u32(),
new
identifier_name
random.rs
/// /// TODO: We should disallow re-seeding this RNG. pub fn global_rng() -> GlobalRng { GLOBAL_RNG_STATE.clone() } /// Call me if you want a cheap but insecure RNG seeded by the current system /// time. pub fn clocked_rng() -> MersenneTwisterRng { let mut rng = MersenneTwisterRng::mt19937(); let seed = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .subsec_nanos(); rng.seed_u32(seed); rng } /// Generates secure random bytes suitable for cryptographic key generation. /// This will wait for sufficient entropy to accumulate in the system. /// /// Once done, the provided buffer will be filled with the random bytes to the /// end. pub async fn secure_random_bytes(buf: &mut [u8]) -> Result<()> { // See http://man7.org/linux/man-pages/man7/random.7.html // TODO: Reuse the file handle across calls. let mut f = LocalFile::open("/dev/random")?; f.read_exact(buf).await?; Ok(()) } /// Securely generates a random value in the range '[lower, upper)'. /// /// This is implemented to give every integer in the range the same probabiity /// of being output. /// /// NOTE: Both the 'lower' and 'upper' numbers should be publicly known for this /// to be secure. /// /// The output integer will have the same width as the 'upper' integer. pub async fn secure_random_range( lower: &SecureBigUint, upper: &SecureBigUint, ) -> Result<SecureBigUint> { if upper.byte_width() == 0 || upper <= lower
let mut buf = vec![]; buf.resize(upper.byte_width(), 0); let mut num_bytes = ceil_div(upper.value_bits(), 8); let msb_mask: u8 = { let r = upper.value_bits() % 8; if r == 0 { 0xff } else { !((1 << (8 - r)) - 1) } }; // TODO: Refactor out retrying. Instead shift to 0 loop { secure_random_bytes(&mut buf[0..num_bytes]).await?; buf[num_bytes - 1] &= msb_mask; let n = SecureBigUint::from_le_bytes(&buf); // TODO: This *must* be a secure comparison (which it isn't right now). if &n >= lower && &n < upper { return Ok(n); } } } pub trait Rng { fn seed_size(&self) -> usize; fn seed(&mut self, new_seed: &[u8]); fn generate_bytes(&mut self, output: &mut [u8]); } #[async_trait] pub trait SharedRng:'static + Send + Sync { /// Number of bytes used to seed this RNG. fn seed_size(&self) -> usize; /// Should reset the state of the RNG based on the provided seed. /// Calling generate_bytes after calling reseed with the same seed should /// always produce the same result. async fn seed(&self, new_seed: &[u8]); async fn generate_bytes(&self, output: &mut [u8]); } #[derive(Clone)] pub struct GlobalRng { state: Arc<GlobalRngState>, } struct GlobalRngState { bytes_since_reseed: Mutex<usize>, rng: ChaCha20RNG, } impl GlobalRng { fn new() -> Self { Self { state: Arc::new(GlobalRngState { bytes_since_reseed: Mutex::new(std::usize::MAX), rng: ChaCha20RNG::new(), }), } } } #[async_trait] impl SharedRng for GlobalRng { fn seed_size(&self) -> usize { 0 } async fn seed(&self, _new_seed: &[u8]) { // Global RNG can't be manually reseeding panic!(); } async fn generate_bytes(&self, output: &mut [u8]) { { let mut counter = self.state.bytes_since_reseed.lock().await; if *counter > MAX_BYTES_BEFORE_RESEED { let mut new_seed = vec![0u8; self.state.rng.seed_size()]; secure_random_bytes(&mut new_seed).await.unwrap(); self.state.rng.seed(&new_seed).await; *counter = 0; } // NOTE: For now we ignore the case of a user requesting a quantity that // partially exceeds our max threshold. *counter += output.len(); } self.state.rng.generate_bytes(output).await } } #[async_trait] impl<R: Rng + Send +?Sized +'static> SharedRng for Mutex<R> { fn seed_size(&self) -> usize { todo!() // self.lock().await.seed_size() } async fn seed(&self, new_seed: &[u8]) { self.lock().await.seed(new_seed) } async fn generate_bytes(&self, output: &mut [u8]) { self.lock().await.generate_bytes(output) } } /// Sample random number generator based on ChaCha20 /// /// - During initialization and periodically afterwards, we (re-)generate the /// 256-bit key from a 'true random' source (/dev/random). /// - When a key is selected, we reset the nonce to 0. /// - The nonce is incremented by 1 for each block we encrypt. /// - The plaintext to be encrypted is the system time at key creation in /// nanoseconds. /// - All of the above are re-seeding in the background every 30 seconds. /// - Random bytes are generated by encrypting the plaintext with the current /// nonce and key. pub struct ChaCha20RNG { state: Mutex<ChaCha20RNGState>, } #[derive(Clone)] struct ChaCha20RNGState { key: [u8; CHACHA20_KEY_SIZE], nonce: u64, plaintext: [u8; CHACHA20_BLOCK_SIZE], } impl ChaCha20RNG { /// Creates a new instance of the rng with a fixed 'zero' seed. pub fn new() -> Self { Self { state: Mutex::new(ChaCha20RNGState { key: [0u8; CHACHA20_KEY_SIZE], nonce: 0, plaintext: [0u8; CHACHA20_BLOCK_SIZE], }), } } } #[async_trait] impl SharedRng for ChaCha20RNG { fn seed_size(&self) -> usize { CHACHA20_KEY_SIZE + CHACHA20_BLOCK_SIZE } async fn seed(&self, new_seed: &[u8]) { let mut state = self.state.lock().await; state.nonce = 0; state.key.copy_from_slice(&new_seed[0..CHACHA20_KEY_SIZE]); state .plaintext .copy_from_slice(&new_seed[CHACHA20_KEY_SIZE..]); } async fn generate_bytes(&self, mut output: &mut [u8]) { let state = { let mut guard = self.state.lock().await; let cur_state = guard.clone(); guard.nonce += 1; cur_state }; let mut nonce = [0u8; CHACHA20_NONCE_SIZE]; nonce[0..8].copy_from_slice(&state.nonce.to_ne_bytes()); let mut chacha = ChaCha20::new(&state.key, &nonce); while!output.is_empty() { let mut output_block = [0u8; CHACHA20_BLOCK_SIZE]; chacha.encrypt(&state.plaintext, &mut output_block); let n = std::cmp::min(output_block.len(), output.len()); output[0..n].copy_from_slice(&output_block[0..n]); output = &mut output[n..]; } } } #[async_trait] pub trait SharedRngExt { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]); async fn uniform<T: RngNumber>(&self) -> T; async fn between<T: RngNumber>(&self, min: T, max: T) -> T; } #[async_trait] impl<R: SharedRng +?Sized> SharedRngExt for Arc<R> { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { self.as_ref().shuffle(elements).await } async fn uniform<T: RngNumber>(&self) -> T { self.as_ref().uniform().await } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { self.as_ref().between(min, max).await } } #[async_trait] impl<R: SharedRng +?Sized> SharedRngExt for R { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>().await % elements.len(); elements.swap(i, j); } } async fn uniform<T: RngNumber>(&self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::uniform_buffer(buf) } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::between_buffer(buf, min, max) } } pub trait RngNumber: Send + Sync +'static { type Buffer: Send + Sync + Sized + Default + AsMut<[u8]>; fn uniform_buffer(random: Self::Buffer) -> Self; fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self; } macro_rules! ensure_positive { ($value:ident, I) => { if $value < 0 { $value * -1 } else { $value } }; ($value:ident, U) => { $value }; } macro_rules! impl_rng_number_integer { ($num:ident, $type_prefix:ident) => { impl RngNumber for $num { type Buffer = [u8; std::mem::size_of::<$num>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = Self::uniform_buffer(random); // In rust (negative_number % positive_number) = negative_number num = ensure_positive!(num, $type_prefix); // Convert to [0, range) let range = max - min; num = num % range; // Convert to [min, max) num += min; num } } }; } impl_rng_number_integer!(u8, U); impl_rng_number_integer!(i8, I); impl_rng_number_integer!(u16, U); impl_rng_number_integer!(i16, I); impl_rng_number_integer!(u32, U); impl_rng_number_integer!(i32, I); impl_rng_number_integer!(u64, U); impl_rng_number_integer!(i64, I); impl_rng_number_integer!(usize, U); impl_rng_number_integer!(isize, I); macro_rules! impl_rng_number_float { ($float_type:ident, $int_type:ident, $fraction_bits:expr, $zero_exponent:expr) => { impl RngNumber for $float_type { type Buffer = [u8; std::mem::size_of::<$float_type>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(mut random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = $int_type::from_le_bytes(random); // Clear the sign and exponent bits. num &= (1 << $fraction_bits) - 1; // Set the exponent to '0'. So the number will be (1 + fraction) * 2^0 num |= $zero_exponent << $fraction_bits; random = num.to_le_bytes(); // This will in the range [0, 1). let f = Self::from_le_bytes(random) - 1.0; // Convert to [min, max). let range = max - min; f * range + min } } }; } impl_rng_number_float!(f32, u32, 23, 127); impl_rng_number_float!(f64, u64, 52, 1023); pub trait RngExt { fn shuffle<T>(&mut self, elements: &mut [T]); fn uniform<T: RngNumber>(&mut self) -> T; fn between<T: RngNumber>(&mut self, min: T, max: T) -> T; fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T; } impl<R: Rng +?Sized> RngExt for R { fn shuffle<T>(&mut self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>() % elements.len(); elements.swap(i, j); } } /// Returns a completely random number anywhere in the range of the number /// type. Every number is equally probably of occuring. fn uniform<T: RngNumber>(&mut self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::uniform_buffer(buf) } /// Returns a uniform random number in the range [min, max). /// /// Limitations: /// -'max' must be >='min'. /// - For signed integer types for N bits,'max' -'min' must fit in N-1 /// bits. fn between<T: RngNumber>(&mut self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::between_buffer(buf, min, max) } fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T { assert!(!elements.is_empty(), "Choosing from empty list"); let n = self.uniform::<usize>(); &elements[n % elements.len()] } } pub const MT_DEFAULT_SEED: u32 = 5489; pub struct MersenneTwisterRng { w: u32, n: usize, m: usize, r: u32, a: u32, // b: u32, c: u32, s: u32, t: u32, u: u32, d: u32, l: u32, f: u32, x: Vec<u32>, index: usize, } impl MersenneTwisterRng { // TODO: Add a simple time seeded implementation. pub fn mt19937() -> Self { Self { w: 32, n: 624, m: 397, r: 31, a: 0x9908B0DF, u: 11, d: 0xffffffff, s: 7, b: 0x9D2C5680, t: 15, c: 0xEFC60000, l: 18, f: 1812433253, x: vec![], index: 0, } } pub fn seed_u32(&mut self, seed: u32) { self.x.resize(self.n, 0); self.index = self.n; self.x[0] = seed; for i in 1..self.n { self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2))) .wrapping_mul(self.f) .wrapping_add(i as u32); } } pub fn next_u32(&mut self) -> u32 { if self.x.is_empty() { self.seed_u32(MT_DEFAULT_SEED); } if self.index >= self.n { self.twist(); } let mut y = self.x[self.index]; y ^= (y >> self.u) & self.d; y ^= (y << self.s) & self.b; y ^= (y << self.t) & self.c; y ^= y >> self.l; self.index += 1; y } fn twist(&mut self) { let w_mask = 1u32.checked_shl(self.w).unwrap_or(0).wrapping_sub(1); let upper_mask = (w_mask << self.r) & w_mask; let lower_mask = (!upper_mask) & w_mask; self.index = 0; for i in 0..self.n { let x = (self.x[i] & upper_mask) | (self.x[(i + 1) % self.x.len()] & lower_mask); let mut x_a = x >> 1; if x & 1!= 0 { x_a = x_a ^ self.a; } self.x[i] = self.x[(i + self.m) % self.x.len()] ^ x_a; } } } impl Rng for MersenneTwisterRng { fn seed_size(&self) -> usize { std::mem::size_of::<u32>() } fn seed(&mut self, new_seed: &[u8]) { assert_eq!(new_seed.len(), std::mem::size_of::<u32>()); let seed_num = u32::from_le_bytes(*array_ref![new_seed, 0, 4]); self.seed_u32(seed_num); } fn generate_bytes(&mut self, output: &mut [u8]) { // NOTE: All of the 4's in here are std::mem::size_of::<u32>() let n = output.len() / 4; let r = output.len() % 4; for i in 0..n { *array_mut_ref![output, 4 * i, 4] = self.next_u32().to_le_bytes(); } if r!= 0 { let v = self.next_u32().to_le_bytes(); let i = output.len() - r; output[i..].copy_from_slice(&v[0..r]); } } } pub struct FixedBytesRng { data: Bytes, } impl FixedBytesRng { pub fn new<T: Into<Bytes>>(data: T) -> Self { Self { data: data.into() } } } impl Rng for FixedBytesRng { fn seed_size(&self) -> usize { panic!(); } fn seed(&mut self, _new_seed: &[u8]) { panic!(); } fn generate_bytes(&mut self, output: &mut [u8]) { if output.len() > self.data.len() { panic!(); } output.copy_from_slice(&self.data[0..output.len()]); self.data.advance(output.len()); } } pub struct NormalDistribution { mean: f64, stddev: f64, next_number: Option<f64>, } impl NormalDistribution { pub fn new(mean: f64, stddev: f64) -> Self { Self { mean, stddev, next_number: None, } } /// Given two uniformly sampled random numbers in the range [0, 1], computes /// two independent random values with a normal/gaussian distribution /// with mean of 0 and standard deviation of 1. /// See https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform fn box_muller_transform(u1: f64, u2: f64) -> (f64, f64) { let theta = 2.0 * PI * u2; let (sin, cos) = theta.sin_cos(); let r = (-2.0 * u1.ln()).sqrt(); (r * sin, r * cos) } } pub trait NormalDistributionRngExt { fn next(&mut self, rng: &mut dyn Rng) -> f64; } impl NormalDistributionRngExt for NormalDistribution { fn next(&mut self, rng: &mut dyn Rng) -> f64 { if let Some(v) = self.next_number.take() { return v; } let u1 = rng.between(0.0, 1.0); let u2 = rng.between(0.0, 1.0); let (z1, z2) = Self::box_muller_transform(u1, u2); self.next_number = Some(z2); z1 } } #[cfg(test)] mod tests { use super::*; #[test] fn mersenne_twister_test() -> Result<()> { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); let data = std::fs::read_to_string(project_path!("testdata/mt19937.txt"))?; for (i, line) in data.lines().enumerate() { let expected = line.parse::<u32>()?; assert_eq!(rng.next_u32(),
{ return Err(err_msg("Invalid upper/lower range")); }
conditional_block
main.rs
use futures_util::future::Either; use futures_util::stream::StreamExt; use std::collections::{BTreeMap, HashMap}; use std::io::{self}; use structopt::StructOpt; use termion::raw::IntoRawMode; use tokio::prelude::*; use tui::backend::Backend; use tui::backend::TermionBackend; use tui::layout::{Constraint, Direction, Layout}; use tui::style::{Color, Modifier, Style}; use tui::widgets::{Block, Borders, Paragraph, Text, Widget}; use tui::Terminal; const DRAW_EVERY: std::time::Duration = std::time::Duration::from_millis(200); const WINDOW: std::time::Duration = std::time::Duration::from_secs(10); #[derive(Debug, StructOpt)] /// A live profile visualizer. /// /// Pipe the output of the appropriate `bpftrace` command into this program, and enjoy. /// Happy profiling! struct Opt { /// Treat input as a replay of a trace and emulate time accordingly. #[structopt(long)] replay: bool, } #[derive(Debug, Default)] struct
{ window: BTreeMap<usize, String>, } fn main() -> Result<(), io::Error> { let opt = Opt::from_args(); if termion::is_tty(&io::stdin().lock()) { eprintln!("Don't type input to this program, that's silly."); return Ok(()); } let stdout = io::stdout().into_raw_mode()?; let backend = TermionBackend::new(stdout); let mut terminal = Terminal::new(backend)?; let mut tids = BTreeMap::new(); let mut inframe = None; let mut stack = String::new(); terminal.hide_cursor()?; terminal.clear()?; terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)) .render(&mut f, chunks[0]); })?; // a _super_ hacky way for us to get input from the TTY let tty = termion::get_tty()?; let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); std::thread::spawn(move || { use termion::input::TermRead; for key in tty.keys() { if let Err(_) = tx.send(key) { return; } } }); let mut rt = tokio::runtime::Runtime::new()?; rt.block_on(async move { let stdin = tokio::io::BufReader::new(tokio::io::stdin()); let lines = stdin.lines().map(Either::Left); let rx = rx.map(Either::Right); let mut input = futures_util::stream::select(lines, rx); let mut lastprint = 0; let mut lasttime = 0; while let Some(got) = input.next().await { match got { Either::Left(line) => { let line = line.unwrap(); if line.starts_with("Error") || line.starts_with("Attaching") { } else if!line.starts_with(' ') || line.is_empty() { if let Some((time, tid)) = inframe { // new frame starts, so finish the old one // skip empty stack frames if!stack.is_empty() { let nxt_stack = String::with_capacity(stack.capacity()); let mut stack = std::mem::replace(&mut stack, nxt_stack); // remove trailing ; let stackn = stack.len(); stack.truncate(stackn - 1); tids.entry(tid) .or_insert_with(Thread::default) .window .insert(time, stack); if opt.replay && lasttime!= 0 && time - lasttime > 1_000_000 { tokio::time::delay_for(std::time::Duration::from_nanos( (time - lasttime) as u64, )) .await; } lasttime = time; if std::time::Duration::from_nanos((time - lastprint) as u64) > DRAW_EVERY { draw(&mut terminal, &mut tids)?; lastprint = time; } } inframe = None; } if!line.is_empty() { // read time + tid let mut fields = line.split_whitespace(); let time = fields .next() .expect("no time given for frame") .parse::<usize>() .expect("invalid time"); let tid = fields .next() .expect("no tid given for frame") .parse::<usize>() .expect("invalid tid"); inframe = Some((time, tid)); } } else { assert!(inframe.is_some()); stack.push_str(line.trim()); stack.push(';'); } } Either::Right(key) => { let key = key?; if let termion::event::Key::Char('q') = key { break; } } } } terminal.clear()?; Ok(()) }) } fn draw<B: Backend>( terminal: &mut Terminal<B>, threads: &mut BTreeMap<usize, Thread>, ) -> Result<(), io::Error> { // keep our window relatively short let mut latest = 0; for thread in threads.values() { if let Some(&last) = thread.window.keys().next_back() { latest = std::cmp::max(latest, last); } } if latest > WINDOW.as_nanos() as usize { for thread in threads.values_mut() { // trim to last 5 seconds thread.window = thread .window .split_off(&(latest - WINDOW.as_nanos() as usize)); } } // now only reading let threads = &*threads; let mut lines = Vec::new(); let mut hits = HashMap::new(); let mut maxes = BTreeMap::new(); for (_, thread) in threads { // add up across the window let mut max: Option<(&str, usize)> = None; for (&time, stack) in &thread.window { latest = std::cmp::max(latest, time); let mut at = stack.len(); while let Some(stack_start) = stack[..at].rfind(';') { at = stack_start; let stack = &stack[at + 1..]; let count = hits.entry(stack).or_insert(0); *count += 1; if let Some((_, max_count)) = max { if *count >= max_count { max = Some((stack, *count)); } } else { max = Some((stack, *count)); } } } if let Some((stack, count)) = max { let e = maxes.entry(stack).or_insert((0, 0)); e.0 += 1; e.1 += count; } hits.clear(); } if maxes.is_empty() { return Ok(()); } let max = *maxes.values().map(|(_, count)| count).max().unwrap() as f64; // sort by where most threads are let mut maxes: Vec<_> = maxes.into_iter().collect(); maxes.sort_by_key(|(_, (nthreads, _))| *nthreads); for (stack, (nthreads, count)) in maxes.iter().rev() { let count = *count; let nthreads = *nthreads; if stack.find(';').is_none() { // this thread just shares the root frame continue; } if count == 1 { // this thread only has one sample ever, let's reduce noise... continue; } let red = (128.0 * count as f64 / max) as u8; let color = Color::Rgb(255, 128 - red, 128 - red); if nthreads == 1 { lines.push(Text::styled( format!("A thread fanned out from here {} times\n", count), Style::default().modifier(Modifier::BOLD).fg(color), )); } else { lines.push(Text::styled( format!( "{} threads fanned out from here {} times\n", nthreads, count ), Style::default().modifier(Modifier::BOLD).fg(color), )); } for (i, frame) in stack.split(';').enumerate() { // https://github.com/alexcrichton/rustc-demangle/issues/34 let offset = &frame[frame.rfind('+').unwrap_or_else(|| frame.len())..]; let frame = rustc_demangle::demangle(&frame[..frame.rfind('+').unwrap_or_else(|| frame.len())]); if i == 0 { lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default(), )); } else { lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default().modifier(Modifier::DIM), )); } } lines.push(Text::raw("\n")); } terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Paragraph::new(lines.iter()) .block( Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)), ) .render(&mut f, chunks[0]); })?; Ok(()) }
Thread
identifier_name