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 |
---|---|---|---|---|
stream.rs | use crate::{JsonRpcClient, Middleware, PinBoxFut, Provider, ProviderError};
use ethers_core::types::{Transaction, TxHash, U256};
use futures_core::stream::Stream;
use futures_core::Future;
use futures_util::stream::FuturesUnordered;
use futures_util::{stream, FutureExt, StreamExt};
use pin_project::pin_project;
use serde::{de::DeserializeOwned, Serialize};
use std::collections::VecDeque;
use std::{
fmt::Debug,
pin::Pin,
task::{Context, Poll},
time::Duration,
vec::IntoIter,
};
#[cfg(not(target_arch = "wasm32"))]
use futures_timer::Delay;
#[cfg(target_arch = "wasm32")]
use wasm_timer::Delay;
// https://github.com/tomusdrw/rust-web3/blob/befcb2fb8f3ca0a43e3081f68886fa327e64c8e6/src/api/eth_filter.rs#L20
pub fn interval(duration: Duration) -> impl Stream<Item = ()> + Send + Unpin {
stream::unfold((), move |_| Delay::new(duration).map(|_| Some(((), ())))).map(drop)
}
/// The default polling interval for filters and pending transactions
pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(7000);
enum FilterWatcherState<'a, R> {
WaitForInterval,
GetFilterChanges(PinBoxFut<'a, Vec<R>>),
NextItem(IntoIter<R>),
}
#[must_use = "filters do nothing unless you stream them"]
#[pin_project]
/// Streams data from an installed filter via `eth_getFilterChanges`
pub struct | <'a, P, R> {
/// The filter's installed id on the ethereum node
pub id: U256,
provider: &'a Provider<P>,
// The polling interval
interval: Box<dyn Stream<Item = ()> + Send + Unpin>,
state: FilterWatcherState<'a, R>,
}
impl<'a, P, R> FilterWatcher<'a, P, R>
where
P: JsonRpcClient,
R: Send + Sync + DeserializeOwned,
{
/// Creates a new watcher with the provided factory and filter id.
pub fn new<T: Into<U256>>(id: T, provider: &'a Provider<P>) -> Self {
Self {
id: id.into(),
interval: Box::new(interval(DEFAULT_POLL_INTERVAL)),
state: FilterWatcherState::WaitForInterval,
provider,
}
}
/// Sets the stream's polling interval
pub fn interval(mut self, duration: Duration) -> Self {
self.interval = Box::new(interval(duration));
self
}
/// Alias for Box::pin, must be called in order to pin the stream and be able
/// to call `next` on it.
pub fn stream(self) -> Pin<Box<Self>> {
Box::pin(self)
}
}
// Pattern for flattening the returned Vec of filter changes taken from
// https://github.com/tomusdrw/rust-web3/blob/f043b222744580bf4be043da757ab0b300c3b2da/src/api/eth_filter.rs#L50-L67
impl<'a, P, R> Stream for FilterWatcher<'a, P, R>
where
P: JsonRpcClient,
R: Serialize + Send + Sync + DeserializeOwned + Debug + 'a,
{
type Item = R;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let this = self.project();
let id = *this.id;
*this.state = match this.state {
FilterWatcherState::WaitForInterval => {
// Wait the polling period
let _ready = futures_util::ready!(this.interval.poll_next_unpin(cx));
// create a new instance of the future
cx.waker().wake_by_ref();
let fut = Box::pin(this.provider.get_filter_changes(id));
FilterWatcherState::GetFilterChanges(fut)
}
FilterWatcherState::GetFilterChanges(fut) => {
// NOTE: If the provider returns an error, this will return an empty
// vector. Should we make this return a Result instead? Ideally if we're
// in a streamed loop we wouldn't want the loop to terminate if an error
// is encountered (since it might be a temporary error).
let items: Vec<R> = futures_util::ready!(fut.as_mut().poll(cx)).unwrap_or_default();
cx.waker().wake_by_ref();
FilterWatcherState::NextItem(items.into_iter())
}
// Consume 1 element from the vector. If more elements are in the vector,
// the next call will immediately go to this branch instead of trying to get
// filter changes again. Once the whole vector is consumed, it will poll again
// for new logs
FilterWatcherState::NextItem(iter) => {
cx.waker().wake_by_ref();
match iter.next() {
Some(item) => return Poll::Ready(Some(item)),
None => FilterWatcherState::WaitForInterval,
}
}
};
Poll::Pending
}
}
impl<'a, P> FilterWatcher<'a, P, TxHash>
where
P: JsonRpcClient,
{
/// Returns a stream that yields the `Transaction`s for the transaction hashes this stream yields.
///
/// This internally calls `Provider::get_transaction` with every new transaction.
/// No more than n futures will be buffered at any point in time, and less than n may also be
/// buffered depending on the state of each future.
pub fn transactions_unordered(self, n: usize) -> TransactionStream<'a, P, Self> {
TransactionStream::new(self.provider, self, n)
}
}
/// Errors `TransactionStream` can throw
#[derive(Debug, thiserror::Error)]
pub enum GetTransactionError {
#[error("Failed to get transaction `{0}`: {1}")]
ProviderError(TxHash, ProviderError),
/// `get_transaction` resulted in a `None`
#[error("Transaction `{0}` not found")]
NotFound(TxHash),
}
impl From<GetTransactionError> for ProviderError {
fn from(err: GetTransactionError) -> Self {
match err {
GetTransactionError::ProviderError(_, err) => err,
err @ GetTransactionError::NotFound(_) => ProviderError::CustomError(err.to_string()),
}
}
}
type TransactionFut<'a> = Pin<Box<dyn Future<Output = TransactionResult> + 'a>>;
type TransactionResult = Result<Transaction, GetTransactionError>;
/// Drains a stream of transaction hashes and yields entire `Transaction`.
#[must_use = "streams do nothing unless polled"]
pub struct TransactionStream<'a, P, St> {
/// Currently running futures pending completion.
pending: FuturesUnordered<TransactionFut<'a>>,
/// Temporary buffered transaction that get started as soon as another future finishes.
buffered: VecDeque<TxHash>,
/// The provider that gets the transaction
provider: &'a Provider<P>,
/// A stream of transaction hashes.
stream: St,
/// max allowed futures to execute at once.
max_concurrent: usize,
}
impl<'a, P: JsonRpcClient, St> TransactionStream<'a, P, St> {
/// Create a new `TransactionStream` instance
pub fn new(provider: &'a Provider<P>, stream: St, max_concurrent: usize) -> Self {
Self {
pending: Default::default(),
buffered: Default::default(),
provider,
stream,
max_concurrent,
}
}
/// Push a future into the set
fn push_tx(&mut self, tx: TxHash) {
let fut = self
.provider
.get_transaction(tx)
.then(move |res| match res {
Ok(Some(tx)) => futures_util::future::ok(tx),
Ok(None) => futures_util::future::err(GetTransactionError::NotFound(tx)),
Err(err) => futures_util::future::err(GetTransactionError::ProviderError(tx, err)),
});
self.pending.push(Box::pin(fut));
}
}
impl<'a, P, St> Stream for TransactionStream<'a, P, St>
where
P: JsonRpcClient,
St: Stream<Item = TxHash> + Unpin + 'a,
{
type Item = TransactionResult;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
// drain buffered transactions first
while this.pending.len() < this.max_concurrent {
if let Some(tx) = this.buffered.pop_front() {
this.push_tx(tx);
} else {
break;
}
}
let mut stream_done = false;
loop {
match Stream::poll_next(Pin::new(&mut this.stream), cx) {
Poll::Ready(Some(tx)) => {
if this.pending.len() < this.max_concurrent {
this.push_tx(tx);
} else {
this.buffered.push_back(tx);
}
}
Poll::Ready(None) => {
stream_done = true;
break;
}
_ => break,
}
}
// poll running futures
if let tx @ Poll::Ready(Some(_)) = this.pending.poll_next_unpin(cx) {
return tx;
}
if stream_done && this.pending.is_empty() {
// all done
return Poll::Ready(None);
}
Poll::Pending
}
}
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
use super::*;
use crate::{Http, Ws};
use ethers_core::{
types::{TransactionReceipt, TransactionRequest},
utils::{Ganache, Geth},
};
use futures_util::{FutureExt, StreamExt};
use std::collections::HashSet;
use std::convert::TryFrom;
#[tokio::test]
async fn can_stream_pending_transactions() {
let num_txs = 5;
let geth = Geth::new().block_time(2u64).spawn();
let provider = Provider::<Http>::try_from(geth.endpoint())
.unwrap()
.interval(Duration::from_millis(1000));
let ws = Ws::connect(geth.ws_endpoint()).await.unwrap();
let ws_provider = Provider::new(ws);
let accounts = provider.get_accounts().await.unwrap();
let tx = TransactionRequest::new()
.from(accounts[0])
.to(accounts[0])
.value(1e18 as u64);
let mut sending = futures_util::future::join_all(
std::iter::repeat(tx.clone()).take(num_txs).map(|tx| async {
provider
.send_transaction(tx, None)
.await
.unwrap()
.await
.unwrap()
.unwrap()
}),
)
.fuse();
let mut watch_tx_stream = provider
.watch_pending_transactions()
.await
.unwrap()
.transactions_unordered(num_txs)
.fuse();
let mut sub_tx_stream = ws_provider
.subscribe_pending_txs()
.await
.unwrap()
.transactions_unordered(2)
.fuse();
let mut sent: Option<Vec<TransactionReceipt>> = None;
let mut watch_received: Vec<Transaction> = Vec::with_capacity(num_txs);
let mut sub_received: Vec<Transaction> = Vec::with_capacity(num_txs);
loop {
futures_util::select! {
txs = sending => {
sent = Some(txs)
},
tx = watch_tx_stream.next() => watch_received.push(tx.unwrap().unwrap()),
tx = sub_tx_stream.next() => sub_received.push(tx.unwrap().unwrap()),
};
if watch_received.len() == num_txs && sub_received.len() == num_txs {
if let Some(ref sent) = sent {
assert_eq!(sent.len(), watch_received.len());
let sent_txs = sent
.iter()
.map(|tx| tx.transaction_hash)
.collect::<HashSet<_>>();
assert_eq!(sent_txs, watch_received.iter().map(|tx| tx.hash).collect());
assert_eq!(sent_txs, sub_received.iter().map(|tx| tx.hash).collect());
break;
}
}
}
}
#[tokio::test]
async fn can_stream_transactions() {
let ganache = Ganache::new().block_time(2u64).spawn();
let provider = Provider::<Http>::try_from(ganache.endpoint())
.unwrap()
.with_sender(ganache.addresses()[0]);
let accounts = provider.get_accounts().await.unwrap();
let tx = TransactionRequest::new()
.from(accounts[0])
.to(accounts[0])
.value(1e18 as u64);
let txs =
futures_util::future::join_all(std::iter::repeat(tx.clone()).take(3).map(|tx| async {
provider
.send_transaction(tx, None)
.await
.unwrap()
.await
.unwrap()
}))
.await;
let stream = TransactionStream::new(
&provider,
stream::iter(txs.iter().cloned().map(|tx| tx.unwrap().transaction_hash)),
10,
);
let res = stream
.collect::<Vec<_>>()
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert_eq!(res.len(), txs.len());
assert_eq!(
res.into_iter().map(|tx| tx.hash).collect::<HashSet<_>>(),
txs.into_iter()
.map(|tx| tx.unwrap().transaction_hash)
.collect()
);
}
}
| FilterWatcher | identifier_name |
lib.rs | //! This is an implementation the test factory pattern made to work with [Diesel][].
//!
//! [Diesel]: https://diesel.rs
//!
//! Example usage:
//!
//! ```
//! #[macro_use]
//! extern crate diesel;
//!
//! use diesel_factories::{Association, Factory};
//! use diesel::{pg::PgConnection, prelude::*};
//!
//! // Tell Diesel what our schema is
//! // Note unusual primary key name - see options for derive macro.
//! mod schema {
//! table! {
//! countries (identity) {
//! identity -> Integer,
//! name -> Text,
//! }
//! }
//!
//! table! {
//! cities (id) {
//! id -> Integer,
//! name -> Text,
//! country_id -> Integer,
//! }
//! }
//! }
//!
//! // Our city model
//! #[derive(Clone, Queryable)]
//! struct City {
//! pub id: i32,
//! pub name: String,
//! pub country_id: i32,
//! }
//!
//! #[derive(Clone, Factory)]
//! #[factory(
//! // model type our factory inserts
//! model = City,
//! // table the model belongs to
//! table = crate::schema::cities,
//! // connection type you use. Defaults to `PgConnection`
//! connection = diesel::pg::PgConnection,
//! // type of primary key. Defaults to `i32`
//! id = i32,
//! )]
//! struct CityFactory<'a> {
//! pub name: String,
//! // A `CityFactory` is associated to either an inserted `&'a Country` or a `CountryFactory`
//! // instance.
//! pub country: Association<'a, Country, CountryFactory>,
//! }
//!
//! // We make new factory instances through the `Default` trait
//! impl<'a> Default for CityFactory<'a> {
//! fn default() -> Self {
//! Self {
//! name: "Copenhagen".to_string(),
//! // `default` will return an `Association` with a `CountryFactory`. No inserts happen
//! // here.
//! //
//! // This is the same as `Association::Factory(CountryFactory::default())`.
//! country: Association::default(),
//! }
//! }
//! }
//!
//! // The same setup, but for `Country`
//! #[derive(Clone, Queryable)]
//! struct Country {
//! pub identity: i32,
//! pub name: String,
//! }
//!
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = Country,
//! table = crate::schema::countries,
//! connection = diesel::pg::PgConnection,
//! id = i32,
//! id_name = identity,
//! )]
//! struct CountryFactory {
//! pub name: String,
//! }
//!
//! impl Default for CountryFactory {
//! fn default() -> Self {
//! Self {
//! name: "Denmark".into(),
//! }
//! }
//! }
//!
//! // Usage
//! fn basic_usage() {
//! let con = establish_connection();
//!
//! let city = CityFactory::default().insert(&con);
//! assert_eq!("Copenhagen", city.name);
//!
//! let country = find_country_by_id(city.country_id, &con);
//! assert_eq!("Denmark", country.name);
//!
//! assert_eq!(1, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//!
//! fn setting_fields() {
//! let con = establish_connection();
//!
//! let city = CityFactory::default()
//! .name("Amsterdam")
//! .country(CountryFactory::default().name("Netherlands"))
//! .insert(&con);
//! assert_eq!("Amsterdam", city.name);
//!
//! let country = find_country_by_id(city.country_id, &con);
//! assert_eq!("Netherlands", country.name);
//!
//! assert_eq!(1, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//!
//! fn multiple_models_with_same_association() {
//! let con = establish_connection();
//!
//! let netherlands = CountryFactory::default()
//! .name("Netherlands")
//! .insert(&con);
//!
//! let amsterdam = CityFactory::default()
//! .name("Amsterdam")
//! .country(&netherlands)
//! .insert(&con);
//!
//! let hague = CityFactory::default()
//! .name("The Hague")
//! .country(&netherlands)
//! .insert(&con);
//!
//! assert_eq!(amsterdam.country_id, hague.country_id);
//!
//! assert_eq!(2, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//! #
//! # fn main() {
//! # basic_usage();
//! # setting_fields();
//! # multiple_models_with_same_association();
//! # }
//! # fn establish_connection() -> PgConnection {
//! # use std::env;
//! # let pg_host = env::var("POSTGRES_HOST").unwrap_or_else(|_| "localhost".to_string());
//! # let pg_port = env::var("POSTGRES_PORT").unwrap_or_else(|_| "5432".to_string());
//! # let pg_password = env::var("POSTGRES_PASSWORD").ok();
//! #
//! # let auth = if let Some(pg_password) = pg_password {
//! # format!("postgres:{}@", pg_password)
//! # } else {
//! # String::new()
//! # };
//! #
//! # let database_url = format!(
//! # "postgres://{auth}{host}:{port}/diesel_factories_test",
//! # auth = auth,
//! # host = pg_host,
//! # port = pg_port
//! # );
//! # let con = PgConnection::establish(&database_url).unwrap();
//! # con.begin_test_transaction().unwrap();
//! # con
//! # }
//!
//! // Utility functions just for demo'ing
//! fn count_cities(con: &PgConnection) -> i64 {
//! use crate::schema::cities;
//! use diesel::dsl::count_star;
//! cities::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn count_countries(con: &PgConnection) -> i64 {
//! use crate::schema::countries;
//! use diesel::dsl::count_star;
//! countries::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn find_country_by_id(input: i32, con: &PgConnection) -> Country {
//! use crate::schema::countries::dsl::*;
//! countries
//! .filter(identity.eq(&input))
//! .first::<Country>(con)
//! .unwrap()
//! }
//! ```
//!
//! ## `#[derive(Factory)]`
//!
//! ### Attributes
//!
//! These attributes are available on the struct itself inside `#[factory(...)]`.
//!
//! | Name | Description | Example | Default |
//! |---|---|---|---|
//! | `model` | Model type your factory inserts | `City` | None, required |
//! | `table` | Table your model belongs to | `crate::schema::cities` | None, required |
//! | `connection` | The connection type your app uses | `MysqlConnection` | `diesel::pg::PgConnection` |
//! | `id` | The type of your table's primary key | `i64` | `i32` |
//! | `id_name` | The name of your table's primary key column | `identity` | `id` |
//!
//! These attributes are available on association fields inside `#[factory(...)]`.
//!
//! | Name | Description | Example | Default |
//! |---|---|---|---|
//! | `foreign_key_name` | Name of the foreign key column on your model | `country_identity` | `{association_name}_id` |
//!
//! ### Builder methods
//!
//! Besides implementing [`Factory`] for your struct it will also derive builder methods for easily customizing each field. The generated code looks something like this:
//!
//! ```
//! struct CountryFactory {
//! pub name: String,
//! }
//!
//! // This is what gets generated for each field
//! impl CountryFactory {
//! fn name<T: Into<String>>(mut self, new: T) -> Self {
//! self.name = new.into();
//! self
//! }
//! }
//! #
//! # impl Default for CountryFactory {
//! # fn default() -> Self {
//! # CountryFactory { name: String::new() }
//! # }
//! # }
//!
//! // So you can do this
//! CountryFactory::default().name("Amsterdam");
//! ```
//!
//! [`Factory`]: trait.Factory.html
//!
//! ### Builder methods for associations
//!
//! The builder methods generated for `Association` fields are a bit different. If you have a factory like:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = City,
//! table = crate::schema::cities,
//! )]
//! struct CityFactory<'a> {
//! pub name: String,
//! pub country: Association<'a, Country, CountryFactory>,
//! }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # unimplemented!()
//! # }
//! # }
//! #
//! # fn main() {}
//! ```
//!
//! You'll be able to call `country` either with an owned `CountryFactory`:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! # #[derive(Clone, Factory)]
//! # #[factory(
//! # model = City,
//! # table = crate::schema::cities,
//! # )]
//! # struct CityFactory<'a> {
//! # pub name: String,
//! # pub country: Association<'a, Country, CountryFactory>,
//! # }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # Self {
//! # name: String::new(), country: Association::default(),
//! # }
//! # }
//! # }
//! #
//! # fn main() {
//! let country_factory = CountryFactory::default();
//! CityFactory::default().country(country_factory);
//! # }
//! ```
//!
//! Or a borrowed `Country`:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! # #[derive(Clone, Factory)]
//! # #[factory(
//! # model = City,
//! # table = crate::schema::cities,
//! # )]
//! # struct CityFactory<'a> {
//! # pub name: String,
//! # pub country: Association<'a, Country, CountryFactory>,
//! # }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # Self {
//! # name: String::new(), country: Association::default(),
//! # }
//! # }
//! # }
//! #
//! # fn main() {
//! let country = Country { id: 1, name: "Denmark".into() };
//! CityFactory::default().country(&country);
//! # }
//! ```
//!
//! This should prevent bugs where you have multiple factory instances sharing some association that you mutate halfway through a test.
//!
//! ### Optional associations
//!
//! If your model has a nullable association you can do this:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup_with_city_factory.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = User,
//! table = crate::schema::users,
//! )]
//! struct UserFactory<'a> {
//! pub name: String,
//! pub country: Option<Association<'a, Country, CountryFactory>>,
//! # pub age: i32,
//! # pub home_city: Option<Association<'a, City, CityFactory<'a>>>,
//! # pub current_city: Option<Association<'a, City, CityFactory<'a>>>,
//! }
//!
//! impl<'a> Default for UserFactory<'a> {
//! fn default() -> Self {
//! Self {
//! name: "Bob".into(),
//! country: None,
//! # age: 30,
//! # home_city: None,
//! # current_city: None,
//! }
//! }
//! }
//!
//! # fn main() {
//! // Setting `country` to a `CountryFactory`
//! let country_factory = CountryFactory::default();
//! UserFactory::default().country(Some(country_factory));
//!
//! // Setting `country` to a `Country`
//! let country = Country { id: 1, name: "Denmark".into() };
//! UserFactory::default().country(Some(&country));
//!
//! // Setting `country` to `None`
//! UserFactory::default().country(Option::<CountryFactory>::None);
//! UserFactory::default().country(Option::<&Country>::None);
//! # }
//! ```
//!
//! ### Customizing foreign key names
//!
//! You can customize the name of the foreign key for your associations like so
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = City,
//! table = crate::schema::cities,
//! )]
//! struct CityFactory<'a> {
//! #[factory(foreign_key_name = country_id)]
//! pub country: Association<'a, Country, CountryFactory>,
//! # pub name: String,
//! }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # unimplemented!()
//! # }
//! # }
//! #
//! # fn main() {}
//! ```
#![doc(html_root_url = "https://docs.rs/diesel-factories/2.0.0")]
#![deny(
mutable_borrow_reservation_conflict,
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
use std::sync::atomic::{AtomicUsize, Ordering};
pub use diesel_factories_code_gen::Factory;
/// A "belongs to" association that may or may not have been inserted yet.
///
/// You will normally be using this when setting up "belongs to" associations between models in
/// factories.
#[derive(Debug, Clone)]
pub enum Association<'a, Model, Factory> {
/// An associated model that has been inserted into the database.
///
/// You shouldn't have to use this direclty but instead just `Association::default()`.
Model(&'a Model),
/// A factory for a model that hasn't been inserted yet into the database.
///
/// You shouldn't have to use this direclty but instead just `Association::default()`.
Factory(Factory),
}
impl<Model, Factory: Default> Default for Association<'_, Model, Factory> {
fn default() -> Self {
Association::Factory(Factory::default())
}
}
impl<'a, Model, Factory> Association<'a, Model, Factory> {
#[doc(hidden)]
pub fn new_model(inner: &'a Model) -> Self {
Association::Model(inner)
}
#[doc(hidden)]
pub fn new_factory(inner: Factory) -> Self {
Association::Factory(inner)
}
}
impl<M, F> Association<'_, M, F>
where
F: Factory<Model = M> + Clone,
{
#[doc(hidden)]
pub fn insert_returning_id(&self, con: &F::Connection) -> F::Id {
match self {
Association::Model(model) => F::id_for_model(&model).clone(),
Association::Factory(factory) => {
let model = factory.clone().insert(con);
F::id_for_model(&model).clone()
}
}
}
}
/// A generic factory trait.
///
/// You shouldn't ever have to implement this trait yourself. It can be derived using
/// `#[derive(Factory)]`
///
/// See the [root module docs](/) for info on how to use `#[derive(Factory)]`.
pub trait Factory: Clone {
/// The model type the factory inserts.
///
/// For a factory named `UserFactory` this would probably be `User`. | /// The primary key type your model uses.
///
/// This will normally be i32 or i64 but can be whatever you need.
type Id: Clone;
/// The database connection type you use such as `diesel::pg::PgConnection`.
type Connection;
/// Insert the factory into the database.
///
/// # Panics
/// This will panic if the insert fails. Should be fine since you want panics early in tests.
fn insert(self, con: &Self::Connection) -> Self::Model;
/// Get the primary key value for a model type.
///
/// Just a generic wrapper around `model.id`.
fn id_for_model(model: &Self::Model) -> &Self::Id;
}
static SEQUENCE_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Utility function for generating unique ids or strings in factories.
/// Each time `sequence` gets called, the closure will receive a different number.
///
/// ```
/// use diesel_factories::sequence;
///
/// assert_ne!(
/// sequence(|i| format!("unique-string-{}", i)),
/// sequence(|i| format!("unique-string-{}", i)),
/// );
/// ```
pub fn sequence<T, F>(f: F) -> T
where
F: Fn(usize) -> T,
{
SEQUENCE_COUNTER.fetch_add(1, Ordering::SeqCst);
let count = SEQUENCE_COUNTER.load(Ordering::Relaxed);
f(count)
}
#[cfg(test)]
mod test {
#[allow(unused_imports)]
use super::*;
#[test]
fn test_compile_pass() {
let t = trybuild::TestCases::new();
t.pass("tests/compile_pass/*.rs");
t.compile_fail("tests/compile_fail/*.rs");
}
} | type Model;
| random_line_split |
lib.rs | //! This is an implementation the test factory pattern made to work with [Diesel][].
//!
//! [Diesel]: https://diesel.rs
//!
//! Example usage:
//!
//! ```
//! #[macro_use]
//! extern crate diesel;
//!
//! use diesel_factories::{Association, Factory};
//! use diesel::{pg::PgConnection, prelude::*};
//!
//! // Tell Diesel what our schema is
//! // Note unusual primary key name - see options for derive macro.
//! mod schema {
//! table! {
//! countries (identity) {
//! identity -> Integer,
//! name -> Text,
//! }
//! }
//!
//! table! {
//! cities (id) {
//! id -> Integer,
//! name -> Text,
//! country_id -> Integer,
//! }
//! }
//! }
//!
//! // Our city model
//! #[derive(Clone, Queryable)]
//! struct City {
//! pub id: i32,
//! pub name: String,
//! pub country_id: i32,
//! }
//!
//! #[derive(Clone, Factory)]
//! #[factory(
//! // model type our factory inserts
//! model = City,
//! // table the model belongs to
//! table = crate::schema::cities,
//! // connection type you use. Defaults to `PgConnection`
//! connection = diesel::pg::PgConnection,
//! // type of primary key. Defaults to `i32`
//! id = i32,
//! )]
//! struct CityFactory<'a> {
//! pub name: String,
//! // A `CityFactory` is associated to either an inserted `&'a Country` or a `CountryFactory`
//! // instance.
//! pub country: Association<'a, Country, CountryFactory>,
//! }
//!
//! // We make new factory instances through the `Default` trait
//! impl<'a> Default for CityFactory<'a> {
//! fn default() -> Self {
//! Self {
//! name: "Copenhagen".to_string(),
//! // `default` will return an `Association` with a `CountryFactory`. No inserts happen
//! // here.
//! //
//! // This is the same as `Association::Factory(CountryFactory::default())`.
//! country: Association::default(),
//! }
//! }
//! }
//!
//! // The same setup, but for `Country`
//! #[derive(Clone, Queryable)]
//! struct Country {
//! pub identity: i32,
//! pub name: String,
//! }
//!
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = Country,
//! table = crate::schema::countries,
//! connection = diesel::pg::PgConnection,
//! id = i32,
//! id_name = identity,
//! )]
//! struct CountryFactory {
//! pub name: String,
//! }
//!
//! impl Default for CountryFactory {
//! fn default() -> Self {
//! Self {
//! name: "Denmark".into(),
//! }
//! }
//! }
//!
//! // Usage
//! fn basic_usage() {
//! let con = establish_connection();
//!
//! let city = CityFactory::default().insert(&con);
//! assert_eq!("Copenhagen", city.name);
//!
//! let country = find_country_by_id(city.country_id, &con);
//! assert_eq!("Denmark", country.name);
//!
//! assert_eq!(1, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//!
//! fn setting_fields() {
//! let con = establish_connection();
//!
//! let city = CityFactory::default()
//! .name("Amsterdam")
//! .country(CountryFactory::default().name("Netherlands"))
//! .insert(&con);
//! assert_eq!("Amsterdam", city.name);
//!
//! let country = find_country_by_id(city.country_id, &con);
//! assert_eq!("Netherlands", country.name);
//!
//! assert_eq!(1, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//!
//! fn multiple_models_with_same_association() {
//! let con = establish_connection();
//!
//! let netherlands = CountryFactory::default()
//! .name("Netherlands")
//! .insert(&con);
//!
//! let amsterdam = CityFactory::default()
//! .name("Amsterdam")
//! .country(&netherlands)
//! .insert(&con);
//!
//! let hague = CityFactory::default()
//! .name("The Hague")
//! .country(&netherlands)
//! .insert(&con);
//!
//! assert_eq!(amsterdam.country_id, hague.country_id);
//!
//! assert_eq!(2, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//! #
//! # fn main() {
//! # basic_usage();
//! # setting_fields();
//! # multiple_models_with_same_association();
//! # }
//! # fn establish_connection() -> PgConnection {
//! # use std::env;
//! # let pg_host = env::var("POSTGRES_HOST").unwrap_or_else(|_| "localhost".to_string());
//! # let pg_port = env::var("POSTGRES_PORT").unwrap_or_else(|_| "5432".to_string());
//! # let pg_password = env::var("POSTGRES_PASSWORD").ok();
//! #
//! # let auth = if let Some(pg_password) = pg_password {
//! # format!("postgres:{}@", pg_password)
//! # } else {
//! # String::new()
//! # };
//! #
//! # let database_url = format!(
//! # "postgres://{auth}{host}:{port}/diesel_factories_test",
//! # auth = auth,
//! # host = pg_host,
//! # port = pg_port
//! # );
//! # let con = PgConnection::establish(&database_url).unwrap();
//! # con.begin_test_transaction().unwrap();
//! # con
//! # }
//!
//! // Utility functions just for demo'ing
//! fn count_cities(con: &PgConnection) -> i64 {
//! use crate::schema::cities;
//! use diesel::dsl::count_star;
//! cities::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn count_countries(con: &PgConnection) -> i64 {
//! use crate::schema::countries;
//! use diesel::dsl::count_star;
//! countries::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn find_country_by_id(input: i32, con: &PgConnection) -> Country {
//! use crate::schema::countries::dsl::*;
//! countries
//! .filter(identity.eq(&input))
//! .first::<Country>(con)
//! .unwrap()
//! }
//! ```
//!
//! ## `#[derive(Factory)]`
//!
//! ### Attributes
//!
//! These attributes are available on the struct itself inside `#[factory(...)]`.
//!
//! | Name | Description | Example | Default |
//! |---|---|---|---|
//! | `model` | Model type your factory inserts | `City` | None, required |
//! | `table` | Table your model belongs to | `crate::schema::cities` | None, required |
//! | `connection` | The connection type your app uses | `MysqlConnection` | `diesel::pg::PgConnection` |
//! | `id` | The type of your table's primary key | `i64` | `i32` |
//! | `id_name` | The name of your table's primary key column | `identity` | `id` |
//!
//! These attributes are available on association fields inside `#[factory(...)]`.
//!
//! | Name | Description | Example | Default |
//! |---|---|---|---|
//! | `foreign_key_name` | Name of the foreign key column on your model | `country_identity` | `{association_name}_id` |
//!
//! ### Builder methods
//!
//! Besides implementing [`Factory`] for your struct it will also derive builder methods for easily customizing each field. The generated code looks something like this:
//!
//! ```
//! struct CountryFactory {
//! pub name: String,
//! }
//!
//! // This is what gets generated for each field
//! impl CountryFactory {
//! fn name<T: Into<String>>(mut self, new: T) -> Self {
//! self.name = new.into();
//! self
//! }
//! }
//! #
//! # impl Default for CountryFactory {
//! # fn default() -> Self {
//! # CountryFactory { name: String::new() }
//! # }
//! # }
//!
//! // So you can do this
//! CountryFactory::default().name("Amsterdam");
//! ```
//!
//! [`Factory`]: trait.Factory.html
//!
//! ### Builder methods for associations
//!
//! The builder methods generated for `Association` fields are a bit different. If you have a factory like:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = City,
//! table = crate::schema::cities,
//! )]
//! struct CityFactory<'a> {
//! pub name: String,
//! pub country: Association<'a, Country, CountryFactory>,
//! }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # unimplemented!()
//! # }
//! # }
//! #
//! # fn main() {}
//! ```
//!
//! You'll be able to call `country` either with an owned `CountryFactory`:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! # #[derive(Clone, Factory)]
//! # #[factory(
//! # model = City,
//! # table = crate::schema::cities,
//! # )]
//! # struct CityFactory<'a> {
//! # pub name: String,
//! # pub country: Association<'a, Country, CountryFactory>,
//! # }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # Self {
//! # name: String::new(), country: Association::default(),
//! # }
//! # }
//! # }
//! #
//! # fn main() {
//! let country_factory = CountryFactory::default();
//! CityFactory::default().country(country_factory);
//! # }
//! ```
//!
//! Or a borrowed `Country`:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! # #[derive(Clone, Factory)]
//! # #[factory(
//! # model = City,
//! # table = crate::schema::cities,
//! # )]
//! # struct CityFactory<'a> {
//! # pub name: String,
//! # pub country: Association<'a, Country, CountryFactory>,
//! # }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # Self {
//! # name: String::new(), country: Association::default(),
//! # }
//! # }
//! # }
//! #
//! # fn main() {
//! let country = Country { id: 1, name: "Denmark".into() };
//! CityFactory::default().country(&country);
//! # }
//! ```
//!
//! This should prevent bugs where you have multiple factory instances sharing some association that you mutate halfway through a test.
//!
//! ### Optional associations
//!
//! If your model has a nullable association you can do this:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup_with_city_factory.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = User,
//! table = crate::schema::users,
//! )]
//! struct UserFactory<'a> {
//! pub name: String,
//! pub country: Option<Association<'a, Country, CountryFactory>>,
//! # pub age: i32,
//! # pub home_city: Option<Association<'a, City, CityFactory<'a>>>,
//! # pub current_city: Option<Association<'a, City, CityFactory<'a>>>,
//! }
//!
//! impl<'a> Default for UserFactory<'a> {
//! fn default() -> Self {
//! Self {
//! name: "Bob".into(),
//! country: None,
//! # age: 30,
//! # home_city: None,
//! # current_city: None,
//! }
//! }
//! }
//!
//! # fn main() {
//! // Setting `country` to a `CountryFactory`
//! let country_factory = CountryFactory::default();
//! UserFactory::default().country(Some(country_factory));
//!
//! // Setting `country` to a `Country`
//! let country = Country { id: 1, name: "Denmark".into() };
//! UserFactory::default().country(Some(&country));
//!
//! // Setting `country` to `None`
//! UserFactory::default().country(Option::<CountryFactory>::None);
//! UserFactory::default().country(Option::<&Country>::None);
//! # }
//! ```
//!
//! ### Customizing foreign key names
//!
//! You can customize the name of the foreign key for your associations like so
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = City,
//! table = crate::schema::cities,
//! )]
//! struct CityFactory<'a> {
//! #[factory(foreign_key_name = country_id)]
//! pub country: Association<'a, Country, CountryFactory>,
//! # pub name: String,
//! }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # unimplemented!()
//! # }
//! # }
//! #
//! # fn main() {}
//! ```
#![doc(html_root_url = "https://docs.rs/diesel-factories/2.0.0")]
#![deny(
mutable_borrow_reservation_conflict,
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
use std::sync::atomic::{AtomicUsize, Ordering};
pub use diesel_factories_code_gen::Factory;
/// A "belongs to" association that may or may not have been inserted yet.
///
/// You will normally be using this when setting up "belongs to" associations between models in
/// factories.
#[derive(Debug, Clone)]
pub enum Association<'a, Model, Factory> {
/// An associated model that has been inserted into the database.
///
/// You shouldn't have to use this direclty but instead just `Association::default()`.
Model(&'a Model),
/// A factory for a model that hasn't been inserted yet into the database.
///
/// You shouldn't have to use this direclty but instead just `Association::default()`.
Factory(Factory),
}
impl<Model, Factory: Default> Default for Association<'_, Model, Factory> {
fn default() -> Self {
Association::Factory(Factory::default())
}
}
impl<'a, Model, Factory> Association<'a, Model, Factory> {
#[doc(hidden)]
pub fn new_model(inner: &'a Model) -> Self {
Association::Model(inner)
}
#[doc(hidden)]
pub fn new_factory(inner: Factory) -> Self {
Association::Factory(inner)
}
}
impl<M, F> Association<'_, M, F>
where
F: Factory<Model = M> + Clone,
{
#[doc(hidden)]
pub fn insert_returning_id(&self, con: &F::Connection) -> F::Id {
match self {
Association::Model(model) => F::id_for_model(&model).clone(),
Association::Factory(factory) => |
}
}
}
/// A generic factory trait.
///
/// You shouldn't ever have to implement this trait yourself. It can be derived using
/// `#[derive(Factory)]`
///
/// See the [root module docs](/) for info on how to use `#[derive(Factory)]`.
pub trait Factory: Clone {
/// The model type the factory inserts.
///
/// For a factory named `UserFactory` this would probably be `User`.
type Model;
/// The primary key type your model uses.
///
/// This will normally be i32 or i64 but can be whatever you need.
type Id: Clone;
/// The database connection type you use such as `diesel::pg::PgConnection`.
type Connection;
/// Insert the factory into the database.
///
/// # Panics
/// This will panic if the insert fails. Should be fine since you want panics early in tests.
fn insert(self, con: &Self::Connection) -> Self::Model;
/// Get the primary key value for a model type.
///
/// Just a generic wrapper around `model.id`.
fn id_for_model(model: &Self::Model) -> &Self::Id;
}
static SEQUENCE_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Utility function for generating unique ids or strings in factories.
/// Each time `sequence` gets called, the closure will receive a different number.
///
/// ```
/// use diesel_factories::sequence;
///
/// assert_ne!(
/// sequence(|i| format!("unique-string-{}", i)),
/// sequence(|i| format!("unique-string-{}", i)),
/// );
/// ```
pub fn sequence<T, F>(f: F) -> T
where
F: Fn(usize) -> T,
{
SEQUENCE_COUNTER.fetch_add(1, Ordering::SeqCst);
let count = SEQUENCE_COUNTER.load(Ordering::Relaxed);
f(count)
}
#[cfg(test)]
mod test {
#[allow(unused_imports)]
use super::*;
#[test]
fn test_compile_pass() {
let t = trybuild::TestCases::new();
t.pass("tests/compile_pass/*.rs");
t.compile_fail("tests/compile_fail/*.rs");
}
}
| {
let model = factory.clone().insert(con);
F::id_for_model(&model).clone()
} | conditional_block |
lib.rs | //! This is an implementation the test factory pattern made to work with [Diesel][].
//!
//! [Diesel]: https://diesel.rs
//!
//! Example usage:
//!
//! ```
//! #[macro_use]
//! extern crate diesel;
//!
//! use diesel_factories::{Association, Factory};
//! use diesel::{pg::PgConnection, prelude::*};
//!
//! // Tell Diesel what our schema is
//! // Note unusual primary key name - see options for derive macro.
//! mod schema {
//! table! {
//! countries (identity) {
//! identity -> Integer,
//! name -> Text,
//! }
//! }
//!
//! table! {
//! cities (id) {
//! id -> Integer,
//! name -> Text,
//! country_id -> Integer,
//! }
//! }
//! }
//!
//! // Our city model
//! #[derive(Clone, Queryable)]
//! struct City {
//! pub id: i32,
//! pub name: String,
//! pub country_id: i32,
//! }
//!
//! #[derive(Clone, Factory)]
//! #[factory(
//! // model type our factory inserts
//! model = City,
//! // table the model belongs to
//! table = crate::schema::cities,
//! // connection type you use. Defaults to `PgConnection`
//! connection = diesel::pg::PgConnection,
//! // type of primary key. Defaults to `i32`
//! id = i32,
//! )]
//! struct CityFactory<'a> {
//! pub name: String,
//! // A `CityFactory` is associated to either an inserted `&'a Country` or a `CountryFactory`
//! // instance.
//! pub country: Association<'a, Country, CountryFactory>,
//! }
//!
//! // We make new factory instances through the `Default` trait
//! impl<'a> Default for CityFactory<'a> {
//! fn default() -> Self {
//! Self {
//! name: "Copenhagen".to_string(),
//! // `default` will return an `Association` with a `CountryFactory`. No inserts happen
//! // here.
//! //
//! // This is the same as `Association::Factory(CountryFactory::default())`.
//! country: Association::default(),
//! }
//! }
//! }
//!
//! // The same setup, but for `Country`
//! #[derive(Clone, Queryable)]
//! struct Country {
//! pub identity: i32,
//! pub name: String,
//! }
//!
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = Country,
//! table = crate::schema::countries,
//! connection = diesel::pg::PgConnection,
//! id = i32,
//! id_name = identity,
//! )]
//! struct CountryFactory {
//! pub name: String,
//! }
//!
//! impl Default for CountryFactory {
//! fn default() -> Self {
//! Self {
//! name: "Denmark".into(),
//! }
//! }
//! }
//!
//! // Usage
//! fn basic_usage() {
//! let con = establish_connection();
//!
//! let city = CityFactory::default().insert(&con);
//! assert_eq!("Copenhagen", city.name);
//!
//! let country = find_country_by_id(city.country_id, &con);
//! assert_eq!("Denmark", country.name);
//!
//! assert_eq!(1, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//!
//! fn setting_fields() {
//! let con = establish_connection();
//!
//! let city = CityFactory::default()
//! .name("Amsterdam")
//! .country(CountryFactory::default().name("Netherlands"))
//! .insert(&con);
//! assert_eq!("Amsterdam", city.name);
//!
//! let country = find_country_by_id(city.country_id, &con);
//! assert_eq!("Netherlands", country.name);
//!
//! assert_eq!(1, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//!
//! fn multiple_models_with_same_association() {
//! let con = establish_connection();
//!
//! let netherlands = CountryFactory::default()
//! .name("Netherlands")
//! .insert(&con);
//!
//! let amsterdam = CityFactory::default()
//! .name("Amsterdam")
//! .country(&netherlands)
//! .insert(&con);
//!
//! let hague = CityFactory::default()
//! .name("The Hague")
//! .country(&netherlands)
//! .insert(&con);
//!
//! assert_eq!(amsterdam.country_id, hague.country_id);
//!
//! assert_eq!(2, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//! #
//! # fn main() {
//! # basic_usage();
//! # setting_fields();
//! # multiple_models_with_same_association();
//! # }
//! # fn establish_connection() -> PgConnection {
//! # use std::env;
//! # let pg_host = env::var("POSTGRES_HOST").unwrap_or_else(|_| "localhost".to_string());
//! # let pg_port = env::var("POSTGRES_PORT").unwrap_or_else(|_| "5432".to_string());
//! # let pg_password = env::var("POSTGRES_PASSWORD").ok();
//! #
//! # let auth = if let Some(pg_password) = pg_password {
//! # format!("postgres:{}@", pg_password)
//! # } else {
//! # String::new()
//! # };
//! #
//! # let database_url = format!(
//! # "postgres://{auth}{host}:{port}/diesel_factories_test",
//! # auth = auth,
//! # host = pg_host,
//! # port = pg_port
//! # );
//! # let con = PgConnection::establish(&database_url).unwrap();
//! # con.begin_test_transaction().unwrap();
//! # con
//! # }
//!
//! // Utility functions just for demo'ing
//! fn count_cities(con: &PgConnection) -> i64 {
//! use crate::schema::cities;
//! use diesel::dsl::count_star;
//! cities::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn count_countries(con: &PgConnection) -> i64 {
//! use crate::schema::countries;
//! use diesel::dsl::count_star;
//! countries::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn find_country_by_id(input: i32, con: &PgConnection) -> Country {
//! use crate::schema::countries::dsl::*;
//! countries
//! .filter(identity.eq(&input))
//! .first::<Country>(con)
//! .unwrap()
//! }
//! ```
//!
//! ## `#[derive(Factory)]`
//!
//! ### Attributes
//!
//! These attributes are available on the struct itself inside `#[factory(...)]`.
//!
//! | Name | Description | Example | Default |
//! |---|---|---|---|
//! | `model` | Model type your factory inserts | `City` | None, required |
//! | `table` | Table your model belongs to | `crate::schema::cities` | None, required |
//! | `connection` | The connection type your app uses | `MysqlConnection` | `diesel::pg::PgConnection` |
//! | `id` | The type of your table's primary key | `i64` | `i32` |
//! | `id_name` | The name of your table's primary key column | `identity` | `id` |
//!
//! These attributes are available on association fields inside `#[factory(...)]`.
//!
//! | Name | Description | Example | Default |
//! |---|---|---|---|
//! | `foreign_key_name` | Name of the foreign key column on your model | `country_identity` | `{association_name}_id` |
//!
//! ### Builder methods
//!
//! Besides implementing [`Factory`] for your struct it will also derive builder methods for easily customizing each field. The generated code looks something like this:
//!
//! ```
//! struct CountryFactory {
//! pub name: String,
//! }
//!
//! // This is what gets generated for each field
//! impl CountryFactory {
//! fn name<T: Into<String>>(mut self, new: T) -> Self {
//! self.name = new.into();
//! self
//! }
//! }
//! #
//! # impl Default for CountryFactory {
//! # fn default() -> Self {
//! # CountryFactory { name: String::new() }
//! # }
//! # }
//!
//! // So you can do this
//! CountryFactory::default().name("Amsterdam");
//! ```
//!
//! [`Factory`]: trait.Factory.html
//!
//! ### Builder methods for associations
//!
//! The builder methods generated for `Association` fields are a bit different. If you have a factory like:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = City,
//! table = crate::schema::cities,
//! )]
//! struct CityFactory<'a> {
//! pub name: String,
//! pub country: Association<'a, Country, CountryFactory>,
//! }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # unimplemented!()
//! # }
//! # }
//! #
//! # fn main() {}
//! ```
//!
//! You'll be able to call `country` either with an owned `CountryFactory`:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! # #[derive(Clone, Factory)]
//! # #[factory(
//! # model = City,
//! # table = crate::schema::cities,
//! # )]
//! # struct CityFactory<'a> {
//! # pub name: String,
//! # pub country: Association<'a, Country, CountryFactory>,
//! # }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # Self {
//! # name: String::new(), country: Association::default(),
//! # }
//! # }
//! # }
//! #
//! # fn main() {
//! let country_factory = CountryFactory::default();
//! CityFactory::default().country(country_factory);
//! # }
//! ```
//!
//! Or a borrowed `Country`:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! # #[derive(Clone, Factory)]
//! # #[factory(
//! # model = City,
//! # table = crate::schema::cities,
//! # )]
//! # struct CityFactory<'a> {
//! # pub name: String,
//! # pub country: Association<'a, Country, CountryFactory>,
//! # }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # Self {
//! # name: String::new(), country: Association::default(),
//! # }
//! # }
//! # }
//! #
//! # fn main() {
//! let country = Country { id: 1, name: "Denmark".into() };
//! CityFactory::default().country(&country);
//! # }
//! ```
//!
//! This should prevent bugs where you have multiple factory instances sharing some association that you mutate halfway through a test.
//!
//! ### Optional associations
//!
//! If your model has a nullable association you can do this:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup_with_city_factory.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = User,
//! table = crate::schema::users,
//! )]
//! struct UserFactory<'a> {
//! pub name: String,
//! pub country: Option<Association<'a, Country, CountryFactory>>,
//! # pub age: i32,
//! # pub home_city: Option<Association<'a, City, CityFactory<'a>>>,
//! # pub current_city: Option<Association<'a, City, CityFactory<'a>>>,
//! }
//!
//! impl<'a> Default for UserFactory<'a> {
//! fn default() -> Self {
//! Self {
//! name: "Bob".into(),
//! country: None,
//! # age: 30,
//! # home_city: None,
//! # current_city: None,
//! }
//! }
//! }
//!
//! # fn main() {
//! // Setting `country` to a `CountryFactory`
//! let country_factory = CountryFactory::default();
//! UserFactory::default().country(Some(country_factory));
//!
//! // Setting `country` to a `Country`
//! let country = Country { id: 1, name: "Denmark".into() };
//! UserFactory::default().country(Some(&country));
//!
//! // Setting `country` to `None`
//! UserFactory::default().country(Option::<CountryFactory>::None);
//! UserFactory::default().country(Option::<&Country>::None);
//! # }
//! ```
//!
//! ### Customizing foreign key names
//!
//! You can customize the name of the foreign key for your associations like so
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = City,
//! table = crate::schema::cities,
//! )]
//! struct CityFactory<'a> {
//! #[factory(foreign_key_name = country_id)]
//! pub country: Association<'a, Country, CountryFactory>,
//! # pub name: String,
//! }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # unimplemented!()
//! # }
//! # }
//! #
//! # fn main() {}
//! ```
#![doc(html_root_url = "https://docs.rs/diesel-factories/2.0.0")]
#![deny(
mutable_borrow_reservation_conflict,
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
use std::sync::atomic::{AtomicUsize, Ordering};
pub use diesel_factories_code_gen::Factory;
/// A "belongs to" association that may or may not have been inserted yet.
///
/// You will normally be using this when setting up "belongs to" associations between models in
/// factories.
#[derive(Debug, Clone)]
pub enum Association<'a, Model, Factory> {
/// An associated model that has been inserted into the database.
///
/// You shouldn't have to use this direclty but instead just `Association::default()`.
Model(&'a Model),
/// A factory for a model that hasn't been inserted yet into the database.
///
/// You shouldn't have to use this direclty but instead just `Association::default()`.
Factory(Factory),
}
impl<Model, Factory: Default> Default for Association<'_, Model, Factory> {
fn default() -> Self {
Association::Factory(Factory::default())
}
}
impl<'a, Model, Factory> Association<'a, Model, Factory> {
#[doc(hidden)]
pub fn new_model(inner: &'a Model) -> Self |
#[doc(hidden)]
pub fn new_factory(inner: Factory) -> Self {
Association::Factory(inner)
}
}
impl<M, F> Association<'_, M, F>
where
F: Factory<Model = M> + Clone,
{
#[doc(hidden)]
pub fn insert_returning_id(&self, con: &F::Connection) -> F::Id {
match self {
Association::Model(model) => F::id_for_model(&model).clone(),
Association::Factory(factory) => {
let model = factory.clone().insert(con);
F::id_for_model(&model).clone()
}
}
}
}
/// A generic factory trait.
///
/// You shouldn't ever have to implement this trait yourself. It can be derived using
/// `#[derive(Factory)]`
///
/// See the [root module docs](/) for info on how to use `#[derive(Factory)]`.
pub trait Factory: Clone {
/// The model type the factory inserts.
///
/// For a factory named `UserFactory` this would probably be `User`.
type Model;
/// The primary key type your model uses.
///
/// This will normally be i32 or i64 but can be whatever you need.
type Id: Clone;
/// The database connection type you use such as `diesel::pg::PgConnection`.
type Connection;
/// Insert the factory into the database.
///
/// # Panics
/// This will panic if the insert fails. Should be fine since you want panics early in tests.
fn insert(self, con: &Self::Connection) -> Self::Model;
/// Get the primary key value for a model type.
///
/// Just a generic wrapper around `model.id`.
fn id_for_model(model: &Self::Model) -> &Self::Id;
}
static SEQUENCE_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Utility function for generating unique ids or strings in factories.
/// Each time `sequence` gets called, the closure will receive a different number.
///
/// ```
/// use diesel_factories::sequence;
///
/// assert_ne!(
/// sequence(|i| format!("unique-string-{}", i)),
/// sequence(|i| format!("unique-string-{}", i)),
/// );
/// ```
pub fn sequence<T, F>(f: F) -> T
where
F: Fn(usize) -> T,
{
SEQUENCE_COUNTER.fetch_add(1, Ordering::SeqCst);
let count = SEQUENCE_COUNTER.load(Ordering::Relaxed);
f(count)
}
#[cfg(test)]
mod test {
#[allow(unused_imports)]
use super::*;
#[test]
fn test_compile_pass() {
let t = trybuild::TestCases::new();
t.pass("tests/compile_pass/*.rs");
t.compile_fail("tests/compile_fail/*.rs");
}
}
| {
Association::Model(inner)
} | identifier_body |
lib.rs | //! This is an implementation the test factory pattern made to work with [Diesel][].
//!
//! [Diesel]: https://diesel.rs
//!
//! Example usage:
//!
//! ```
//! #[macro_use]
//! extern crate diesel;
//!
//! use diesel_factories::{Association, Factory};
//! use diesel::{pg::PgConnection, prelude::*};
//!
//! // Tell Diesel what our schema is
//! // Note unusual primary key name - see options for derive macro.
//! mod schema {
//! table! {
//! countries (identity) {
//! identity -> Integer,
//! name -> Text,
//! }
//! }
//!
//! table! {
//! cities (id) {
//! id -> Integer,
//! name -> Text,
//! country_id -> Integer,
//! }
//! }
//! }
//!
//! // Our city model
//! #[derive(Clone, Queryable)]
//! struct City {
//! pub id: i32,
//! pub name: String,
//! pub country_id: i32,
//! }
//!
//! #[derive(Clone, Factory)]
//! #[factory(
//! // model type our factory inserts
//! model = City,
//! // table the model belongs to
//! table = crate::schema::cities,
//! // connection type you use. Defaults to `PgConnection`
//! connection = diesel::pg::PgConnection,
//! // type of primary key. Defaults to `i32`
//! id = i32,
//! )]
//! struct CityFactory<'a> {
//! pub name: String,
//! // A `CityFactory` is associated to either an inserted `&'a Country` or a `CountryFactory`
//! // instance.
//! pub country: Association<'a, Country, CountryFactory>,
//! }
//!
//! // We make new factory instances through the `Default` trait
//! impl<'a> Default for CityFactory<'a> {
//! fn default() -> Self {
//! Self {
//! name: "Copenhagen".to_string(),
//! // `default` will return an `Association` with a `CountryFactory`. No inserts happen
//! // here.
//! //
//! // This is the same as `Association::Factory(CountryFactory::default())`.
//! country: Association::default(),
//! }
//! }
//! }
//!
//! // The same setup, but for `Country`
//! #[derive(Clone, Queryable)]
//! struct Country {
//! pub identity: i32,
//! pub name: String,
//! }
//!
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = Country,
//! table = crate::schema::countries,
//! connection = diesel::pg::PgConnection,
//! id = i32,
//! id_name = identity,
//! )]
//! struct CountryFactory {
//! pub name: String,
//! }
//!
//! impl Default for CountryFactory {
//! fn default() -> Self {
//! Self {
//! name: "Denmark".into(),
//! }
//! }
//! }
//!
//! // Usage
//! fn basic_usage() {
//! let con = establish_connection();
//!
//! let city = CityFactory::default().insert(&con);
//! assert_eq!("Copenhagen", city.name);
//!
//! let country = find_country_by_id(city.country_id, &con);
//! assert_eq!("Denmark", country.name);
//!
//! assert_eq!(1, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//!
//! fn setting_fields() {
//! let con = establish_connection();
//!
//! let city = CityFactory::default()
//! .name("Amsterdam")
//! .country(CountryFactory::default().name("Netherlands"))
//! .insert(&con);
//! assert_eq!("Amsterdam", city.name);
//!
//! let country = find_country_by_id(city.country_id, &con);
//! assert_eq!("Netherlands", country.name);
//!
//! assert_eq!(1, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//!
//! fn multiple_models_with_same_association() {
//! let con = establish_connection();
//!
//! let netherlands = CountryFactory::default()
//! .name("Netherlands")
//! .insert(&con);
//!
//! let amsterdam = CityFactory::default()
//! .name("Amsterdam")
//! .country(&netherlands)
//! .insert(&con);
//!
//! let hague = CityFactory::default()
//! .name("The Hague")
//! .country(&netherlands)
//! .insert(&con);
//!
//! assert_eq!(amsterdam.country_id, hague.country_id);
//!
//! assert_eq!(2, count_cities(&con));
//! assert_eq!(1, count_countries(&con));
//! }
//! #
//! # fn main() {
//! # basic_usage();
//! # setting_fields();
//! # multiple_models_with_same_association();
//! # }
//! # fn establish_connection() -> PgConnection {
//! # use std::env;
//! # let pg_host = env::var("POSTGRES_HOST").unwrap_or_else(|_| "localhost".to_string());
//! # let pg_port = env::var("POSTGRES_PORT").unwrap_or_else(|_| "5432".to_string());
//! # let pg_password = env::var("POSTGRES_PASSWORD").ok();
//! #
//! # let auth = if let Some(pg_password) = pg_password {
//! # format!("postgres:{}@", pg_password)
//! # } else {
//! # String::new()
//! # };
//! #
//! # let database_url = format!(
//! # "postgres://{auth}{host}:{port}/diesel_factories_test",
//! # auth = auth,
//! # host = pg_host,
//! # port = pg_port
//! # );
//! # let con = PgConnection::establish(&database_url).unwrap();
//! # con.begin_test_transaction().unwrap();
//! # con
//! # }
//!
//! // Utility functions just for demo'ing
//! fn count_cities(con: &PgConnection) -> i64 {
//! use crate::schema::cities;
//! use diesel::dsl::count_star;
//! cities::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn count_countries(con: &PgConnection) -> i64 {
//! use crate::schema::countries;
//! use diesel::dsl::count_star;
//! countries::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn find_country_by_id(input: i32, con: &PgConnection) -> Country {
//! use crate::schema::countries::dsl::*;
//! countries
//! .filter(identity.eq(&input))
//! .first::<Country>(con)
//! .unwrap()
//! }
//! ```
//!
//! ## `#[derive(Factory)]`
//!
//! ### Attributes
//!
//! These attributes are available on the struct itself inside `#[factory(...)]`.
//!
//! | Name | Description | Example | Default |
//! |---|---|---|---|
//! | `model` | Model type your factory inserts | `City` | None, required |
//! | `table` | Table your model belongs to | `crate::schema::cities` | None, required |
//! | `connection` | The connection type your app uses | `MysqlConnection` | `diesel::pg::PgConnection` |
//! | `id` | The type of your table's primary key | `i64` | `i32` |
//! | `id_name` | The name of your table's primary key column | `identity` | `id` |
//!
//! These attributes are available on association fields inside `#[factory(...)]`.
//!
//! | Name | Description | Example | Default |
//! |---|---|---|---|
//! | `foreign_key_name` | Name of the foreign key column on your model | `country_identity` | `{association_name}_id` |
//!
//! ### Builder methods
//!
//! Besides implementing [`Factory`] for your struct it will also derive builder methods for easily customizing each field. The generated code looks something like this:
//!
//! ```
//! struct CountryFactory {
//! pub name: String,
//! }
//!
//! // This is what gets generated for each field
//! impl CountryFactory {
//! fn name<T: Into<String>>(mut self, new: T) -> Self {
//! self.name = new.into();
//! self
//! }
//! }
//! #
//! # impl Default for CountryFactory {
//! # fn default() -> Self {
//! # CountryFactory { name: String::new() }
//! # }
//! # }
//!
//! // So you can do this
//! CountryFactory::default().name("Amsterdam");
//! ```
//!
//! [`Factory`]: trait.Factory.html
//!
//! ### Builder methods for associations
//!
//! The builder methods generated for `Association` fields are a bit different. If you have a factory like:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = City,
//! table = crate::schema::cities,
//! )]
//! struct CityFactory<'a> {
//! pub name: String,
//! pub country: Association<'a, Country, CountryFactory>,
//! }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # unimplemented!()
//! # }
//! # }
//! #
//! # fn main() {}
//! ```
//!
//! You'll be able to call `country` either with an owned `CountryFactory`:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! # #[derive(Clone, Factory)]
//! # #[factory(
//! # model = City,
//! # table = crate::schema::cities,
//! # )]
//! # struct CityFactory<'a> {
//! # pub name: String,
//! # pub country: Association<'a, Country, CountryFactory>,
//! # }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # Self {
//! # name: String::new(), country: Association::default(),
//! # }
//! # }
//! # }
//! #
//! # fn main() {
//! let country_factory = CountryFactory::default();
//! CityFactory::default().country(country_factory);
//! # }
//! ```
//!
//! Or a borrowed `Country`:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! # #[derive(Clone, Factory)]
//! # #[factory(
//! # model = City,
//! # table = crate::schema::cities,
//! # )]
//! # struct CityFactory<'a> {
//! # pub name: String,
//! # pub country: Association<'a, Country, CountryFactory>,
//! # }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # Self {
//! # name: String::new(), country: Association::default(),
//! # }
//! # }
//! # }
//! #
//! # fn main() {
//! let country = Country { id: 1, name: "Denmark".into() };
//! CityFactory::default().country(&country);
//! # }
//! ```
//!
//! This should prevent bugs where you have multiple factory instances sharing some association that you mutate halfway through a test.
//!
//! ### Optional associations
//!
//! If your model has a nullable association you can do this:
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup_with_city_factory.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = User,
//! table = crate::schema::users,
//! )]
//! struct UserFactory<'a> {
//! pub name: String,
//! pub country: Option<Association<'a, Country, CountryFactory>>,
//! # pub age: i32,
//! # pub home_city: Option<Association<'a, City, CityFactory<'a>>>,
//! # pub current_city: Option<Association<'a, City, CityFactory<'a>>>,
//! }
//!
//! impl<'a> Default for UserFactory<'a> {
//! fn default() -> Self {
//! Self {
//! name: "Bob".into(),
//! country: None,
//! # age: 30,
//! # home_city: None,
//! # current_city: None,
//! }
//! }
//! }
//!
//! # fn main() {
//! // Setting `country` to a `CountryFactory`
//! let country_factory = CountryFactory::default();
//! UserFactory::default().country(Some(country_factory));
//!
//! // Setting `country` to a `Country`
//! let country = Country { id: 1, name: "Denmark".into() };
//! UserFactory::default().country(Some(&country));
//!
//! // Setting `country` to `None`
//! UserFactory::default().country(Option::<CountryFactory>::None);
//! UserFactory::default().country(Option::<&Country>::None);
//! # }
//! ```
//!
//! ### Customizing foreign key names
//!
//! You can customize the name of the foreign key for your associations like so
//!
//! ```
//! # #![allow(unused_imports)]
//! # include!("../tests/docs_setup.rs");
//! #
//! #[derive(Clone, Factory)]
//! #[factory(
//! model = City,
//! table = crate::schema::cities,
//! )]
//! struct CityFactory<'a> {
//! #[factory(foreign_key_name = country_id)]
//! pub country: Association<'a, Country, CountryFactory>,
//! # pub name: String,
//! }
//! #
//! # impl<'a> Default for CityFactory<'a> {
//! # fn default() -> Self {
//! # unimplemented!()
//! # }
//! # }
//! #
//! # fn main() {}
//! ```
#![doc(html_root_url = "https://docs.rs/diesel-factories/2.0.0")]
#![deny(
mutable_borrow_reservation_conflict,
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
use std::sync::atomic::{AtomicUsize, Ordering};
pub use diesel_factories_code_gen::Factory;
/// A "belongs to" association that may or may not have been inserted yet.
///
/// You will normally be using this when setting up "belongs to" associations between models in
/// factories.
#[derive(Debug, Clone)]
pub enum Association<'a, Model, Factory> {
/// An associated model that has been inserted into the database.
///
/// You shouldn't have to use this direclty but instead just `Association::default()`.
Model(&'a Model),
/// A factory for a model that hasn't been inserted yet into the database.
///
/// You shouldn't have to use this direclty but instead just `Association::default()`.
Factory(Factory),
}
impl<Model, Factory: Default> Default for Association<'_, Model, Factory> {
fn default() -> Self {
Association::Factory(Factory::default())
}
}
impl<'a, Model, Factory> Association<'a, Model, Factory> {
#[doc(hidden)]
pub fn new_model(inner: &'a Model) -> Self {
Association::Model(inner)
}
#[doc(hidden)]
pub fn new_factory(inner: Factory) -> Self {
Association::Factory(inner)
}
}
impl<M, F> Association<'_, M, F>
where
F: Factory<Model = M> + Clone,
{
#[doc(hidden)]
pub fn | (&self, con: &F::Connection) -> F::Id {
match self {
Association::Model(model) => F::id_for_model(&model).clone(),
Association::Factory(factory) => {
let model = factory.clone().insert(con);
F::id_for_model(&model).clone()
}
}
}
}
/// A generic factory trait.
///
/// You shouldn't ever have to implement this trait yourself. It can be derived using
/// `#[derive(Factory)]`
///
/// See the [root module docs](/) for info on how to use `#[derive(Factory)]`.
pub trait Factory: Clone {
/// The model type the factory inserts.
///
/// For a factory named `UserFactory` this would probably be `User`.
type Model;
/// The primary key type your model uses.
///
/// This will normally be i32 or i64 but can be whatever you need.
type Id: Clone;
/// The database connection type you use such as `diesel::pg::PgConnection`.
type Connection;
/// Insert the factory into the database.
///
/// # Panics
/// This will panic if the insert fails. Should be fine since you want panics early in tests.
fn insert(self, con: &Self::Connection) -> Self::Model;
/// Get the primary key value for a model type.
///
/// Just a generic wrapper around `model.id`.
fn id_for_model(model: &Self::Model) -> &Self::Id;
}
static SEQUENCE_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Utility function for generating unique ids or strings in factories.
/// Each time `sequence` gets called, the closure will receive a different number.
///
/// ```
/// use diesel_factories::sequence;
///
/// assert_ne!(
/// sequence(|i| format!("unique-string-{}", i)),
/// sequence(|i| format!("unique-string-{}", i)),
/// );
/// ```
pub fn sequence<T, F>(f: F) -> T
where
F: Fn(usize) -> T,
{
SEQUENCE_COUNTER.fetch_add(1, Ordering::SeqCst);
let count = SEQUENCE_COUNTER.load(Ordering::Relaxed);
f(count)
}
#[cfg(test)]
mod test {
#[allow(unused_imports)]
use super::*;
#[test]
fn test_compile_pass() {
let t = trybuild::TestCases::new();
t.pass("tests/compile_pass/*.rs");
t.compile_fail("tests/compile_fail/*.rs");
}
}
| insert_returning_id | identifier_name |
test_util.rs | use crate::runtime::Runtime;
use crate::{event::LogEvent, Event};
use futures::{compat::Stream01CompatExt, stream, SinkExt, Stream, StreamExt, TryStreamExt};
use futures01::{
future, stream as stream01, sync::mpsc, try_ready, Async, Future, Poll, Stream as Stream01,
};
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{
collections::HashMap,
convert::Infallible,
fs::File,
io::Read,
iter, mem,
net::{Shutdown, SocketAddr},
path::{Path, PathBuf},
sync::atomic::{AtomicUsize, Ordering},
sync::Arc,
};
use tokio::{
io::{AsyncRead, AsyncWrite, Result as IoResult},
net::{TcpListener, TcpStream},
sync::oneshot,
task::JoinHandle,
};
use tokio01::util::FutureExt;
use tokio_util::codec::{Encoder, FramedRead, FramedWrite, LinesCodec};
#[macro_export]
macro_rules! assert_downcast_matches {
($e:expr, $t:ty, $v:pat) => {{
match $e.downcast_ref::<$t>() {
Some($v) => (),
got => panic!("assertion failed: got wrong error variant {:?}", got),
}
}};
}
static NEXT_PORT: AtomicUsize = AtomicUsize::new(1234);
pub fn next_addr() -> SocketAddr {
use std::net::{IpAddr, Ipv4Addr};
let port = NEXT_PORT.fetch_add(1, Ordering::AcqRel) as u16;
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port)
}
pub fn trace_init() {
let env = std::env::var("TEST_LOG").unwrap_or_else(|_| "off".to_string());
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_env_filter(env)
.finish();
let _ = tracing_log::LogTracer::init();
let _ = tracing::dispatcher::set_global_default(tracing::Dispatch::new(subscriber));
}
pub async fn send_lines(
addr: SocketAddr,
lines: impl IntoIterator<Item = String>,
) -> Result<(), Infallible> {
send_encodable(addr, LinesCodec::new(), lines).await
}
pub async fn send_encodable<I, E: From<std::io::Error> + std::fmt::Debug>(
addr: SocketAddr,
encoder: impl Encoder<I, Error = E>,
lines: impl IntoIterator<Item = I>,
) -> Result<(), Infallible> {
let stream = TcpStream::connect(&addr).await.unwrap();
let mut sink = FramedWrite::new(stream, encoder);
let mut lines = stream::iter(lines.into_iter()).map(Ok);
sink.send_all(&mut lines).await.unwrap();
let stream = sink.get_mut();
stream.shutdown(Shutdown::Both).unwrap();
Ok(())
}
pub async fn send_lines_tls(
addr: SocketAddr,
host: String,
lines: impl Iterator<Item = String>,
) -> Result<(), Infallible> {
let stream = TcpStream::connect(&addr).await.unwrap();
let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
connector.set_verify(SslVerifyMode::NONE);
let config = connector.build().configure().unwrap();
let stream = tokio_openssl::connect(config, &host, stream).await.unwrap();
let mut sink = FramedWrite::new(stream, LinesCodec::new());
let mut lines = stream::iter(lines).map(Ok);
sink.send_all(&mut lines).await.unwrap();
let stream = sink.get_mut().get_mut();
stream.shutdown(Shutdown::Both).unwrap();
Ok(())
}
pub fn temp_file() -> PathBuf {
let path = std::env::temp_dir();
let file_name = random_string(16);
path.join(file_name + ".log")
}
pub fn temp_dir() -> PathBuf {
let path = std::env::temp_dir();
let dir_name = random_string(16);
path.join(dir_name)
}
pub fn random_lines_with_stream(
len: usize,
count: usize,
) -> (Vec<String>, impl Stream01<Item = Event, Error = ()>) {
let lines = (0..count).map(|_| random_string(len)).collect::<Vec<_>>();
let stream = stream01::iter_ok(lines.clone().into_iter().map(Event::from));
(lines, stream)
}
pub fn random_events_with_stream(
len: usize,
count: usize,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) {
random_events_with_stream_generic(count, move || Event::from(random_string(len)))
}
pub fn random_nested_events_with_stream(
len: usize,
breadth: usize,
depth: usize,
count: usize,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) {
random_events_with_stream_generic(count, move || {
let mut log = LogEvent::default();
let tree = random_pseudonested_map(len, breadth, depth);
for (k, v) in tree.into_iter() {
log.insert(k, v);
}
Event::Log(log)
})
}
pub fn random_string(len: usize) -> String {
thread_rng()
.sample_iter(&Alphanumeric)
.take(len)
.collect::<String>()
}
pub fn random_lines(len: usize) -> impl Iterator<Item = String> {
std::iter::repeat(()).map(move |_| random_string(len))
}
pub fn random_map(max_size: usize, field_len: usize) -> HashMap<String, String> {
let size = thread_rng().gen_range(0, max_size);
(0..size)
.map(move |_| (random_string(field_len), random_string(field_len)))
.collect()
}
pub fn random_maps(
max_size: usize,
field_len: usize,
) -> impl Iterator<Item = HashMap<String, String>> {
iter::repeat(()).map(move |_| random_map(max_size, field_len))
}
pub fn collect_n<T>(mut rx: mpsc::Receiver<T>, n: usize) -> impl Future<Item = Vec<T>, Error = ()> {
let mut events = Vec::new();
future::poll_fn(move || {
while events.len() < n {
let e = try_ready!(rx.poll()).unwrap();
events.push(e);
}
Ok(Async::Ready(mem::replace(&mut events, Vec::new())))
})
}
pub fn lines_from_file<P: AsRef<Path>>(path: P) -> Vec<String> {
trace!(message = "Reading file.", path = %path.as_ref().display());
let mut file = File::open(path).unwrap();
let mut output = String::new();
file.read_to_string(&mut output).unwrap();
output.lines().map(|s| s.to_owned()).collect()
}
pub fn wait_for(mut f: impl FnMut() -> bool) {
let wait = std::time::Duration::from_millis(5);
let limit = std::time::Duration::from_secs(5);
let mut attempts = 0;
while!f() {
std::thread::sleep(wait);
attempts += 1;
if attempts * wait > limit {
panic!("timed out while waiting");
}
}
}
pub fn block_on<F, R, E>(future: F) -> Result<R, E>
where
F: Send +'static + Future<Item = R, Error = E>,
R: Send +'static,
E: Send +'static,
{
let mut rt = runtime();
rt.block_on(future)
}
pub fn block_on_std<F>(future: F) -> F::Output
where
F: std::future::Future + Send +'static,
F::Output: Send +'static,
{
let mut rt = runtime();
rt.block_on_std(future)
}
pub fn runtime() -> Runtime {
Runtime::single_threaded().unwrap()
}
pub fn wait_for_tcp(addr: SocketAddr) {
wait_for(|| std::net::TcpStream::connect(addr).is_ok())
}
pub fn wait_for_atomic_usize<T, F>(val: T, unblock: F)
where
T: AsRef<AtomicUsize>,
F: Fn(usize) -> bool,
{
let val = val.as_ref();
wait_for(|| unblock(val.load(Ordering::SeqCst)))
}
pub fn shutdown_on_idle(runtime: Runtime) {
block_on(
runtime
.shutdown_on_idle()
.timeout(std::time::Duration::from_secs(10)),
)
.unwrap()
}
#[derive(Debug)]
pub struct CollectN<S>
where
S: Stream01,
{
stream: Option<S>,
remaining: usize,
items: Option<Vec<S::Item>>,
}
impl<S: Stream01> CollectN<S> {
pub fn new(s: S, n: usize) -> Self {
Self {
stream: Some(s),
remaining: n,
items: Some(Vec::new()),
}
}
}
impl<S> Future for CollectN<S>
where
S: Stream01,
{
type Item = (S, Vec<S::Item>);
type Error = S::Error;
fn poll(&mut self) -> Poll<(S, Vec<S::Item>), S::Error> {
let stream = self.stream.take();
if stream.is_none() {
panic!("Stream is missing");
}
let mut stream = stream.unwrap();
loop {
if self.remaining == 0 {
return Ok(Async::Ready((stream, self.items.take().unwrap())));
}
match stream.poll() {
Ok(Async::Ready(Some(e))) => {
self.items.as_mut().unwrap().push(e);
self.remaining -= 1;
}
Ok(Async::Ready(None)) => {
return Ok(Async::Ready((stream, self.items.take().unwrap())));
}
Ok(Async::NotReady) => {
self.stream.replace(stream);
return Ok(Async::NotReady);
}
Err(e) => {
return Err(e);
}
}
}
}
}
#[derive(Debug)]
pub struct CollectCurrent<S>
where
S: Stream01,
{
stream: Option<S>,
}
impl<S: Stream01> CollectCurrent<S> {
pub fn new(s: S) -> Self {
Self { stream: Some(s) }
}
}
impl<S> Future for CollectCurrent<S>
where
S: Stream01,
{
type Item = (S, Vec<S::Item>);
type Error = S::Error;
fn poll(&mut self) -> Poll<(S, Vec<S::Item>), S::Error> {
if let Some(mut stream) = self.stream.take() {
let mut items = vec![];
loop {
match stream.poll() {
Ok(Async::Ready(Some(e))) => items.push(e),
Ok(Async::Ready(None)) | Ok(Async::NotReady) => {
return Ok(Async::Ready((stream, items)));
}
Err(e) => {
return Err(e);
}
}
}
} else {
panic!("Future already completed");
}
}
}
pub struct CountReceiver<T> {
count: Arc<AtomicUsize>,
trigger: oneshot::Sender<()>,
handle: JoinHandle<Vec<T>>,
}
impl<T: Send +'static> CountReceiver<T> {
pub fn count(&self) -> usize {
self.count.load(Ordering::Relaxed)
}
pub async fn wait(self) -> Vec<T> {
let _ = self.trigger.send(());
self.handle.await.unwrap()
}
fn new<F, Fut>(make_fut: F) -> CountReceiver<T>
where
F: FnOnce(Arc<AtomicUsize>, oneshot::Receiver<()>) -> Fut,
Fut: std::future::Future<Output = Vec<T>> + Send +'static,
{
let count = Arc::new(AtomicUsize::new(0));
let (trigger, tripwire) = oneshot::channel();
CountReceiver {
count: Arc::clone(&count),
trigger,
handle: tokio::spawn(make_fut(count, tripwire)),
}
}
}
impl CountReceiver<String> {
pub fn receive_lines(addr: SocketAddr) -> CountReceiver<String> {
CountReceiver::new(|count, tripwire| async move {
let mut listener = TcpListener::bind(addr).await.unwrap();
CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await
})
}
#[cfg(all(feature = "tokio/uds", unix))]
pub fn receive_lines_unix<P>(path: P) -> CountReceiver<String>
where
P: AsRef<Path> + Send +'static,
|
async fn receive_lines_stream<S, T>(
stream: S,
count: Arc<AtomicUsize>,
tripwire: oneshot::Receiver<()>,
) -> Vec<String>
where
S: Stream<Item = IoResult<T>>,
T: AsyncWrite + AsyncRead,
{
stream
.take_until(tripwire)
.map_ok(|socket| FramedRead::new(socket, LinesCodec::new()))
.map(|x| x.unwrap())
.flatten()
.map(|x| x.unwrap())
.inspect(move |_| {
count.fetch_add(1, Ordering::Relaxed);
})
.collect::<Vec<String>>()
.await
}
}
impl CountReceiver<Event> {
pub fn receive_events<S>(stream: S) -> CountReceiver<Event>
where
S: Stream01<Item = Event> + Send +'static,
<S as Stream01>::Error: std::fmt::Debug,
{
CountReceiver::new(|count, tripwire| async move {
stream
.compat()
.take_until(tripwire)
.map(|x| x.unwrap())
.inspect(move |_| {
count.fetch_add(1, Ordering::Relaxed);
})
.collect::<Vec<Event>>()
.await
})
}
}
fn random_events_with_stream_generic<F>(
count: usize,
generator: F,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>)
where
F: Fn() -> Event,
{
let events = (0..count).map(|_| generator()).collect::<Vec<_>>();
let stream = stream01::iter_ok(events.clone().into_iter());
(events, stream)
}
fn random_pseudonested_map(len: usize, breadth: usize, depth: usize) -> HashMap<String, String> {
if breadth == 0 || depth == 0 {
return HashMap::new();
}
if depth == 1 {
let mut leaf = HashMap::new();
leaf.insert(random_string(len), random_string(len));
return leaf;
}
let mut tree = HashMap::new();
for _ in 0..breadth {
let prefix = random_string(len);
let subtree = random_pseudonested_map(len, breadth, depth - 1);
let subtree: HashMap<String, String> = subtree
.into_iter()
.map(|(mut key, value)| {
key.insert(0, '.');
key.insert_str(0, &prefix[..]);
(key, value)
})
.collect();
for (key, value) in subtree.into_iter() {
tree.insert(key, value);
}
}
tree
}
| {
CountReceiver::new(|count, tripwire| async move {
let mut listener = tokio::net::UnixListener::bind(path).unwrap();
CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await
})
} | identifier_body |
test_util.rs | use crate::runtime::Runtime;
use crate::{event::LogEvent, Event};
use futures::{compat::Stream01CompatExt, stream, SinkExt, Stream, StreamExt, TryStreamExt};
use futures01::{
future, stream as stream01, sync::mpsc, try_ready, Async, Future, Poll, Stream as Stream01,
};
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{
collections::HashMap,
convert::Infallible,
fs::File,
io::Read,
iter, mem,
net::{Shutdown, SocketAddr},
path::{Path, PathBuf},
sync::atomic::{AtomicUsize, Ordering},
sync::Arc,
};
use tokio::{
io::{AsyncRead, AsyncWrite, Result as IoResult},
net::{TcpListener, TcpStream},
sync::oneshot,
task::JoinHandle,
};
use tokio01::util::FutureExt;
use tokio_util::codec::{Encoder, FramedRead, FramedWrite, LinesCodec};
#[macro_export]
macro_rules! assert_downcast_matches {
($e:expr, $t:ty, $v:pat) => {{
match $e.downcast_ref::<$t>() {
Some($v) => (),
got => panic!("assertion failed: got wrong error variant {:?}", got),
}
}};
}
static NEXT_PORT: AtomicUsize = AtomicUsize::new(1234);
pub fn next_addr() -> SocketAddr {
use std::net::{IpAddr, Ipv4Addr};
let port = NEXT_PORT.fetch_add(1, Ordering::AcqRel) as u16;
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port)
}
pub fn trace_init() {
let env = std::env::var("TEST_LOG").unwrap_or_else(|_| "off".to_string());
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_env_filter(env)
.finish();
let _ = tracing_log::LogTracer::init();
let _ = tracing::dispatcher::set_global_default(tracing::Dispatch::new(subscriber));
}
pub async fn send_lines(
addr: SocketAddr,
lines: impl IntoIterator<Item = String>,
) -> Result<(), Infallible> {
send_encodable(addr, LinesCodec::new(), lines).await
}
pub async fn send_encodable<I, E: From<std::io::Error> + std::fmt::Debug>(
addr: SocketAddr,
encoder: impl Encoder<I, Error = E>,
lines: impl IntoIterator<Item = I>,
) -> Result<(), Infallible> {
let stream = TcpStream::connect(&addr).await.unwrap();
let mut sink = FramedWrite::new(stream, encoder);
let mut lines = stream::iter(lines.into_iter()).map(Ok);
sink.send_all(&mut lines).await.unwrap();
let stream = sink.get_mut();
stream.shutdown(Shutdown::Both).unwrap();
Ok(())
}
pub async fn send_lines_tls(
addr: SocketAddr,
host: String,
lines: impl Iterator<Item = String>,
) -> Result<(), Infallible> {
let stream = TcpStream::connect(&addr).await.unwrap();
let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
connector.set_verify(SslVerifyMode::NONE);
let config = connector.build().configure().unwrap();
let stream = tokio_openssl::connect(config, &host, stream).await.unwrap();
let mut sink = FramedWrite::new(stream, LinesCodec::new());
let mut lines = stream::iter(lines).map(Ok);
sink.send_all(&mut lines).await.unwrap();
let stream = sink.get_mut().get_mut();
stream.shutdown(Shutdown::Both).unwrap();
Ok(())
}
pub fn temp_file() -> PathBuf {
let path = std::env::temp_dir();
let file_name = random_string(16);
path.join(file_name + ".log")
}
pub fn temp_dir() -> PathBuf {
let path = std::env::temp_dir();
let dir_name = random_string(16);
path.join(dir_name)
}
pub fn random_lines_with_stream(
len: usize,
count: usize,
) -> (Vec<String>, impl Stream01<Item = Event, Error = ()>) {
let lines = (0..count).map(|_| random_string(len)).collect::<Vec<_>>();
let stream = stream01::iter_ok(lines.clone().into_iter().map(Event::from));
(lines, stream)
}
pub fn random_events_with_stream(
len: usize,
count: usize,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) {
random_events_with_stream_generic(count, move || Event::from(random_string(len)))
}
pub fn random_nested_events_with_stream(
len: usize,
breadth: usize,
depth: usize,
count: usize,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) {
random_events_with_stream_generic(count, move || {
let mut log = LogEvent::default();
let tree = random_pseudonested_map(len, breadth, depth);
for (k, v) in tree.into_iter() {
log.insert(k, v);
}
Event::Log(log)
})
}
pub fn random_string(len: usize) -> String {
thread_rng()
.sample_iter(&Alphanumeric)
.take(len)
.collect::<String>()
}
pub fn random_lines(len: usize) -> impl Iterator<Item = String> {
std::iter::repeat(()).map(move |_| random_string(len))
}
pub fn random_map(max_size: usize, field_len: usize) -> HashMap<String, String> {
let size = thread_rng().gen_range(0, max_size);
(0..size)
.map(move |_| (random_string(field_len), random_string(field_len)))
.collect()
}
pub fn random_maps(
max_size: usize,
field_len: usize,
) -> impl Iterator<Item = HashMap<String, String>> {
iter::repeat(()).map(move |_| random_map(max_size, field_len))
}
pub fn collect_n<T>(mut rx: mpsc::Receiver<T>, n: usize) -> impl Future<Item = Vec<T>, Error = ()> {
let mut events = Vec::new();
future::poll_fn(move || {
while events.len() < n {
let e = try_ready!(rx.poll()).unwrap();
events.push(e);
}
Ok(Async::Ready(mem::replace(&mut events, Vec::new())))
})
}
pub fn lines_from_file<P: AsRef<Path>>(path: P) -> Vec<String> {
trace!(message = "Reading file.", path = %path.as_ref().display());
let mut file = File::open(path).unwrap();
let mut output = String::new();
file.read_to_string(&mut output).unwrap();
output.lines().map(|s| s.to_owned()).collect()
}
pub fn wait_for(mut f: impl FnMut() -> bool) {
let wait = std::time::Duration::from_millis(5);
let limit = std::time::Duration::from_secs(5);
let mut attempts = 0;
while!f() {
std::thread::sleep(wait);
attempts += 1;
if attempts * wait > limit {
panic!("timed out while waiting");
}
}
}
pub fn block_on<F, R, E>(future: F) -> Result<R, E>
where
F: Send +'static + Future<Item = R, Error = E>,
R: Send +'static,
E: Send +'static,
{
let mut rt = runtime();
rt.block_on(future)
}
pub fn block_on_std<F>(future: F) -> F::Output
where
F: std::future::Future + Send +'static,
F::Output: Send +'static,
{
let mut rt = runtime();
rt.block_on_std(future)
} | pub fn wait_for_tcp(addr: SocketAddr) {
wait_for(|| std::net::TcpStream::connect(addr).is_ok())
}
pub fn wait_for_atomic_usize<T, F>(val: T, unblock: F)
where
T: AsRef<AtomicUsize>,
F: Fn(usize) -> bool,
{
let val = val.as_ref();
wait_for(|| unblock(val.load(Ordering::SeqCst)))
}
pub fn shutdown_on_idle(runtime: Runtime) {
block_on(
runtime
.shutdown_on_idle()
.timeout(std::time::Duration::from_secs(10)),
)
.unwrap()
}
#[derive(Debug)]
pub struct CollectN<S>
where
S: Stream01,
{
stream: Option<S>,
remaining: usize,
items: Option<Vec<S::Item>>,
}
impl<S: Stream01> CollectN<S> {
pub fn new(s: S, n: usize) -> Self {
Self {
stream: Some(s),
remaining: n,
items: Some(Vec::new()),
}
}
}
impl<S> Future for CollectN<S>
where
S: Stream01,
{
type Item = (S, Vec<S::Item>);
type Error = S::Error;
fn poll(&mut self) -> Poll<(S, Vec<S::Item>), S::Error> {
let stream = self.stream.take();
if stream.is_none() {
panic!("Stream is missing");
}
let mut stream = stream.unwrap();
loop {
if self.remaining == 0 {
return Ok(Async::Ready((stream, self.items.take().unwrap())));
}
match stream.poll() {
Ok(Async::Ready(Some(e))) => {
self.items.as_mut().unwrap().push(e);
self.remaining -= 1;
}
Ok(Async::Ready(None)) => {
return Ok(Async::Ready((stream, self.items.take().unwrap())));
}
Ok(Async::NotReady) => {
self.stream.replace(stream);
return Ok(Async::NotReady);
}
Err(e) => {
return Err(e);
}
}
}
}
}
#[derive(Debug)]
pub struct CollectCurrent<S>
where
S: Stream01,
{
stream: Option<S>,
}
impl<S: Stream01> CollectCurrent<S> {
pub fn new(s: S) -> Self {
Self { stream: Some(s) }
}
}
impl<S> Future for CollectCurrent<S>
where
S: Stream01,
{
type Item = (S, Vec<S::Item>);
type Error = S::Error;
fn poll(&mut self) -> Poll<(S, Vec<S::Item>), S::Error> {
if let Some(mut stream) = self.stream.take() {
let mut items = vec![];
loop {
match stream.poll() {
Ok(Async::Ready(Some(e))) => items.push(e),
Ok(Async::Ready(None)) | Ok(Async::NotReady) => {
return Ok(Async::Ready((stream, items)));
}
Err(e) => {
return Err(e);
}
}
}
} else {
panic!("Future already completed");
}
}
}
pub struct CountReceiver<T> {
count: Arc<AtomicUsize>,
trigger: oneshot::Sender<()>,
handle: JoinHandle<Vec<T>>,
}
impl<T: Send +'static> CountReceiver<T> {
pub fn count(&self) -> usize {
self.count.load(Ordering::Relaxed)
}
pub async fn wait(self) -> Vec<T> {
let _ = self.trigger.send(());
self.handle.await.unwrap()
}
fn new<F, Fut>(make_fut: F) -> CountReceiver<T>
where
F: FnOnce(Arc<AtomicUsize>, oneshot::Receiver<()>) -> Fut,
Fut: std::future::Future<Output = Vec<T>> + Send +'static,
{
let count = Arc::new(AtomicUsize::new(0));
let (trigger, tripwire) = oneshot::channel();
CountReceiver {
count: Arc::clone(&count),
trigger,
handle: tokio::spawn(make_fut(count, tripwire)),
}
}
}
impl CountReceiver<String> {
pub fn receive_lines(addr: SocketAddr) -> CountReceiver<String> {
CountReceiver::new(|count, tripwire| async move {
let mut listener = TcpListener::bind(addr).await.unwrap();
CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await
})
}
#[cfg(all(feature = "tokio/uds", unix))]
pub fn receive_lines_unix<P>(path: P) -> CountReceiver<String>
where
P: AsRef<Path> + Send +'static,
{
CountReceiver::new(|count, tripwire| async move {
let mut listener = tokio::net::UnixListener::bind(path).unwrap();
CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await
})
}
async fn receive_lines_stream<S, T>(
stream: S,
count: Arc<AtomicUsize>,
tripwire: oneshot::Receiver<()>,
) -> Vec<String>
where
S: Stream<Item = IoResult<T>>,
T: AsyncWrite + AsyncRead,
{
stream
.take_until(tripwire)
.map_ok(|socket| FramedRead::new(socket, LinesCodec::new()))
.map(|x| x.unwrap())
.flatten()
.map(|x| x.unwrap())
.inspect(move |_| {
count.fetch_add(1, Ordering::Relaxed);
})
.collect::<Vec<String>>()
.await
}
}
impl CountReceiver<Event> {
pub fn receive_events<S>(stream: S) -> CountReceiver<Event>
where
S: Stream01<Item = Event> + Send +'static,
<S as Stream01>::Error: std::fmt::Debug,
{
CountReceiver::new(|count, tripwire| async move {
stream
.compat()
.take_until(tripwire)
.map(|x| x.unwrap())
.inspect(move |_| {
count.fetch_add(1, Ordering::Relaxed);
})
.collect::<Vec<Event>>()
.await
})
}
}
fn random_events_with_stream_generic<F>(
count: usize,
generator: F,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>)
where
F: Fn() -> Event,
{
let events = (0..count).map(|_| generator()).collect::<Vec<_>>();
let stream = stream01::iter_ok(events.clone().into_iter());
(events, stream)
}
fn random_pseudonested_map(len: usize, breadth: usize, depth: usize) -> HashMap<String, String> {
if breadth == 0 || depth == 0 {
return HashMap::new();
}
if depth == 1 {
let mut leaf = HashMap::new();
leaf.insert(random_string(len), random_string(len));
return leaf;
}
let mut tree = HashMap::new();
for _ in 0..breadth {
let prefix = random_string(len);
let subtree = random_pseudonested_map(len, breadth, depth - 1);
let subtree: HashMap<String, String> = subtree
.into_iter()
.map(|(mut key, value)| {
key.insert(0, '.');
key.insert_str(0, &prefix[..]);
(key, value)
})
.collect();
for (key, value) in subtree.into_iter() {
tree.insert(key, value);
}
}
tree
} |
pub fn runtime() -> Runtime {
Runtime::single_threaded().unwrap()
}
| random_line_split |
test_util.rs | use crate::runtime::Runtime;
use crate::{event::LogEvent, Event};
use futures::{compat::Stream01CompatExt, stream, SinkExt, Stream, StreamExt, TryStreamExt};
use futures01::{
future, stream as stream01, sync::mpsc, try_ready, Async, Future, Poll, Stream as Stream01,
};
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{
collections::HashMap,
convert::Infallible,
fs::File,
io::Read,
iter, mem,
net::{Shutdown, SocketAddr},
path::{Path, PathBuf},
sync::atomic::{AtomicUsize, Ordering},
sync::Arc,
};
use tokio::{
io::{AsyncRead, AsyncWrite, Result as IoResult},
net::{TcpListener, TcpStream},
sync::oneshot,
task::JoinHandle,
};
use tokio01::util::FutureExt;
use tokio_util::codec::{Encoder, FramedRead, FramedWrite, LinesCodec};
#[macro_export]
macro_rules! assert_downcast_matches {
($e:expr, $t:ty, $v:pat) => {{
match $e.downcast_ref::<$t>() {
Some($v) => (),
got => panic!("assertion failed: got wrong error variant {:?}", got),
}
}};
}
static NEXT_PORT: AtomicUsize = AtomicUsize::new(1234);
pub fn next_addr() -> SocketAddr {
use std::net::{IpAddr, Ipv4Addr};
let port = NEXT_PORT.fetch_add(1, Ordering::AcqRel) as u16;
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port)
}
pub fn trace_init() {
let env = std::env::var("TEST_LOG").unwrap_or_else(|_| "off".to_string());
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_env_filter(env)
.finish();
let _ = tracing_log::LogTracer::init();
let _ = tracing::dispatcher::set_global_default(tracing::Dispatch::new(subscriber));
}
pub async fn send_lines(
addr: SocketAddr,
lines: impl IntoIterator<Item = String>,
) -> Result<(), Infallible> {
send_encodable(addr, LinesCodec::new(), lines).await
}
pub async fn send_encodable<I, E: From<std::io::Error> + std::fmt::Debug>(
addr: SocketAddr,
encoder: impl Encoder<I, Error = E>,
lines: impl IntoIterator<Item = I>,
) -> Result<(), Infallible> {
let stream = TcpStream::connect(&addr).await.unwrap();
let mut sink = FramedWrite::new(stream, encoder);
let mut lines = stream::iter(lines.into_iter()).map(Ok);
sink.send_all(&mut lines).await.unwrap();
let stream = sink.get_mut();
stream.shutdown(Shutdown::Both).unwrap();
Ok(())
}
pub async fn send_lines_tls(
addr: SocketAddr,
host: String,
lines: impl Iterator<Item = String>,
) -> Result<(), Infallible> {
let stream = TcpStream::connect(&addr).await.unwrap();
let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
connector.set_verify(SslVerifyMode::NONE);
let config = connector.build().configure().unwrap();
let stream = tokio_openssl::connect(config, &host, stream).await.unwrap();
let mut sink = FramedWrite::new(stream, LinesCodec::new());
let mut lines = stream::iter(lines).map(Ok);
sink.send_all(&mut lines).await.unwrap();
let stream = sink.get_mut().get_mut();
stream.shutdown(Shutdown::Both).unwrap();
Ok(())
}
pub fn temp_file() -> PathBuf {
let path = std::env::temp_dir();
let file_name = random_string(16);
path.join(file_name + ".log")
}
pub fn temp_dir() -> PathBuf {
let path = std::env::temp_dir();
let dir_name = random_string(16);
path.join(dir_name)
}
pub fn random_lines_with_stream(
len: usize,
count: usize,
) -> (Vec<String>, impl Stream01<Item = Event, Error = ()>) {
let lines = (0..count).map(|_| random_string(len)).collect::<Vec<_>>();
let stream = stream01::iter_ok(lines.clone().into_iter().map(Event::from));
(lines, stream)
}
pub fn random_events_with_stream(
len: usize,
count: usize,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) {
random_events_with_stream_generic(count, move || Event::from(random_string(len)))
}
pub fn | (
len: usize,
breadth: usize,
depth: usize,
count: usize,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) {
random_events_with_stream_generic(count, move || {
let mut log = LogEvent::default();
let tree = random_pseudonested_map(len, breadth, depth);
for (k, v) in tree.into_iter() {
log.insert(k, v);
}
Event::Log(log)
})
}
pub fn random_string(len: usize) -> String {
thread_rng()
.sample_iter(&Alphanumeric)
.take(len)
.collect::<String>()
}
pub fn random_lines(len: usize) -> impl Iterator<Item = String> {
std::iter::repeat(()).map(move |_| random_string(len))
}
pub fn random_map(max_size: usize, field_len: usize) -> HashMap<String, String> {
let size = thread_rng().gen_range(0, max_size);
(0..size)
.map(move |_| (random_string(field_len), random_string(field_len)))
.collect()
}
pub fn random_maps(
max_size: usize,
field_len: usize,
) -> impl Iterator<Item = HashMap<String, String>> {
iter::repeat(()).map(move |_| random_map(max_size, field_len))
}
pub fn collect_n<T>(mut rx: mpsc::Receiver<T>, n: usize) -> impl Future<Item = Vec<T>, Error = ()> {
let mut events = Vec::new();
future::poll_fn(move || {
while events.len() < n {
let e = try_ready!(rx.poll()).unwrap();
events.push(e);
}
Ok(Async::Ready(mem::replace(&mut events, Vec::new())))
})
}
pub fn lines_from_file<P: AsRef<Path>>(path: P) -> Vec<String> {
trace!(message = "Reading file.", path = %path.as_ref().display());
let mut file = File::open(path).unwrap();
let mut output = String::new();
file.read_to_string(&mut output).unwrap();
output.lines().map(|s| s.to_owned()).collect()
}
pub fn wait_for(mut f: impl FnMut() -> bool) {
let wait = std::time::Duration::from_millis(5);
let limit = std::time::Duration::from_secs(5);
let mut attempts = 0;
while!f() {
std::thread::sleep(wait);
attempts += 1;
if attempts * wait > limit {
panic!("timed out while waiting");
}
}
}
pub fn block_on<F, R, E>(future: F) -> Result<R, E>
where
F: Send +'static + Future<Item = R, Error = E>,
R: Send +'static,
E: Send +'static,
{
let mut rt = runtime();
rt.block_on(future)
}
pub fn block_on_std<F>(future: F) -> F::Output
where
F: std::future::Future + Send +'static,
F::Output: Send +'static,
{
let mut rt = runtime();
rt.block_on_std(future)
}
pub fn runtime() -> Runtime {
Runtime::single_threaded().unwrap()
}
pub fn wait_for_tcp(addr: SocketAddr) {
wait_for(|| std::net::TcpStream::connect(addr).is_ok())
}
pub fn wait_for_atomic_usize<T, F>(val: T, unblock: F)
where
T: AsRef<AtomicUsize>,
F: Fn(usize) -> bool,
{
let val = val.as_ref();
wait_for(|| unblock(val.load(Ordering::SeqCst)))
}
pub fn shutdown_on_idle(runtime: Runtime) {
block_on(
runtime
.shutdown_on_idle()
.timeout(std::time::Duration::from_secs(10)),
)
.unwrap()
}
#[derive(Debug)]
pub struct CollectN<S>
where
S: Stream01,
{
stream: Option<S>,
remaining: usize,
items: Option<Vec<S::Item>>,
}
impl<S: Stream01> CollectN<S> {
pub fn new(s: S, n: usize) -> Self {
Self {
stream: Some(s),
remaining: n,
items: Some(Vec::new()),
}
}
}
impl<S> Future for CollectN<S>
where
S: Stream01,
{
type Item = (S, Vec<S::Item>);
type Error = S::Error;
fn poll(&mut self) -> Poll<(S, Vec<S::Item>), S::Error> {
let stream = self.stream.take();
if stream.is_none() {
panic!("Stream is missing");
}
let mut stream = stream.unwrap();
loop {
if self.remaining == 0 {
return Ok(Async::Ready((stream, self.items.take().unwrap())));
}
match stream.poll() {
Ok(Async::Ready(Some(e))) => {
self.items.as_mut().unwrap().push(e);
self.remaining -= 1;
}
Ok(Async::Ready(None)) => {
return Ok(Async::Ready((stream, self.items.take().unwrap())));
}
Ok(Async::NotReady) => {
self.stream.replace(stream);
return Ok(Async::NotReady);
}
Err(e) => {
return Err(e);
}
}
}
}
}
#[derive(Debug)]
pub struct CollectCurrent<S>
where
S: Stream01,
{
stream: Option<S>,
}
impl<S: Stream01> CollectCurrent<S> {
pub fn new(s: S) -> Self {
Self { stream: Some(s) }
}
}
impl<S> Future for CollectCurrent<S>
where
S: Stream01,
{
type Item = (S, Vec<S::Item>);
type Error = S::Error;
fn poll(&mut self) -> Poll<(S, Vec<S::Item>), S::Error> {
if let Some(mut stream) = self.stream.take() {
let mut items = vec![];
loop {
match stream.poll() {
Ok(Async::Ready(Some(e))) => items.push(e),
Ok(Async::Ready(None)) | Ok(Async::NotReady) => {
return Ok(Async::Ready((stream, items)));
}
Err(e) => {
return Err(e);
}
}
}
} else {
panic!("Future already completed");
}
}
}
pub struct CountReceiver<T> {
count: Arc<AtomicUsize>,
trigger: oneshot::Sender<()>,
handle: JoinHandle<Vec<T>>,
}
impl<T: Send +'static> CountReceiver<T> {
pub fn count(&self) -> usize {
self.count.load(Ordering::Relaxed)
}
pub async fn wait(self) -> Vec<T> {
let _ = self.trigger.send(());
self.handle.await.unwrap()
}
fn new<F, Fut>(make_fut: F) -> CountReceiver<T>
where
F: FnOnce(Arc<AtomicUsize>, oneshot::Receiver<()>) -> Fut,
Fut: std::future::Future<Output = Vec<T>> + Send +'static,
{
let count = Arc::new(AtomicUsize::new(0));
let (trigger, tripwire) = oneshot::channel();
CountReceiver {
count: Arc::clone(&count),
trigger,
handle: tokio::spawn(make_fut(count, tripwire)),
}
}
}
impl CountReceiver<String> {
pub fn receive_lines(addr: SocketAddr) -> CountReceiver<String> {
CountReceiver::new(|count, tripwire| async move {
let mut listener = TcpListener::bind(addr).await.unwrap();
CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await
})
}
#[cfg(all(feature = "tokio/uds", unix))]
pub fn receive_lines_unix<P>(path: P) -> CountReceiver<String>
where
P: AsRef<Path> + Send +'static,
{
CountReceiver::new(|count, tripwire| async move {
let mut listener = tokio::net::UnixListener::bind(path).unwrap();
CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await
})
}
async fn receive_lines_stream<S, T>(
stream: S,
count: Arc<AtomicUsize>,
tripwire: oneshot::Receiver<()>,
) -> Vec<String>
where
S: Stream<Item = IoResult<T>>,
T: AsyncWrite + AsyncRead,
{
stream
.take_until(tripwire)
.map_ok(|socket| FramedRead::new(socket, LinesCodec::new()))
.map(|x| x.unwrap())
.flatten()
.map(|x| x.unwrap())
.inspect(move |_| {
count.fetch_add(1, Ordering::Relaxed);
})
.collect::<Vec<String>>()
.await
}
}
impl CountReceiver<Event> {
pub fn receive_events<S>(stream: S) -> CountReceiver<Event>
where
S: Stream01<Item = Event> + Send +'static,
<S as Stream01>::Error: std::fmt::Debug,
{
CountReceiver::new(|count, tripwire| async move {
stream
.compat()
.take_until(tripwire)
.map(|x| x.unwrap())
.inspect(move |_| {
count.fetch_add(1, Ordering::Relaxed);
})
.collect::<Vec<Event>>()
.await
})
}
}
fn random_events_with_stream_generic<F>(
count: usize,
generator: F,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>)
where
F: Fn() -> Event,
{
let events = (0..count).map(|_| generator()).collect::<Vec<_>>();
let stream = stream01::iter_ok(events.clone().into_iter());
(events, stream)
}
fn random_pseudonested_map(len: usize, breadth: usize, depth: usize) -> HashMap<String, String> {
if breadth == 0 || depth == 0 {
return HashMap::new();
}
if depth == 1 {
let mut leaf = HashMap::new();
leaf.insert(random_string(len), random_string(len));
return leaf;
}
let mut tree = HashMap::new();
for _ in 0..breadth {
let prefix = random_string(len);
let subtree = random_pseudonested_map(len, breadth, depth - 1);
let subtree: HashMap<String, String> = subtree
.into_iter()
.map(|(mut key, value)| {
key.insert(0, '.');
key.insert_str(0, &prefix[..]);
(key, value)
})
.collect();
for (key, value) in subtree.into_iter() {
tree.insert(key, value);
}
}
tree
}
| random_nested_events_with_stream | identifier_name |
test_util.rs | use crate::runtime::Runtime;
use crate::{event::LogEvent, Event};
use futures::{compat::Stream01CompatExt, stream, SinkExt, Stream, StreamExt, TryStreamExt};
use futures01::{
future, stream as stream01, sync::mpsc, try_ready, Async, Future, Poll, Stream as Stream01,
};
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{
collections::HashMap,
convert::Infallible,
fs::File,
io::Read,
iter, mem,
net::{Shutdown, SocketAddr},
path::{Path, PathBuf},
sync::atomic::{AtomicUsize, Ordering},
sync::Arc,
};
use tokio::{
io::{AsyncRead, AsyncWrite, Result as IoResult},
net::{TcpListener, TcpStream},
sync::oneshot,
task::JoinHandle,
};
use tokio01::util::FutureExt;
use tokio_util::codec::{Encoder, FramedRead, FramedWrite, LinesCodec};
#[macro_export]
macro_rules! assert_downcast_matches {
($e:expr, $t:ty, $v:pat) => {{
match $e.downcast_ref::<$t>() {
Some($v) => (),
got => panic!("assertion failed: got wrong error variant {:?}", got),
}
}};
}
static NEXT_PORT: AtomicUsize = AtomicUsize::new(1234);
pub fn next_addr() -> SocketAddr {
use std::net::{IpAddr, Ipv4Addr};
let port = NEXT_PORT.fetch_add(1, Ordering::AcqRel) as u16;
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port)
}
pub fn trace_init() {
let env = std::env::var("TEST_LOG").unwrap_or_else(|_| "off".to_string());
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_env_filter(env)
.finish();
let _ = tracing_log::LogTracer::init();
let _ = tracing::dispatcher::set_global_default(tracing::Dispatch::new(subscriber));
}
pub async fn send_lines(
addr: SocketAddr,
lines: impl IntoIterator<Item = String>,
) -> Result<(), Infallible> {
send_encodable(addr, LinesCodec::new(), lines).await
}
pub async fn send_encodable<I, E: From<std::io::Error> + std::fmt::Debug>(
addr: SocketAddr,
encoder: impl Encoder<I, Error = E>,
lines: impl IntoIterator<Item = I>,
) -> Result<(), Infallible> {
let stream = TcpStream::connect(&addr).await.unwrap();
let mut sink = FramedWrite::new(stream, encoder);
let mut lines = stream::iter(lines.into_iter()).map(Ok);
sink.send_all(&mut lines).await.unwrap();
let stream = sink.get_mut();
stream.shutdown(Shutdown::Both).unwrap();
Ok(())
}
pub async fn send_lines_tls(
addr: SocketAddr,
host: String,
lines: impl Iterator<Item = String>,
) -> Result<(), Infallible> {
let stream = TcpStream::connect(&addr).await.unwrap();
let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
connector.set_verify(SslVerifyMode::NONE);
let config = connector.build().configure().unwrap();
let stream = tokio_openssl::connect(config, &host, stream).await.unwrap();
let mut sink = FramedWrite::new(stream, LinesCodec::new());
let mut lines = stream::iter(lines).map(Ok);
sink.send_all(&mut lines).await.unwrap();
let stream = sink.get_mut().get_mut();
stream.shutdown(Shutdown::Both).unwrap();
Ok(())
}
pub fn temp_file() -> PathBuf {
let path = std::env::temp_dir();
let file_name = random_string(16);
path.join(file_name + ".log")
}
pub fn temp_dir() -> PathBuf {
let path = std::env::temp_dir();
let dir_name = random_string(16);
path.join(dir_name)
}
pub fn random_lines_with_stream(
len: usize,
count: usize,
) -> (Vec<String>, impl Stream01<Item = Event, Error = ()>) {
let lines = (0..count).map(|_| random_string(len)).collect::<Vec<_>>();
let stream = stream01::iter_ok(lines.clone().into_iter().map(Event::from));
(lines, stream)
}
pub fn random_events_with_stream(
len: usize,
count: usize,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) {
random_events_with_stream_generic(count, move || Event::from(random_string(len)))
}
pub fn random_nested_events_with_stream(
len: usize,
breadth: usize,
depth: usize,
count: usize,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) {
random_events_with_stream_generic(count, move || {
let mut log = LogEvent::default();
let tree = random_pseudonested_map(len, breadth, depth);
for (k, v) in tree.into_iter() {
log.insert(k, v);
}
Event::Log(log)
})
}
pub fn random_string(len: usize) -> String {
thread_rng()
.sample_iter(&Alphanumeric)
.take(len)
.collect::<String>()
}
pub fn random_lines(len: usize) -> impl Iterator<Item = String> {
std::iter::repeat(()).map(move |_| random_string(len))
}
pub fn random_map(max_size: usize, field_len: usize) -> HashMap<String, String> {
let size = thread_rng().gen_range(0, max_size);
(0..size)
.map(move |_| (random_string(field_len), random_string(field_len)))
.collect()
}
pub fn random_maps(
max_size: usize,
field_len: usize,
) -> impl Iterator<Item = HashMap<String, String>> {
iter::repeat(()).map(move |_| random_map(max_size, field_len))
}
pub fn collect_n<T>(mut rx: mpsc::Receiver<T>, n: usize) -> impl Future<Item = Vec<T>, Error = ()> {
let mut events = Vec::new();
future::poll_fn(move || {
while events.len() < n {
let e = try_ready!(rx.poll()).unwrap();
events.push(e);
}
Ok(Async::Ready(mem::replace(&mut events, Vec::new())))
})
}
pub fn lines_from_file<P: AsRef<Path>>(path: P) -> Vec<String> {
trace!(message = "Reading file.", path = %path.as_ref().display());
let mut file = File::open(path).unwrap();
let mut output = String::new();
file.read_to_string(&mut output).unwrap();
output.lines().map(|s| s.to_owned()).collect()
}
pub fn wait_for(mut f: impl FnMut() -> bool) {
let wait = std::time::Duration::from_millis(5);
let limit = std::time::Duration::from_secs(5);
let mut attempts = 0;
while!f() {
std::thread::sleep(wait);
attempts += 1;
if attempts * wait > limit {
panic!("timed out while waiting");
}
}
}
pub fn block_on<F, R, E>(future: F) -> Result<R, E>
where
F: Send +'static + Future<Item = R, Error = E>,
R: Send +'static,
E: Send +'static,
{
let mut rt = runtime();
rt.block_on(future)
}
pub fn block_on_std<F>(future: F) -> F::Output
where
F: std::future::Future + Send +'static,
F::Output: Send +'static,
{
let mut rt = runtime();
rt.block_on_std(future)
}
pub fn runtime() -> Runtime {
Runtime::single_threaded().unwrap()
}
pub fn wait_for_tcp(addr: SocketAddr) {
wait_for(|| std::net::TcpStream::connect(addr).is_ok())
}
pub fn wait_for_atomic_usize<T, F>(val: T, unblock: F)
where
T: AsRef<AtomicUsize>,
F: Fn(usize) -> bool,
{
let val = val.as_ref();
wait_for(|| unblock(val.load(Ordering::SeqCst)))
}
pub fn shutdown_on_idle(runtime: Runtime) {
block_on(
runtime
.shutdown_on_idle()
.timeout(std::time::Duration::from_secs(10)),
)
.unwrap()
}
#[derive(Debug)]
pub struct CollectN<S>
where
S: Stream01,
{
stream: Option<S>,
remaining: usize,
items: Option<Vec<S::Item>>,
}
impl<S: Stream01> CollectN<S> {
pub fn new(s: S, n: usize) -> Self {
Self {
stream: Some(s),
remaining: n,
items: Some(Vec::new()),
}
}
}
impl<S> Future for CollectN<S>
where
S: Stream01,
{
type Item = (S, Vec<S::Item>);
type Error = S::Error;
fn poll(&mut self) -> Poll<(S, Vec<S::Item>), S::Error> {
let stream = self.stream.take();
if stream.is_none() {
panic!("Stream is missing");
}
let mut stream = stream.unwrap();
loop {
if self.remaining == 0 {
return Ok(Async::Ready((stream, self.items.take().unwrap())));
}
match stream.poll() {
Ok(Async::Ready(Some(e))) => {
self.items.as_mut().unwrap().push(e);
self.remaining -= 1;
}
Ok(Async::Ready(None)) => {
return Ok(Async::Ready((stream, self.items.take().unwrap())));
}
Ok(Async::NotReady) => {
self.stream.replace(stream);
return Ok(Async::NotReady);
}
Err(e) => {
return Err(e);
}
}
}
}
}
#[derive(Debug)]
pub struct CollectCurrent<S>
where
S: Stream01,
{
stream: Option<S>,
}
impl<S: Stream01> CollectCurrent<S> {
pub fn new(s: S) -> Self {
Self { stream: Some(s) }
}
}
impl<S> Future for CollectCurrent<S>
where
S: Stream01,
{
type Item = (S, Vec<S::Item>);
type Error = S::Error;
fn poll(&mut self) -> Poll<(S, Vec<S::Item>), S::Error> {
if let Some(mut stream) = self.stream.take() {
let mut items = vec![];
loop {
match stream.poll() {
Ok(Async::Ready(Some(e))) => items.push(e),
Ok(Async::Ready(None)) | Ok(Async::NotReady) => {
return Ok(Async::Ready((stream, items)));
}
Err(e) => {
return Err(e);
}
}
}
} else |
}
}
pub struct CountReceiver<T> {
count: Arc<AtomicUsize>,
trigger: oneshot::Sender<()>,
handle: JoinHandle<Vec<T>>,
}
impl<T: Send +'static> CountReceiver<T> {
pub fn count(&self) -> usize {
self.count.load(Ordering::Relaxed)
}
pub async fn wait(self) -> Vec<T> {
let _ = self.trigger.send(());
self.handle.await.unwrap()
}
fn new<F, Fut>(make_fut: F) -> CountReceiver<T>
where
F: FnOnce(Arc<AtomicUsize>, oneshot::Receiver<()>) -> Fut,
Fut: std::future::Future<Output = Vec<T>> + Send +'static,
{
let count = Arc::new(AtomicUsize::new(0));
let (trigger, tripwire) = oneshot::channel();
CountReceiver {
count: Arc::clone(&count),
trigger,
handle: tokio::spawn(make_fut(count, tripwire)),
}
}
}
impl CountReceiver<String> {
pub fn receive_lines(addr: SocketAddr) -> CountReceiver<String> {
CountReceiver::new(|count, tripwire| async move {
let mut listener = TcpListener::bind(addr).await.unwrap();
CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await
})
}
#[cfg(all(feature = "tokio/uds", unix))]
pub fn receive_lines_unix<P>(path: P) -> CountReceiver<String>
where
P: AsRef<Path> + Send +'static,
{
CountReceiver::new(|count, tripwire| async move {
let mut listener = tokio::net::UnixListener::bind(path).unwrap();
CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await
})
}
async fn receive_lines_stream<S, T>(
stream: S,
count: Arc<AtomicUsize>,
tripwire: oneshot::Receiver<()>,
) -> Vec<String>
where
S: Stream<Item = IoResult<T>>,
T: AsyncWrite + AsyncRead,
{
stream
.take_until(tripwire)
.map_ok(|socket| FramedRead::new(socket, LinesCodec::new()))
.map(|x| x.unwrap())
.flatten()
.map(|x| x.unwrap())
.inspect(move |_| {
count.fetch_add(1, Ordering::Relaxed);
})
.collect::<Vec<String>>()
.await
}
}
impl CountReceiver<Event> {
pub fn receive_events<S>(stream: S) -> CountReceiver<Event>
where
S: Stream01<Item = Event> + Send +'static,
<S as Stream01>::Error: std::fmt::Debug,
{
CountReceiver::new(|count, tripwire| async move {
stream
.compat()
.take_until(tripwire)
.map(|x| x.unwrap())
.inspect(move |_| {
count.fetch_add(1, Ordering::Relaxed);
})
.collect::<Vec<Event>>()
.await
})
}
}
fn random_events_with_stream_generic<F>(
count: usize,
generator: F,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>)
where
F: Fn() -> Event,
{
let events = (0..count).map(|_| generator()).collect::<Vec<_>>();
let stream = stream01::iter_ok(events.clone().into_iter());
(events, stream)
}
fn random_pseudonested_map(len: usize, breadth: usize, depth: usize) -> HashMap<String, String> {
if breadth == 0 || depth == 0 {
return HashMap::new();
}
if depth == 1 {
let mut leaf = HashMap::new();
leaf.insert(random_string(len), random_string(len));
return leaf;
}
let mut tree = HashMap::new();
for _ in 0..breadth {
let prefix = random_string(len);
let subtree = random_pseudonested_map(len, breadth, depth - 1);
let subtree: HashMap<String, String> = subtree
.into_iter()
.map(|(mut key, value)| {
key.insert(0, '.');
key.insert_str(0, &prefix[..]);
(key, value)
})
.collect();
for (key, value) in subtree.into_iter() {
tree.insert(key, value);
}
}
tree
}
| {
panic!("Future already completed");
} | conditional_block |
model.rs | use chrono::{DateTime, Utc};
use failure::{format_err, Error};
use serde::{Deserialize, Serialize};
use std::{borrow::Borrow, convert::TryFrom, fmt};
#[derive(Debug, Default)]
pub struct Root {
pub channel_url: Option<String>,
pub cache_url: Option<String>,
pub git_revision: Option<String>,
pub fetch_time: Option<DateTime<Utc>>,
pub status: RootStatus,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RootStatus {
Pending,
Downloading,
Available,
}
impl Default for RootStatus {
fn default() -> Self {
Self::Pending
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Nar {
pub store_path: StorePath,
pub meta: NarMeta,
pub references: String,
}
// https://github.com/NixOS/nix/blob/61e816217bfdfffd39c130c7cd24f07e640098fc/src/libstore/schema.sql
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NarMeta {
pub url: String,
pub compression: Option<String>,
pub file_hash: Option<String>,
pub file_size: Option<u64>,
pub nar_hash: String,
pub nar_size: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub deriver: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sig: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ca: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum NarStatus {
Pending,
Available,
Trashed,
}
impl Default for NarStatus {
fn default() -> Self {
Self::Pending
}
}
impl Nar {
fn ref_paths(&self) -> impl Iterator<Item = Result<StorePath, Error>> + '_ {
// Yield nothing on empty string.
self.references.split_terminator(" ").map(move |basename| {
StorePath::try_from(format!("{}/{}", self.store_path.root(), basename))
})
}
pub fn ref_hashes(&self) -> impl Iterator<Item = Result<StorePathHash, Error>> + '_ {
self.ref_paths().map(|r| r.map(|path| path.hash()))
}
pub fn format_nar_info<'a>(&'a self) -> impl fmt::Display + 'a {
struct Fmt<'a>(&'a Nar);
impl fmt::Display for Fmt<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (nar, meta) = (&self.0, &self.0.meta);
write!(f, "StorePath: {}\n", nar.store_path)?;
write!(f, "URL: {}\n", meta.url)?;
if let Some(comp) = &meta.compression {
write!(f, "Compression: {}\n", comp)?;
}
if let Some(hash) = &meta.file_hash {
write!(f, "FileHash: {}\n", hash)?;
}
if let Some(size) = &meta.file_size {
write!(f, "FileSize: {}\n", size)?;
}
write!(f, "NarHash: {}\n", meta.nar_hash)?;
write!(f, "NarSize: {}\n", meta.nar_size)?;
write!(f, "References: {}\n", nar.references)?;
if let Some(sig) = &meta.sig {
write!(f, "Sig: {}\n", sig)?;
}
if let Some(deriver) = &meta.deriver {
write!(f, "Deriver: {}\n", deriver)?;
}
if let Some(ca) = &meta.ca {
write!(f, "CA: {}\n", ca)?;
}
Ok(())
}
}
Fmt(self)
}
pub fn parse_nar_info(info: &str) -> Result<Self, Error> {
Self::parse_nar_info_inner(info).map_err(|err| format_err!("Invalid narinfo: {}", err))
}
fn parse_nar_info_inner(info: &str) -> Result<Self, &'static str> {
let (
mut store_path,
mut url,
mut compression,
mut file_hash,
mut file_size,
mut nar_hash,
mut nar_size,
mut references,
mut deriver,
mut sig,
mut ca,
) = Default::default();
for line in info.lines() {
if line.is_empty() {
continue;
}
let sep = line.find(": ").ok_or("Missing colon")?;
let (k, v) = (&line[..sep], &line[sep + 2..]);
match k {
"StorePath" => {
store_path = Some(StorePath::try_from(v).map_err(|_| "Invalid StorePath")?);
}
"URL" => url = Some(v),
"Compression" => compression = Some(v),
"FileHash" => file_hash = Some(v),
"FileSize" => file_size = Some(v.parse().map_err(|_| "Invalid FileSize")?),
"NarHash" => nar_hash = Some(v),
"NarSize" => nar_size = Some(v.parse().map_err(|_| "Invalid NarSize")?),
"References" => references = Some(v),
"Deriver" => deriver = Some(v),
"Sig" => sig = Some(v),
"CA" => ca = Some(v),
_ => return Err("Unknown field"),
}
}
Ok(Nar {
store_path: store_path.ok_or("Missing StorePath")?,
meta: NarMeta {
compression: compression.map(|s| s.to_owned()),
url: url.ok_or("Missing URL")?.to_owned(),
file_hash: file_hash.map(|s| s.to_owned()),
file_size: file_size,
nar_hash: nar_hash.ok_or("Missing NarHash")?.to_owned(),
nar_size: nar_size.ok_or("Missing NarSize")?,
deriver: deriver.map(|s| s.to_owned()),
sig: sig.map(|s| s.to_owned()),
ca: ca.map(|s| s.to_owned()),
},
references: references.ok_or("Missing References")?.to_owned(),
})
}
}
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct StorePathHash([u8; Self::LEN]);
impl StorePathHash {
pub const LEN: usize = 32;
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0).unwrap()
}
}
impl fmt::Display for StorePathHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl fmt::Debug for StorePathHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("StorePathHash")
.field(&self.to_string())
.finish()
}
}
impl Borrow<[u8]> for StorePathHash {
fn borrow(&self) -> &[u8] {
&self.0
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct StorePath {
path: String,
}
// FIXME: Allow non-default store root.
impl StorePath {
const STORE_PREFIX: &'static str = "/nix/store/";
const SEP_POS: usize = Self::STORE_PREFIX.len() + StorePathHash::LEN;
const MIN_LEN: usize = Self::SEP_POS + 1 + 1;
const MAX_LEN: usize = 212;
pub fn path(&self) -> &str {
&self.path
}
pub fn root(&self) -> &str {
&Self::STORE_PREFIX[..Self::STORE_PREFIX.len() - 1]
}
pub fn hash_str(&self) -> &str {
&self.path[Self::STORE_PREFIX.len()..Self::SEP_POS]
}
pub fn | (&self) -> StorePathHash {
StorePathHash(
<[u8; StorePathHash::LEN]>::try_from(
self.path[Self::STORE_PREFIX.len()..Self::SEP_POS].as_bytes(),
)
.unwrap(),
)
}
pub fn name(&self) -> &str {
&self.path[Self::SEP_POS + 1..]
}
}
impl TryFrom<String> for StorePath {
type Error = Error;
// https://github.com/NixOS/nix/blob/abb8ef619ba2fab3ae16fb5b5430215905bac723/src/libstore/store-api.cc#L85
fn try_from(path: String) -> Result<Self, Self::Error> {
use failure::ensure;
fn is_valid_hash(s: &[u8]) -> bool {
s.iter().all(|&b| match b {
b'e' | b'o' | b'u' | b't' => false,
b'a'..=b'z' | b'0'..=b'9' => true,
_ => false,
})
}
fn is_valid_name(s: &[u8]) -> bool {
const VALID_CHARS: &[u8] = b"+-._?=";
s.iter()
.all(|&b| b.is_ascii_alphanumeric() || VALID_CHARS.contains(&b))
}
ensure!(
Self::MIN_LEN <= path.len() && path.len() <= Self::MAX_LEN,
"Length {} is not in range [{}, {}]",
path.len(),
Self::MIN_LEN,
Self::MAX_LEN,
);
ensure!(path.is_ascii(), "Not ascii string: {}", path);
ensure!(
path.as_bytes()[Self::SEP_POS] == b'-',
"Hash seperator `-` not found",
);
let hash = &path[Self::STORE_PREFIX.len()..Self::SEP_POS];
let name = &path[Self::SEP_POS + 1..];
ensure!(is_valid_hash(hash.as_bytes()), "Invalid hash '{}'", hash);
ensure!(is_valid_name(name.as_bytes()), "Invalid name '{}'", name);
// Already checked
Ok(Self {
path: path.to_owned(),
})
}
}
impl TryFrom<&'_ str> for StorePath {
type Error = Error;
fn try_from(path: &'_ str) -> Result<Self, Self::Error> {
Self::try_from(path.to_owned())
}
}
impl fmt::Display for StorePath {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.path(), f)
}
}
#[cfg(test)]
mod tests {
use super::*;
use insta::assert_snapshot;
#[test]
fn test_nar_info_format() {
let mut nar = Nar {
store_path: StorePath::try_from(
"/nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10",
)
.unwrap(),
meta: NarMeta {
url: "some/url".to_owned(),
compression: Some("xz".to_owned()),
file_hash: Some("file:hash".to_owned()),
file_size: Some(123),
nar_hash: "nar:hash".to_owned(),
nar_size: 456,
deriver: Some("some.drv".to_owned()),
sig: Some("s:i/g 2".to_owned()),
ca: Some("fixed:hash".to_owned()),
},
references: "ref1 ref2".to_owned(),
};
assert_snapshot!(nar.format_nar_info().to_string(), @r###"
StorePath: /nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10
URL: some/url
Compression: xz
FileHash: file:hash
FileSize: 123
NarHash: nar:hash
NarSize: 456
References: ref1 ref2
Sig: s:i/g 2
Deriver: some.drv
CA: fixed:hash
"###);
nar.references = String::new();
nar.meta.deriver = None;
nar.meta.ca = None;
assert_snapshot!(nar.format_nar_info().to_string(), @r###"
StorePath: /nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10
URL: some/url
Compression: xz
FileHash: file:hash
FileSize: 123
NarHash: nar:hash
NarSize: 456
References:
Sig: s:i/g 2
"###);
}
#[test]
fn test_nar_info_parse() {
let raw = r###"
StorePath: /nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10
URL: some/url
Compression: xz
FileHash: file:hash
FileSize: 123
NarHash: nar:hash
NarSize: 456
References: ref1 ref2
Sig: s:i/g 2
Deriver: some.drv
CA: fixed:hash
"###;
let nar = Nar {
store_path: StorePath::try_from(
"/nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10",
)
.unwrap(),
meta: NarMeta {
url: "some/url".to_owned(),
compression: Some("xz".to_owned()),
file_hash: Some("file:hash".to_owned()),
file_size: Some(123),
nar_hash: "nar:hash".to_owned(),
nar_size: 456,
deriver: Some("some.drv".to_owned()),
sig: Some("s:i/g 2".to_owned()),
ca: Some("fixed:hash".to_owned()),
},
references: "ref1 ref2".to_owned(),
};
assert_eq!(Nar::parse_nar_info(raw).unwrap(), nar);
}
}
| hash | identifier_name |
model.rs | use chrono::{DateTime, Utc};
use failure::{format_err, Error};
use serde::{Deserialize, Serialize};
use std::{borrow::Borrow, convert::TryFrom, fmt};
#[derive(Debug, Default)]
pub struct Root {
pub channel_url: Option<String>,
pub cache_url: Option<String>,
pub git_revision: Option<String>,
pub fetch_time: Option<DateTime<Utc>>,
pub status: RootStatus,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RootStatus {
Pending,
Downloading,
Available,
}
impl Default for RootStatus {
fn default() -> Self {
Self::Pending
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Nar {
pub store_path: StorePath,
pub meta: NarMeta,
pub references: String,
}
// https://github.com/NixOS/nix/blob/61e816217bfdfffd39c130c7cd24f07e640098fc/src/libstore/schema.sql
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NarMeta {
pub url: String,
pub compression: Option<String>,
pub file_hash: Option<String>,
pub file_size: Option<u64>,
pub nar_hash: String,
pub nar_size: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub deriver: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sig: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ca: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum NarStatus {
Pending,
Available,
Trashed,
}
impl Default for NarStatus {
fn default() -> Self {
Self::Pending
}
}
impl Nar {
fn ref_paths(&self) -> impl Iterator<Item = Result<StorePath, Error>> + '_ {
// Yield nothing on empty string.
self.references.split_terminator(" ").map(move |basename| {
StorePath::try_from(format!("{}/{}", self.store_path.root(), basename))
})
}
pub fn ref_hashes(&self) -> impl Iterator<Item = Result<StorePathHash, Error>> + '_ {
self.ref_paths().map(|r| r.map(|path| path.hash()))
}
pub fn format_nar_info<'a>(&'a self) -> impl fmt::Display + 'a {
struct Fmt<'a>(&'a Nar);
impl fmt::Display for Fmt<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (nar, meta) = (&self.0, &self.0.meta);
write!(f, "StorePath: {}\n", nar.store_path)?;
write!(f, "URL: {}\n", meta.url)?;
if let Some(comp) = &meta.compression {
write!(f, "Compression: {}\n", comp)?;
}
if let Some(hash) = &meta.file_hash {
write!(f, "FileHash: {}\n", hash)?;
}
if let Some(size) = &meta.file_size {
write!(f, "FileSize: {}\n", size)?;
}
write!(f, "NarHash: {}\n", meta.nar_hash)?;
write!(f, "NarSize: {}\n", meta.nar_size)?;
write!(f, "References: {}\n", nar.references)?;
if let Some(sig) = &meta.sig {
write!(f, "Sig: {}\n", sig)?;
}
if let Some(deriver) = &meta.deriver {
write!(f, "Deriver: {}\n", deriver)?;
}
if let Some(ca) = &meta.ca {
write!(f, "CA: {}\n", ca)?;
}
Ok(())
}
}
Fmt(self)
}
pub fn parse_nar_info(info: &str) -> Result<Self, Error> {
Self::parse_nar_info_inner(info).map_err(|err| format_err!("Invalid narinfo: {}", err))
}
fn parse_nar_info_inner(info: &str) -> Result<Self, &'static str> {
let (
mut store_path,
mut url,
mut compression,
mut file_hash,
mut file_size,
mut nar_hash,
mut nar_size,
mut references,
mut deriver,
mut sig,
mut ca,
) = Default::default();
for line in info.lines() {
if line.is_empty() {
continue;
}
let sep = line.find(": ").ok_or("Missing colon")?;
let (k, v) = (&line[..sep], &line[sep + 2..]);
match k {
"StorePath" => {
store_path = Some(StorePath::try_from(v).map_err(|_| "Invalid StorePath")?);
}
"URL" => url = Some(v),
"Compression" => compression = Some(v),
"FileHash" => file_hash = Some(v),
"FileSize" => file_size = Some(v.parse().map_err(|_| "Invalid FileSize")?),
"NarHash" => nar_hash = Some(v),
"NarSize" => nar_size = Some(v.parse().map_err(|_| "Invalid NarSize")?),
"References" => references = Some(v),
"Deriver" => deriver = Some(v),
"Sig" => sig = Some(v),
"CA" => ca = Some(v),
_ => return Err("Unknown field"),
}
}
Ok(Nar {
store_path: store_path.ok_or("Missing StorePath")?,
meta: NarMeta {
compression: compression.map(|s| s.to_owned()),
url: url.ok_or("Missing URL")?.to_owned(),
file_hash: file_hash.map(|s| s.to_owned()),
file_size: file_size,
nar_hash: nar_hash.ok_or("Missing NarHash")?.to_owned(),
nar_size: nar_size.ok_or("Missing NarSize")?,
deriver: deriver.map(|s| s.to_owned()),
sig: sig.map(|s| s.to_owned()),
ca: ca.map(|s| s.to_owned()),
},
references: references.ok_or("Missing References")?.to_owned(),
})
}
}
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct StorePathHash([u8; Self::LEN]);
impl StorePathHash {
pub const LEN: usize = 32;
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0).unwrap()
}
}
impl fmt::Display for StorePathHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl fmt::Debug for StorePathHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("StorePathHash")
.field(&self.to_string())
.finish()
}
}
impl Borrow<[u8]> for StorePathHash {
fn borrow(&self) -> &[u8] {
&self.0
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct StorePath {
path: String,
}
// FIXME: Allow non-default store root.
impl StorePath {
const STORE_PREFIX: &'static str = "/nix/store/";
const SEP_POS: usize = Self::STORE_PREFIX.len() + StorePathHash::LEN;
const MIN_LEN: usize = Self::SEP_POS + 1 + 1;
const MAX_LEN: usize = 212;
pub fn path(&self) -> &str |
pub fn root(&self) -> &str {
&Self::STORE_PREFIX[..Self::STORE_PREFIX.len() - 1]
}
pub fn hash_str(&self) -> &str {
&self.path[Self::STORE_PREFIX.len()..Self::SEP_POS]
}
pub fn hash(&self) -> StorePathHash {
StorePathHash(
<[u8; StorePathHash::LEN]>::try_from(
self.path[Self::STORE_PREFIX.len()..Self::SEP_POS].as_bytes(),
)
.unwrap(),
)
}
pub fn name(&self) -> &str {
&self.path[Self::SEP_POS + 1..]
}
}
impl TryFrom<String> for StorePath {
type Error = Error;
// https://github.com/NixOS/nix/blob/abb8ef619ba2fab3ae16fb5b5430215905bac723/src/libstore/store-api.cc#L85
fn try_from(path: String) -> Result<Self, Self::Error> {
use failure::ensure;
fn is_valid_hash(s: &[u8]) -> bool {
s.iter().all(|&b| match b {
b'e' | b'o' | b'u' | b't' => false,
b'a'..=b'z' | b'0'..=b'9' => true,
_ => false,
})
}
fn is_valid_name(s: &[u8]) -> bool {
const VALID_CHARS: &[u8] = b"+-._?=";
s.iter()
.all(|&b| b.is_ascii_alphanumeric() || VALID_CHARS.contains(&b))
}
ensure!(
Self::MIN_LEN <= path.len() && path.len() <= Self::MAX_LEN,
"Length {} is not in range [{}, {}]",
path.len(),
Self::MIN_LEN,
Self::MAX_LEN,
);
ensure!(path.is_ascii(), "Not ascii string: {}", path);
ensure!(
path.as_bytes()[Self::SEP_POS] == b'-',
"Hash seperator `-` not found",
);
let hash = &path[Self::STORE_PREFIX.len()..Self::SEP_POS];
let name = &path[Self::SEP_POS + 1..];
ensure!(is_valid_hash(hash.as_bytes()), "Invalid hash '{}'", hash);
ensure!(is_valid_name(name.as_bytes()), "Invalid name '{}'", name);
// Already checked
Ok(Self {
path: path.to_owned(),
})
}
}
impl TryFrom<&'_ str> for StorePath {
type Error = Error;
fn try_from(path: &'_ str) -> Result<Self, Self::Error> {
Self::try_from(path.to_owned())
}
}
impl fmt::Display for StorePath {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.path(), f)
}
}
#[cfg(test)]
mod tests {
use super::*;
use insta::assert_snapshot;
#[test]
fn test_nar_info_format() {
let mut nar = Nar {
store_path: StorePath::try_from(
"/nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10",
)
.unwrap(),
meta: NarMeta {
url: "some/url".to_owned(),
compression: Some("xz".to_owned()),
file_hash: Some("file:hash".to_owned()),
file_size: Some(123),
nar_hash: "nar:hash".to_owned(),
nar_size: 456,
deriver: Some("some.drv".to_owned()),
sig: Some("s:i/g 2".to_owned()),
ca: Some("fixed:hash".to_owned()),
},
references: "ref1 ref2".to_owned(),
};
assert_snapshot!(nar.format_nar_info().to_string(), @r###"
StorePath: /nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10
URL: some/url
Compression: xz
FileHash: file:hash
FileSize: 123
NarHash: nar:hash
NarSize: 456
References: ref1 ref2
Sig: s:i/g 2
Deriver: some.drv
CA: fixed:hash
"###);
nar.references = String::new();
nar.meta.deriver = None;
nar.meta.ca = None;
assert_snapshot!(nar.format_nar_info().to_string(), @r###"
StorePath: /nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10
URL: some/url
Compression: xz
FileHash: file:hash
FileSize: 123
NarHash: nar:hash
NarSize: 456
References:
Sig: s:i/g 2
"###);
}
#[test]
fn test_nar_info_parse() {
let raw = r###"
StorePath: /nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10
URL: some/url
Compression: xz
FileHash: file:hash
FileSize: 123
NarHash: nar:hash
NarSize: 456
References: ref1 ref2
Sig: s:i/g 2
Deriver: some.drv
CA: fixed:hash
"###;
let nar = Nar {
store_path: StorePath::try_from(
"/nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10",
)
.unwrap(),
meta: NarMeta {
url: "some/url".to_owned(),
compression: Some("xz".to_owned()),
file_hash: Some("file:hash".to_owned()),
file_size: Some(123),
nar_hash: "nar:hash".to_owned(),
nar_size: 456,
deriver: Some("some.drv".to_owned()),
sig: Some("s:i/g 2".to_owned()),
ca: Some("fixed:hash".to_owned()),
},
references: "ref1 ref2".to_owned(),
};
assert_eq!(Nar::parse_nar_info(raw).unwrap(), nar);
}
}
| {
&self.path
} | identifier_body |
model.rs | use chrono::{DateTime, Utc};
use failure::{format_err, Error};
use serde::{Deserialize, Serialize};
use std::{borrow::Borrow, convert::TryFrom, fmt};
#[derive(Debug, Default)]
pub struct Root {
pub channel_url: Option<String>,
pub cache_url: Option<String>,
pub git_revision: Option<String>,
pub fetch_time: Option<DateTime<Utc>>,
pub status: RootStatus,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RootStatus {
Pending,
Downloading,
Available,
}
impl Default for RootStatus {
fn default() -> Self {
Self::Pending
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Nar {
pub store_path: StorePath,
pub meta: NarMeta,
pub references: String,
}
// https://github.com/NixOS/nix/blob/61e816217bfdfffd39c130c7cd24f07e640098fc/src/libstore/schema.sql
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NarMeta {
pub url: String,
pub compression: Option<String>,
pub file_hash: Option<String>,
pub file_size: Option<u64>,
pub nar_hash: String,
pub nar_size: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub deriver: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sig: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ca: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum NarStatus {
Pending,
Available,
Trashed,
}
impl Default for NarStatus {
fn default() -> Self {
Self::Pending
}
}
impl Nar {
fn ref_paths(&self) -> impl Iterator<Item = Result<StorePath, Error>> + '_ {
// Yield nothing on empty string.
self.references.split_terminator(" ").map(move |basename| {
StorePath::try_from(format!("{}/{}", self.store_path.root(), basename))
})
}
pub fn ref_hashes(&self) -> impl Iterator<Item = Result<StorePathHash, Error>> + '_ {
self.ref_paths().map(|r| r.map(|path| path.hash()))
}
pub fn format_nar_info<'a>(&'a self) -> impl fmt::Display + 'a {
struct Fmt<'a>(&'a Nar);
impl fmt::Display for Fmt<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (nar, meta) = (&self.0, &self.0.meta);
write!(f, "StorePath: {}\n", nar.store_path)?;
write!(f, "URL: {}\n", meta.url)?;
if let Some(comp) = &meta.compression {
write!(f, "Compression: {}\n", comp)?;
}
if let Some(hash) = &meta.file_hash {
write!(f, "FileHash: {}\n", hash)?;
}
if let Some(size) = &meta.file_size {
write!(f, "FileSize: {}\n", size)?;
}
write!(f, "NarHash: {}\n", meta.nar_hash)?;
write!(f, "NarSize: {}\n", meta.nar_size)?;
write!(f, "References: {}\n", nar.references)?;
if let Some(sig) = &meta.sig {
write!(f, "Sig: {}\n", sig)?;
}
if let Some(deriver) = &meta.deriver {
write!(f, "Deriver: {}\n", deriver)?;
}
if let Some(ca) = &meta.ca {
write!(f, "CA: {}\n", ca)?;
}
Ok(())
}
}
Fmt(self)
}
pub fn parse_nar_info(info: &str) -> Result<Self, Error> {
Self::parse_nar_info_inner(info).map_err(|err| format_err!("Invalid narinfo: {}", err))
}
fn parse_nar_info_inner(info: &str) -> Result<Self, &'static str> {
let (
mut store_path,
mut url,
mut compression,
mut file_hash,
mut file_size,
mut nar_hash,
mut nar_size,
mut references,
mut deriver,
mut sig,
mut ca,
) = Default::default();
for line in info.lines() {
if line.is_empty() {
continue;
}
let sep = line.find(": ").ok_or("Missing colon")?;
let (k, v) = (&line[..sep], &line[sep + 2..]);
match k {
"StorePath" => {
store_path = Some(StorePath::try_from(v).map_err(|_| "Invalid StorePath")?);
}
"URL" => url = Some(v),
"Compression" => compression = Some(v),
"FileHash" => file_hash = Some(v),
"FileSize" => file_size = Some(v.parse().map_err(|_| "Invalid FileSize")?),
"NarHash" => nar_hash = Some(v),
"NarSize" => nar_size = Some(v.parse().map_err(|_| "Invalid NarSize")?),
"References" => references = Some(v),
"Deriver" => deriver = Some(v),
"Sig" => sig = Some(v),
"CA" => ca = Some(v),
_ => return Err("Unknown field"),
}
}
Ok(Nar {
store_path: store_path.ok_or("Missing StorePath")?,
meta: NarMeta {
compression: compression.map(|s| s.to_owned()),
url: url.ok_or("Missing URL")?.to_owned(),
file_hash: file_hash.map(|s| s.to_owned()),
file_size: file_size,
nar_hash: nar_hash.ok_or("Missing NarHash")?.to_owned(),
nar_size: nar_size.ok_or("Missing NarSize")?,
deriver: deriver.map(|s| s.to_owned()),
sig: sig.map(|s| s.to_owned()),
ca: ca.map(|s| s.to_owned()),
},
references: references.ok_or("Missing References")?.to_owned(),
})
}
}
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct StorePathHash([u8; Self::LEN]);
impl StorePathHash {
pub const LEN: usize = 32;
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0).unwrap()
}
}
impl fmt::Display for StorePathHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl fmt::Debug for StorePathHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("StorePathHash")
.field(&self.to_string())
.finish()
}
}
impl Borrow<[u8]> for StorePathHash {
fn borrow(&self) -> &[u8] {
&self.0
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct StorePath {
path: String,
}
// FIXME: Allow non-default store root.
impl StorePath {
const STORE_PREFIX: &'static str = "/nix/store/";
const SEP_POS: usize = Self::STORE_PREFIX.len() + StorePathHash::LEN;
const MIN_LEN: usize = Self::SEP_POS + 1 + 1;
const MAX_LEN: usize = 212;
pub fn path(&self) -> &str {
&self.path
}
pub fn root(&self) -> &str {
&Self::STORE_PREFIX[..Self::STORE_PREFIX.len() - 1]
}
pub fn hash_str(&self) -> &str {
&self.path[Self::STORE_PREFIX.len()..Self::SEP_POS]
}
pub fn hash(&self) -> StorePathHash {
StorePathHash(
<[u8; StorePathHash::LEN]>::try_from(
self.path[Self::STORE_PREFIX.len()..Self::SEP_POS].as_bytes(),
)
.unwrap(),
) | }
}
impl TryFrom<String> for StorePath {
type Error = Error;
// https://github.com/NixOS/nix/blob/abb8ef619ba2fab3ae16fb5b5430215905bac723/src/libstore/store-api.cc#L85
fn try_from(path: String) -> Result<Self, Self::Error> {
use failure::ensure;
fn is_valid_hash(s: &[u8]) -> bool {
s.iter().all(|&b| match b {
b'e' | b'o' | b'u' | b't' => false,
b'a'..=b'z' | b'0'..=b'9' => true,
_ => false,
})
}
fn is_valid_name(s: &[u8]) -> bool {
const VALID_CHARS: &[u8] = b"+-._?=";
s.iter()
.all(|&b| b.is_ascii_alphanumeric() || VALID_CHARS.contains(&b))
}
ensure!(
Self::MIN_LEN <= path.len() && path.len() <= Self::MAX_LEN,
"Length {} is not in range [{}, {}]",
path.len(),
Self::MIN_LEN,
Self::MAX_LEN,
);
ensure!(path.is_ascii(), "Not ascii string: {}", path);
ensure!(
path.as_bytes()[Self::SEP_POS] == b'-',
"Hash seperator `-` not found",
);
let hash = &path[Self::STORE_PREFIX.len()..Self::SEP_POS];
let name = &path[Self::SEP_POS + 1..];
ensure!(is_valid_hash(hash.as_bytes()), "Invalid hash '{}'", hash);
ensure!(is_valid_name(name.as_bytes()), "Invalid name '{}'", name);
// Already checked
Ok(Self {
path: path.to_owned(),
})
}
}
impl TryFrom<&'_ str> for StorePath {
type Error = Error;
fn try_from(path: &'_ str) -> Result<Self, Self::Error> {
Self::try_from(path.to_owned())
}
}
impl fmt::Display for StorePath {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.path(), f)
}
}
#[cfg(test)]
mod tests {
use super::*;
use insta::assert_snapshot;
#[test]
fn test_nar_info_format() {
let mut nar = Nar {
store_path: StorePath::try_from(
"/nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10",
)
.unwrap(),
meta: NarMeta {
url: "some/url".to_owned(),
compression: Some("xz".to_owned()),
file_hash: Some("file:hash".to_owned()),
file_size: Some(123),
nar_hash: "nar:hash".to_owned(),
nar_size: 456,
deriver: Some("some.drv".to_owned()),
sig: Some("s:i/g 2".to_owned()),
ca: Some("fixed:hash".to_owned()),
},
references: "ref1 ref2".to_owned(),
};
assert_snapshot!(nar.format_nar_info().to_string(), @r###"
StorePath: /nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10
URL: some/url
Compression: xz
FileHash: file:hash
FileSize: 123
NarHash: nar:hash
NarSize: 456
References: ref1 ref2
Sig: s:i/g 2
Deriver: some.drv
CA: fixed:hash
"###);
nar.references = String::new();
nar.meta.deriver = None;
nar.meta.ca = None;
assert_snapshot!(nar.format_nar_info().to_string(), @r###"
StorePath: /nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10
URL: some/url
Compression: xz
FileHash: file:hash
FileSize: 123
NarHash: nar:hash
NarSize: 456
References:
Sig: s:i/g 2
"###);
}
#[test]
fn test_nar_info_parse() {
let raw = r###"
StorePath: /nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10
URL: some/url
Compression: xz
FileHash: file:hash
FileSize: 123
NarHash: nar:hash
NarSize: 456
References: ref1 ref2
Sig: s:i/g 2
Deriver: some.drv
CA: fixed:hash
"###;
let nar = Nar {
store_path: StorePath::try_from(
"/nix/store/yhzvzdq82lzk0kvrp3i79yhjnhps6qpk-hello-2.10",
)
.unwrap(),
meta: NarMeta {
url: "some/url".to_owned(),
compression: Some("xz".to_owned()),
file_hash: Some("file:hash".to_owned()),
file_size: Some(123),
nar_hash: "nar:hash".to_owned(),
nar_size: 456,
deriver: Some("some.drv".to_owned()),
sig: Some("s:i/g 2".to_owned()),
ca: Some("fixed:hash".to_owned()),
},
references: "ref1 ref2".to_owned(),
};
assert_eq!(Nar::parse_nar_info(raw).unwrap(), nar);
}
} | }
pub fn name(&self) -> &str {
&self.path[Self::SEP_POS + 1..] | random_line_split |
main.rs | , ObjectSymbol, SymbolKind, SymbolScope};
use std::env;
use std::fs::File;
use std::io::Cursor;
use std::io::Read;
use std::mem;
#[derive(Debug)]
struct ArtifactSummary<'a> {
buffer: &'a Vec<u8>,
obj: &'a object::File<'a>,
symbols: StandardSymbols<'a>,
data_segments: Option<DataSegments>,
serialized_module: Option<SerializedModule>,
exported_functions: Vec<&'a str>,
imported_symbols: Vec<&'a str>,
}
#[derive(Debug)]
struct StandardSymbols<'a> {
lucet_module: Option<object::read::Symbol<'a, 'a>>,
}
#[derive(Debug)]
struct DataSegments {
segments: Vec<DataSegment>,
}
#[derive(Debug)]
struct DataSegment {
offset: u32,
len: u32,
data: Vec<u8>,
}
impl<'a> ArtifactSummary<'a> {
fn new(buffer: &'a Vec<u8>, obj: &'a object::File<'_>) -> Self {
Self {
buffer,
obj,
symbols: StandardSymbols { lucet_module: None },
data_segments: None,
serialized_module: None,
exported_functions: Vec::new(),
imported_symbols: Vec::new(),
}
}
fn read_memory(&self, addr: u64, size: u64) -> Option<&'a [u8]> {
// `addr` is really more of an offset from the start of the segment.
for section in self.obj.sections() {
let bytes = section.data_range(addr, size).ok().flatten();
if bytes.is_some() {
return bytes;
}
}
None
}
fn gather(&mut self) {
for sym in self.obj.symbols() {
match sym.name() {
Ok(ref name) if name == &"lucet_module" => self.symbols.lucet_module = Some(sym),
Ok(ref name) if name == &"" => continue,
Err(_) => continue,
_ => {
if sym.kind() == SymbolKind::Text && sym.scope() == SymbolScope::Dynamic {
self.exported_functions.push(sym.name().unwrap());
} else if sym.scope() == SymbolScope::Unknown {
self.imported_symbols.push(sym.name().unwrap());
}
}
}
}
self.serialized_module = self.symbols.lucet_module.as_ref().map(|module_sym| {
let buffer = self
.read_memory(
module_sym.address(),
mem::size_of::<SerializedModule>() as u64,
)
.unwrap();
let mut rdr = Cursor::new(buffer);
let version = VersionInfo::read_from(&mut rdr).unwrap();
SerializedModule {
version,
module_data_ptr: rdr.read_u64::<LittleEndian>().unwrap(),
module_data_len: rdr.read_u64::<LittleEndian>().unwrap(),
tables_ptr: rdr.read_u64::<LittleEndian>().unwrap(),
tables_len: rdr.read_u64::<LittleEndian>().unwrap(),
function_manifest_ptr: rdr.read_u64::<LittleEndian>().unwrap(),
function_manifest_len: rdr.read_u64::<LittleEndian>().unwrap(),
}
});
}
fn get_symbol_name_for_addr(&self, addr: u64) -> Option<&str> {
self.obj.symbol_map().get(addr).map(|sym| sym.name())
}
}
fn main() {
let path = env::args().nth(1).unwrap();
let mut fd = File::open(path).expect("open");
let mut buffer = Vec::new();
fd.read_to_end(&mut buffer).expect("read");
let object = object::File::parse(&buffer).expect("parse");
let mut summary = ArtifactSummary::new(&buffer, &object);
summary.gather();
print_summary(summary);
}
/// Parse a trap manifest for function `f`, if it has one.
///
/// `parse_trap_manifest` may very understandably be confusing. Why not use `f.traps()`? In
/// `lucet-objdump` the module has been accessed by reading the file and following structures as
/// they exist at rest. This means pointers are not relocated, so slices that would be valid when
/// loaded through the platform's loader currently have pointers that are not valid for memory
/// access.
///
/// In particular, trap pointers are correct with respect to 0 being the start of the file (or,
/// buffer, after reading), which means we can (and must) rebuild a correct slice from the buffer.
fn parse_trap_manifest<'a>(
summary: &'a ArtifactSummary<'a>,
f: &FunctionSpec,
) -> Option<TrapManifest<'a>> {
if let Some(faulty_trap_manifest) = f.traps() {
let trap_ptr = faulty_trap_manifest.traps.as_ptr();
let traps_count = faulty_trap_manifest.traps.len();
let traps_byte_count = traps_count * std::mem::size_of::<TrapSite>();
if let Some(traps_byte_slice) =
summary.read_memory(trap_ptr as u64, traps_byte_count as u64)
{
let real_trap_ptr = traps_byte_slice.as_ptr() as *const TrapSite;
Some(TrapManifest {
traps: unsafe { std::slice::from_raw_parts(real_trap_ptr, traps_count) },
})
} else {
println!(
"Failed to read trap bytes for function {:?}, at {:p}",
f, trap_ptr
);
None
}
} else {
None
}
}
fn load_module<'b, 'a: 'b>(
summary: &'a ArtifactSummary<'a>,
serialized_module: &SerializedModule,
tables: &'b [&[TableElement]],
) -> Module<'b> {
let module_data_bytes = summary
.read_memory(
serialized_module.module_data_ptr,
serialized_module.module_data_len,
)
.unwrap();
let module_data =
ModuleData::deserialize(module_data_bytes).expect("ModuleData can be deserialized");
let function_manifest_bytes = summary
.read_memory(
serialized_module.function_manifest_ptr,
serialized_module.function_manifest_len,
)
.unwrap();
let function_manifest = unsafe {
std::slice::from_raw_parts(
function_manifest_bytes.as_ptr() as *const FunctionSpec,
serialized_module.function_manifest_len as usize,
)
};
Module {
version: serialized_module.version.clone(),
module_data,
tables,
function_manifest,
}
}
fn summarize_module<'a, 'b: 'a>(summary: &'a ArtifactSummary<'a>, module: &Module<'b>) {
let module_data = &module.module_data;
let tables = module.tables;
let function_manifest = module.function_manifest;
println!(" Heap Specification:");
if let Some(heap_spec) = module_data.heap_spec() {
println!(" {:9}: {} bytes", "Reserved", heap_spec.reserved_size);
println!(" {:9}: {} bytes", "Guard", heap_spec.guard_size);
println!(" {:9}: {} bytes", "Initial", heap_spec.initial_size);
if let Some(max_size) = heap_spec.max_size {
println!(" {:9}: {} bytes", "Maximum", max_size);
} else {
println!(" {:9}: None", "Maximum");
}
} else {
println!(" {}", "MISSING".red().bold());
}
println!();
println!(" Sparse Page Data:");
if let Some(sparse_page_data) = module_data.sparse_data() {
println!(" {:6}: {}", "Count", sparse_page_data.pages().len());
let mut allempty = true;
let mut anyempty = false;
for (i, page) in sparse_page_data.pages().iter().enumerate() {
match page {
Some(page) => {
allempty = false;
println!(
" Page[{}]: {:p}, size: {}",
i,
page.as_ptr(),
if page.len()!= 4096 {
format!(
"{} (page size, expected 4096)",
format!("{}", page.len()).bold().red()
)
.red()
} else {
format!("{}", page.len()).green()
}
);
}
None => {
anyempty = true;
}
};
}
if allempty &&!sparse_page_data.pages().is_empty() {
println!(" (all pages empty)");
} else if anyempty {
println!(" (empty pages omitted)");
}
} else {
println!(" {}", "MISSING!".red().bold());
}
println!();
println!("Tables:");
if tables.is_empty() {
println!(" No tables.");
} else {
for (i, table) in tables.iter().enumerate() {
println!(" Table {}: {:?}", i, table);
}
}
println!();
println!("Signatures:");
for (i, s) in module_data.signatures().iter().enumerate() {
println!(" Signature {}: {}", i, s);
}
println!();
println!("Functions:");
if function_manifest.len()!= module_data.function_info().len() {
println!(
" {} function manifest and function info have diverging function counts",
"lucetc bug:".red().bold()
);
println!(
" function_manifest length : {}",
function_manifest.len()
);
println!(
" module data function count : {}",
module_data.function_info().len()
);
println!(" Will attempt to display information about functions anyway, but trap/code information may be misaligned with symbols and signatures.");
}
for (i, f) in function_manifest.iter().enumerate() {
let header_name = summary.get_symbol_name_for_addr(f.ptr().as_usize() as u64);
if i >= module_data.function_info().len() {
// This is one form of the above-mentioned bug case
// Half the function information is missing, so just report the issue and continue.
println!(
" Function {} {}",
i,
"is missing the module data part of its declaration".red()
);
match header_name {
Some(name) => {
println!(" ELF header name: {}", name);
}
None => {
println!(" No corresponding ELF symbol.");
}
};
break;
}
let colorize_name = |x: Option<&str>| match x {
Some(name) => name.green(),
None => "None".red().bold(),
};
let fn_meta = &module_data.function_info()[i];
println!(" Function {} (name: {}):", i, colorize_name(fn_meta.name));
if fn_meta.name!= header_name {
println!(
" Name {} with name declared in ELF headers: {}",
"DISAGREES".red().bold(),
colorize_name(header_name)
);
}
println!(
" Signature (index {}): {}",
fn_meta.signature.as_u32() as usize,
module_data.signatures()[fn_meta.signature.as_u32() as usize]
);
println!(" Start: {:#010x}", f.ptr().as_usize());
println!(" Code length: {} bytes", f.code_len());
if let Some(trap_manifest) = parse_trap_manifest(&summary, f) {
let trap_count = trap_manifest.traps.len();
println!(" Trap information:");
if trap_count > 0 {
println!(
" {} {}...",
trap_manifest.traps.len(),
if trap_count == 1 { "trap" } else { "traps" },
);
for trap in trap_manifest.traps {
println!(" $+{:#06x}: {:?}", trap.offset, trap.code);
}
} else {
println!(" No traps for this function");
}
}
}
println!();
println!("Globals:");
if!module_data.globals_spec().is_empty() {
for global_spec in module_data.globals_spec().iter() {
println!(" {:?}", global_spec.global());
for name in global_spec.export_names() {
println!(" Exported as: {}", name);
}
}
} else {
println!(" None");
}
println!();
println!("Exported Functions/Symbols:");
let mut exported_symbols = summary.exported_functions.clone();
for export in module_data.export_functions() {
match module_data.function_info()[export.fn_idx.as_u32() as usize].name {
Some(name) => {
println!(" Internal name: {}", name);
// The "internal name" is probably the first exported name for this function.
// Remove it from the exported_symbols list to not double-count
if let Some(idx) = exported_symbols.iter().position(|x| *x == name) {
exported_symbols.remove(idx);
}
}
None => {
println!(" No internal name");
}
}
// Export names do not have the guest_func_ prefix that symbol names get, and as such do
// not need to be removed from `exported_symbols` (which is built entirely from
// ELF-declared exports, with namespaced names)
println!(" Exported as: {}", export.names.join(", "));
}
if!exported_symbols.is_empty() {
println!();
println!(" Other exported symbols (from ELF headers):");
for export in exported_symbols {
println!(" {}", export);
}
}
println!();
println!("Imported Functions/Symbols:");
let mut imported_symbols = summary.imported_symbols.clone();
for import in module_data.import_functions() {
match module_data.function_info()[import.fn_idx.as_u32() as usize].name {
Some(name) => {
println!(" Internal name: {}", name);
}
None => {
println!(" No internal name");
}
}
println!(" Imported as: {}/{}", import.module, import.name);
// Remove from the imported_symbols list to not double-count imported functions
if let Some(idx) = imported_symbols.iter().position(|x| x == &import.name) |
}
if!imported_symbols.is_empty() {
println!();
println!(" Other imported symbols (from ELF headers):");
for import in &imported_symbols {
println!(" {}", import);
}
}
}
fn print_summary(summary: ArtifactSummary<'_>) {
println!("Required Symbols:");
println!(
" {:30}: {}",
"lucet_module",
exists_to_str(&summary.symbols.lucet_module)
);
if let Some(ref serialized_module) = summary.serialized_module {
println!("Native module components:");
println!(
" {:30}: {}",
"module_data_ptr",
ptr_to_str(serialized_module.module_data_ptr)
);
println!(
" {:30}: {}",
"module_data_len", serialized_module.module_data_len
);
println!(
" {:30}: {}",
"tables_ptr",
ptr_to_str(serialized_module.tables_ptr)
);
println!(" {:30}: {}", "tables_len", serialized_module.tables_len);
println!(
" {:30}: {}",
"function_manifest_ptr",
ptr_to_str(serialized_module.function_manifest_ptr)
);
println!(
" {:30}: {}",
"function_manifest_len", serialized_module.function_manifest_len
);
let tables_bytes = summary
.read_memory(
serialized_module.tables_ptr,
serialized_module.tables_len * mem::size_of::<&[TableElement]>() as u64,
)
.unwrap();
let tables = unsafe {
std::slice::from_raw_parts(
tables_bytes.as_ptr() as *const &[TableElement],
serialized_module.tables_len as usize,
)
};
let mut reconstructed_tables = Vec::new();
// same situation as trap tables - these slices are valid as if the module was
// dlopen'd, but we just read it as a flat file. So read through the ELF view and use
// pointers to that for the real slices.
for table in tables {
let table_bytes = summary
.read_memory(
table.as_ptr() as usize as u64,
(table.len() * mem::size_of::<TableElement>()) as u64,
)
.unwrap();
reconstructed_tables.push(unsafe {
std::slice::from_raw_parts(
table_bytes.as_ptr() as *const TableElement,
table.len() as usize,
)
});
}
let module = load_module(&summary, serialized_module, &reconstructed_tables);
println!("\nModule:");
summarize_module(&summary, &module);
} else {
println!("The symbol `lucet_module` is {}, so lucet-objdump cannot look at most of the interesting parts.", "MISSING".red().bold());
}
println!();
println!("Data Segments:");
if let Some(data_segments) = summary.data_segments {
println!(" {:6}: {}", "Count", data_segments.segments.len());
for segment in &data_segments.segments {
println!(
" {:7}: {:6} {:6}: {:6}",
"Offset", segment.offset, "Length", segment.len,
| {
imported_symbols.remove(idx);
} | conditional_block |
main.rs | Section, ObjectSymbol, SymbolKind, SymbolScope};
use std::env;
use std::fs::File;
use std::io::Cursor;
use std::io::Read;
use std::mem;
#[derive(Debug)]
struct ArtifactSummary<'a> {
buffer: &'a Vec<u8>,
obj: &'a object::File<'a>,
symbols: StandardSymbols<'a>,
data_segments: Option<DataSegments>,
serialized_module: Option<SerializedModule>,
exported_functions: Vec<&'a str>,
imported_symbols: Vec<&'a str>,
}
#[derive(Debug)]
struct StandardSymbols<'a> {
lucet_module: Option<object::read::Symbol<'a, 'a>>,
}
#[derive(Debug)]
struct DataSegments {
segments: Vec<DataSegment>,
}
#[derive(Debug)]
struct DataSegment {
offset: u32,
len: u32,
data: Vec<u8>,
}
impl<'a> ArtifactSummary<'a> {
fn new(buffer: &'a Vec<u8>, obj: &'a object::File<'_>) -> Self {
Self {
buffer,
obj,
symbols: StandardSymbols { lucet_module: None },
data_segments: None,
serialized_module: None,
exported_functions: Vec::new(),
imported_symbols: Vec::new(),
}
}
fn read_memory(&self, addr: u64, size: u64) -> Option<&'a [u8]> {
// `addr` is really more of an offset from the start of the segment.
for section in self.obj.sections() {
let bytes = section.data_range(addr, size).ok().flatten();
if bytes.is_some() {
return bytes;
}
}
None
}
fn gather(&mut self) {
for sym in self.obj.symbols() {
match sym.name() {
Ok(ref name) if name == &"lucet_module" => self.symbols.lucet_module = Some(sym),
Ok(ref name) if name == &"" => continue,
Err(_) => continue,
_ => {
if sym.kind() == SymbolKind::Text && sym.scope() == SymbolScope::Dynamic {
self.exported_functions.push(sym.name().unwrap());
} else if sym.scope() == SymbolScope::Unknown {
self.imported_symbols.push(sym.name().unwrap());
}
}
}
}
self.serialized_module = self.symbols.lucet_module.as_ref().map(|module_sym| {
let buffer = self
.read_memory(
module_sym.address(),
mem::size_of::<SerializedModule>() as u64,
)
.unwrap();
let mut rdr = Cursor::new(buffer);
let version = VersionInfo::read_from(&mut rdr).unwrap();
SerializedModule {
version,
module_data_ptr: rdr.read_u64::<LittleEndian>().unwrap(),
module_data_len: rdr.read_u64::<LittleEndian>().unwrap(),
tables_ptr: rdr.read_u64::<LittleEndian>().unwrap(),
tables_len: rdr.read_u64::<LittleEndian>().unwrap(),
function_manifest_ptr: rdr.read_u64::<LittleEndian>().unwrap(),
function_manifest_len: rdr.read_u64::<LittleEndian>().unwrap(),
}
});
}
fn get_symbol_name_for_addr(&self, addr: u64) -> Option<&str> {
self.obj.symbol_map().get(addr).map(|sym| sym.name())
}
}
fn main() {
let path = env::args().nth(1).unwrap();
let mut fd = File::open(path).expect("open");
let mut buffer = Vec::new();
fd.read_to_end(&mut buffer).expect("read");
let object = object::File::parse(&buffer).expect("parse");
let mut summary = ArtifactSummary::new(&buffer, &object);
summary.gather();
print_summary(summary);
}
/// Parse a trap manifest for function `f`, if it has one.
///
/// `parse_trap_manifest` may very understandably be confusing. Why not use `f.traps()`? In
/// `lucet-objdump` the module has been accessed by reading the file and following structures as
/// they exist at rest. This means pointers are not relocated, so slices that would be valid when
/// loaded through the platform's loader currently have pointers that are not valid for memory
/// access.
///
/// In particular, trap pointers are correct with respect to 0 being the start of the file (or,
/// buffer, after reading), which means we can (and must) rebuild a correct slice from the buffer.
fn parse_trap_manifest<'a>(
summary: &'a ArtifactSummary<'a>,
f: &FunctionSpec,
) -> Option<TrapManifest<'a>> {
if let Some(faulty_trap_manifest) = f.traps() {
let trap_ptr = faulty_trap_manifest.traps.as_ptr();
let traps_count = faulty_trap_manifest.traps.len();
let traps_byte_count = traps_count * std::mem::size_of::<TrapSite>();
if let Some(traps_byte_slice) =
summary.read_memory(trap_ptr as u64, traps_byte_count as u64)
{
let real_trap_ptr = traps_byte_slice.as_ptr() as *const TrapSite;
Some(TrapManifest {
traps: unsafe { std::slice::from_raw_parts(real_trap_ptr, traps_count) },
})
} else {
println!(
"Failed to read trap bytes for function {:?}, at {:p}",
f, trap_ptr
);
None
}
} else {
None
}
}
fn load_module<'b, 'a: 'b>(
summary: &'a ArtifactSummary<'a>,
serialized_module: &SerializedModule,
tables: &'b [&[TableElement]],
) -> Module<'b> {
let module_data_bytes = summary
.read_memory(
serialized_module.module_data_ptr,
serialized_module.module_data_len,
)
.unwrap();
let module_data =
ModuleData::deserialize(module_data_bytes).expect("ModuleData can be deserialized");
let function_manifest_bytes = summary
.read_memory(
serialized_module.function_manifest_ptr,
serialized_module.function_manifest_len,
)
.unwrap();
let function_manifest = unsafe {
std::slice::from_raw_parts(
function_manifest_bytes.as_ptr() as *const FunctionSpec,
serialized_module.function_manifest_len as usize,
)
};
Module {
version: serialized_module.version.clone(),
module_data,
tables,
function_manifest,
}
}
fn summarize_module<'a, 'b: 'a>(summary: &'a ArtifactSummary<'a>, module: &Module<'b>) {
let module_data = &module.module_data;
let tables = module.tables;
let function_manifest = module.function_manifest;
println!(" Heap Specification:");
if let Some(heap_spec) = module_data.heap_spec() {
println!(" {:9}: {} bytes", "Reserved", heap_spec.reserved_size);
println!(" {:9}: {} bytes", "Guard", heap_spec.guard_size);
println!(" {:9}: {} bytes", "Initial", heap_spec.initial_size);
if let Some(max_size) = heap_spec.max_size {
println!(" {:9}: {} bytes", "Maximum", max_size);
} else {
println!(" {:9}: None", "Maximum");
}
} else {
println!(" {}", "MISSING".red().bold());
}
println!();
println!(" Sparse Page Data:");
if let Some(sparse_page_data) = module_data.sparse_data() {
println!(" {:6}: {}", "Count", sparse_page_data.pages().len());
let mut allempty = true;
let mut anyempty = false;
for (i, page) in sparse_page_data.pages().iter().enumerate() {
match page {
Some(page) => {
allempty = false;
println!(
" Page[{}]: {:p}, size: {}",
i,
page.as_ptr(),
if page.len()!= 4096 {
format!(
"{} (page size, expected 4096)",
format!("{}", page.len()).bold().red()
)
.red()
} else {
format!("{}", page.len()).green()
}
);
}
None => {
anyempty = true;
}
};
}
if allempty &&!sparse_page_data.pages().is_empty() {
println!(" (all pages empty)");
} else if anyempty {
println!(" (empty pages omitted)");
}
} else {
println!(" {}", "MISSING!".red().bold());
}
println!();
println!("Tables:");
if tables.is_empty() {
println!(" No tables.");
} else {
for (i, table) in tables.iter().enumerate() {
println!(" Table {}: {:?}", i, table);
}
}
println!();
println!("Signatures:");
for (i, s) in module_data.signatures().iter().enumerate() {
println!(" Signature {}: {}", i, s);
}
println!();
println!("Functions:");
if function_manifest.len()!= module_data.function_info().len() {
println!(
" {} function manifest and function info have diverging function counts",
"lucetc bug:".red().bold()
);
println!(
" function_manifest length : {}",
function_manifest.len()
);
println!(
" module data function count : {}",
module_data.function_info().len()
);
println!(" Will attempt to display information about functions anyway, but trap/code information may be misaligned with symbols and signatures.");
}
for (i, f) in function_manifest.iter().enumerate() {
let header_name = summary.get_symbol_name_for_addr(f.ptr().as_usize() as u64);
if i >= module_data.function_info().len() {
// This is one form of the above-mentioned bug case
// Half the function information is missing, so just report the issue and continue.
println!( | Some(name) => {
println!(" ELF header name: {}", name);
}
None => {
println!(" No corresponding ELF symbol.");
}
};
break;
}
let colorize_name = |x: Option<&str>| match x {
Some(name) => name.green(),
None => "None".red().bold(),
};
let fn_meta = &module_data.function_info()[i];
println!(" Function {} (name: {}):", i, colorize_name(fn_meta.name));
if fn_meta.name!= header_name {
println!(
" Name {} with name declared in ELF headers: {}",
"DISAGREES".red().bold(),
colorize_name(header_name)
);
}
println!(
" Signature (index {}): {}",
fn_meta.signature.as_u32() as usize,
module_data.signatures()[fn_meta.signature.as_u32() as usize]
);
println!(" Start: {:#010x}", f.ptr().as_usize());
println!(" Code length: {} bytes", f.code_len());
if let Some(trap_manifest) = parse_trap_manifest(&summary, f) {
let trap_count = trap_manifest.traps.len();
println!(" Trap information:");
if trap_count > 0 {
println!(
" {} {}...",
trap_manifest.traps.len(),
if trap_count == 1 { "trap" } else { "traps" },
);
for trap in trap_manifest.traps {
println!(" $+{:#06x}: {:?}", trap.offset, trap.code);
}
} else {
println!(" No traps for this function");
}
}
}
println!();
println!("Globals:");
if!module_data.globals_spec().is_empty() {
for global_spec in module_data.globals_spec().iter() {
println!(" {:?}", global_spec.global());
for name in global_spec.export_names() {
println!(" Exported as: {}", name);
}
}
} else {
println!(" None");
}
println!();
println!("Exported Functions/Symbols:");
let mut exported_symbols = summary.exported_functions.clone();
for export in module_data.export_functions() {
match module_data.function_info()[export.fn_idx.as_u32() as usize].name {
Some(name) => {
println!(" Internal name: {}", name);
// The "internal name" is probably the first exported name for this function.
// Remove it from the exported_symbols list to not double-count
if let Some(idx) = exported_symbols.iter().position(|x| *x == name) {
exported_symbols.remove(idx);
}
}
None => {
println!(" No internal name");
}
}
// Export names do not have the guest_func_ prefix that symbol names get, and as such do
// not need to be removed from `exported_symbols` (which is built entirely from
// ELF-declared exports, with namespaced names)
println!(" Exported as: {}", export.names.join(", "));
}
if!exported_symbols.is_empty() {
println!();
println!(" Other exported symbols (from ELF headers):");
for export in exported_symbols {
println!(" {}", export);
}
}
println!();
println!("Imported Functions/Symbols:");
let mut imported_symbols = summary.imported_symbols.clone();
for import in module_data.import_functions() {
match module_data.function_info()[import.fn_idx.as_u32() as usize].name {
Some(name) => {
println!(" Internal name: {}", name);
}
None => {
println!(" No internal name");
}
}
println!(" Imported as: {}/{}", import.module, import.name);
// Remove from the imported_symbols list to not double-count imported functions
if let Some(idx) = imported_symbols.iter().position(|x| x == &import.name) {
imported_symbols.remove(idx);
}
}
if!imported_symbols.is_empty() {
println!();
println!(" Other imported symbols (from ELF headers):");
for import in &imported_symbols {
println!(" {}", import);
}
}
}
fn print_summary(summary: ArtifactSummary<'_>) {
println!("Required Symbols:");
println!(
" {:30}: {}",
"lucet_module",
exists_to_str(&summary.symbols.lucet_module)
);
if let Some(ref serialized_module) = summary.serialized_module {
println!("Native module components:");
println!(
" {:30}: {}",
"module_data_ptr",
ptr_to_str(serialized_module.module_data_ptr)
);
println!(
" {:30}: {}",
"module_data_len", serialized_module.module_data_len
);
println!(
" {:30}: {}",
"tables_ptr",
ptr_to_str(serialized_module.tables_ptr)
);
println!(" {:30}: {}", "tables_len", serialized_module.tables_len);
println!(
" {:30}: {}",
"function_manifest_ptr",
ptr_to_str(serialized_module.function_manifest_ptr)
);
println!(
" {:30}: {}",
"function_manifest_len", serialized_module.function_manifest_len
);
let tables_bytes = summary
.read_memory(
serialized_module.tables_ptr,
serialized_module.tables_len * mem::size_of::<&[TableElement]>() as u64,
)
.unwrap();
let tables = unsafe {
std::slice::from_raw_parts(
tables_bytes.as_ptr() as *const &[TableElement],
serialized_module.tables_len as usize,
)
};
let mut reconstructed_tables = Vec::new();
// same situation as trap tables - these slices are valid as if the module was
// dlopen'd, but we just read it as a flat file. So read through the ELF view and use
// pointers to that for the real slices.
for table in tables {
let table_bytes = summary
.read_memory(
table.as_ptr() as usize as u64,
(table.len() * mem::size_of::<TableElement>()) as u64,
)
.unwrap();
reconstructed_tables.push(unsafe {
std::slice::from_raw_parts(
table_bytes.as_ptr() as *const TableElement,
table.len() as usize,
)
});
}
let module = load_module(&summary, serialized_module, &reconstructed_tables);
println!("\nModule:");
summarize_module(&summary, &module);
} else {
println!("The symbol `lucet_module` is {}, so lucet-objdump cannot look at most of the interesting parts.", "MISSING".red().bold());
}
println!();
println!("Data Segments:");
if let Some(data_segments) = summary.data_segments {
println!(" {:6}: {}", "Count", data_segments.segments.len());
for segment in &data_segments.segments {
println!(
" {:7}: {:6} {:6}: {:6}",
"Offset", segment.offset, "Length", segment.len,
| " Function {} {}",
i,
"is missing the module data part of its declaration".red()
);
match header_name { | random_line_split |
main.rs | , ObjectSymbol, SymbolKind, SymbolScope};
use std::env;
use std::fs::File;
use std::io::Cursor;
use std::io::Read;
use std::mem;
#[derive(Debug)]
struct ArtifactSummary<'a> {
buffer: &'a Vec<u8>,
obj: &'a object::File<'a>,
symbols: StandardSymbols<'a>,
data_segments: Option<DataSegments>,
serialized_module: Option<SerializedModule>,
exported_functions: Vec<&'a str>,
imported_symbols: Vec<&'a str>,
}
#[derive(Debug)]
struct | <'a> {
lucet_module: Option<object::read::Symbol<'a, 'a>>,
}
#[derive(Debug)]
struct DataSegments {
segments: Vec<DataSegment>,
}
#[derive(Debug)]
struct DataSegment {
offset: u32,
len: u32,
data: Vec<u8>,
}
impl<'a> ArtifactSummary<'a> {
fn new(buffer: &'a Vec<u8>, obj: &'a object::File<'_>) -> Self {
Self {
buffer,
obj,
symbols: StandardSymbols { lucet_module: None },
data_segments: None,
serialized_module: None,
exported_functions: Vec::new(),
imported_symbols: Vec::new(),
}
}
fn read_memory(&self, addr: u64, size: u64) -> Option<&'a [u8]> {
// `addr` is really more of an offset from the start of the segment.
for section in self.obj.sections() {
let bytes = section.data_range(addr, size).ok().flatten();
if bytes.is_some() {
return bytes;
}
}
None
}
fn gather(&mut self) {
for sym in self.obj.symbols() {
match sym.name() {
Ok(ref name) if name == &"lucet_module" => self.symbols.lucet_module = Some(sym),
Ok(ref name) if name == &"" => continue,
Err(_) => continue,
_ => {
if sym.kind() == SymbolKind::Text && sym.scope() == SymbolScope::Dynamic {
self.exported_functions.push(sym.name().unwrap());
} else if sym.scope() == SymbolScope::Unknown {
self.imported_symbols.push(sym.name().unwrap());
}
}
}
}
self.serialized_module = self.symbols.lucet_module.as_ref().map(|module_sym| {
let buffer = self
.read_memory(
module_sym.address(),
mem::size_of::<SerializedModule>() as u64,
)
.unwrap();
let mut rdr = Cursor::new(buffer);
let version = VersionInfo::read_from(&mut rdr).unwrap();
SerializedModule {
version,
module_data_ptr: rdr.read_u64::<LittleEndian>().unwrap(),
module_data_len: rdr.read_u64::<LittleEndian>().unwrap(),
tables_ptr: rdr.read_u64::<LittleEndian>().unwrap(),
tables_len: rdr.read_u64::<LittleEndian>().unwrap(),
function_manifest_ptr: rdr.read_u64::<LittleEndian>().unwrap(),
function_manifest_len: rdr.read_u64::<LittleEndian>().unwrap(),
}
});
}
fn get_symbol_name_for_addr(&self, addr: u64) -> Option<&str> {
self.obj.symbol_map().get(addr).map(|sym| sym.name())
}
}
fn main() {
let path = env::args().nth(1).unwrap();
let mut fd = File::open(path).expect("open");
let mut buffer = Vec::new();
fd.read_to_end(&mut buffer).expect("read");
let object = object::File::parse(&buffer).expect("parse");
let mut summary = ArtifactSummary::new(&buffer, &object);
summary.gather();
print_summary(summary);
}
/// Parse a trap manifest for function `f`, if it has one.
///
/// `parse_trap_manifest` may very understandably be confusing. Why not use `f.traps()`? In
/// `lucet-objdump` the module has been accessed by reading the file and following structures as
/// they exist at rest. This means pointers are not relocated, so slices that would be valid when
/// loaded through the platform's loader currently have pointers that are not valid for memory
/// access.
///
/// In particular, trap pointers are correct with respect to 0 being the start of the file (or,
/// buffer, after reading), which means we can (and must) rebuild a correct slice from the buffer.
fn parse_trap_manifest<'a>(
summary: &'a ArtifactSummary<'a>,
f: &FunctionSpec,
) -> Option<TrapManifest<'a>> {
if let Some(faulty_trap_manifest) = f.traps() {
let trap_ptr = faulty_trap_manifest.traps.as_ptr();
let traps_count = faulty_trap_manifest.traps.len();
let traps_byte_count = traps_count * std::mem::size_of::<TrapSite>();
if let Some(traps_byte_slice) =
summary.read_memory(trap_ptr as u64, traps_byte_count as u64)
{
let real_trap_ptr = traps_byte_slice.as_ptr() as *const TrapSite;
Some(TrapManifest {
traps: unsafe { std::slice::from_raw_parts(real_trap_ptr, traps_count) },
})
} else {
println!(
"Failed to read trap bytes for function {:?}, at {:p}",
f, trap_ptr
);
None
}
} else {
None
}
}
fn load_module<'b, 'a: 'b>(
summary: &'a ArtifactSummary<'a>,
serialized_module: &SerializedModule,
tables: &'b [&[TableElement]],
) -> Module<'b> {
let module_data_bytes = summary
.read_memory(
serialized_module.module_data_ptr,
serialized_module.module_data_len,
)
.unwrap();
let module_data =
ModuleData::deserialize(module_data_bytes).expect("ModuleData can be deserialized");
let function_manifest_bytes = summary
.read_memory(
serialized_module.function_manifest_ptr,
serialized_module.function_manifest_len,
)
.unwrap();
let function_manifest = unsafe {
std::slice::from_raw_parts(
function_manifest_bytes.as_ptr() as *const FunctionSpec,
serialized_module.function_manifest_len as usize,
)
};
Module {
version: serialized_module.version.clone(),
module_data,
tables,
function_manifest,
}
}
fn summarize_module<'a, 'b: 'a>(summary: &'a ArtifactSummary<'a>, module: &Module<'b>) {
let module_data = &module.module_data;
let tables = module.tables;
let function_manifest = module.function_manifest;
println!(" Heap Specification:");
if let Some(heap_spec) = module_data.heap_spec() {
println!(" {:9}: {} bytes", "Reserved", heap_spec.reserved_size);
println!(" {:9}: {} bytes", "Guard", heap_spec.guard_size);
println!(" {:9}: {} bytes", "Initial", heap_spec.initial_size);
if let Some(max_size) = heap_spec.max_size {
println!(" {:9}: {} bytes", "Maximum", max_size);
} else {
println!(" {:9}: None", "Maximum");
}
} else {
println!(" {}", "MISSING".red().bold());
}
println!();
println!(" Sparse Page Data:");
if let Some(sparse_page_data) = module_data.sparse_data() {
println!(" {:6}: {}", "Count", sparse_page_data.pages().len());
let mut allempty = true;
let mut anyempty = false;
for (i, page) in sparse_page_data.pages().iter().enumerate() {
match page {
Some(page) => {
allempty = false;
println!(
" Page[{}]: {:p}, size: {}",
i,
page.as_ptr(),
if page.len()!= 4096 {
format!(
"{} (page size, expected 4096)",
format!("{}", page.len()).bold().red()
)
.red()
} else {
format!("{}", page.len()).green()
}
);
}
None => {
anyempty = true;
}
};
}
if allempty &&!sparse_page_data.pages().is_empty() {
println!(" (all pages empty)");
} else if anyempty {
println!(" (empty pages omitted)");
}
} else {
println!(" {}", "MISSING!".red().bold());
}
println!();
println!("Tables:");
if tables.is_empty() {
println!(" No tables.");
} else {
for (i, table) in tables.iter().enumerate() {
println!(" Table {}: {:?}", i, table);
}
}
println!();
println!("Signatures:");
for (i, s) in module_data.signatures().iter().enumerate() {
println!(" Signature {}: {}", i, s);
}
println!();
println!("Functions:");
if function_manifest.len()!= module_data.function_info().len() {
println!(
" {} function manifest and function info have diverging function counts",
"lucetc bug:".red().bold()
);
println!(
" function_manifest length : {}",
function_manifest.len()
);
println!(
" module data function count : {}",
module_data.function_info().len()
);
println!(" Will attempt to display information about functions anyway, but trap/code information may be misaligned with symbols and signatures.");
}
for (i, f) in function_manifest.iter().enumerate() {
let header_name = summary.get_symbol_name_for_addr(f.ptr().as_usize() as u64);
if i >= module_data.function_info().len() {
// This is one form of the above-mentioned bug case
// Half the function information is missing, so just report the issue and continue.
println!(
" Function {} {}",
i,
"is missing the module data part of its declaration".red()
);
match header_name {
Some(name) => {
println!(" ELF header name: {}", name);
}
None => {
println!(" No corresponding ELF symbol.");
}
};
break;
}
let colorize_name = |x: Option<&str>| match x {
Some(name) => name.green(),
None => "None".red().bold(),
};
let fn_meta = &module_data.function_info()[i];
println!(" Function {} (name: {}):", i, colorize_name(fn_meta.name));
if fn_meta.name!= header_name {
println!(
" Name {} with name declared in ELF headers: {}",
"DISAGREES".red().bold(),
colorize_name(header_name)
);
}
println!(
" Signature (index {}): {}",
fn_meta.signature.as_u32() as usize,
module_data.signatures()[fn_meta.signature.as_u32() as usize]
);
println!(" Start: {:#010x}", f.ptr().as_usize());
println!(" Code length: {} bytes", f.code_len());
if let Some(trap_manifest) = parse_trap_manifest(&summary, f) {
let trap_count = trap_manifest.traps.len();
println!(" Trap information:");
if trap_count > 0 {
println!(
" {} {}...",
trap_manifest.traps.len(),
if trap_count == 1 { "trap" } else { "traps" },
);
for trap in trap_manifest.traps {
println!(" $+{:#06x}: {:?}", trap.offset, trap.code);
}
} else {
println!(" No traps for this function");
}
}
}
println!();
println!("Globals:");
if!module_data.globals_spec().is_empty() {
for global_spec in module_data.globals_spec().iter() {
println!(" {:?}", global_spec.global());
for name in global_spec.export_names() {
println!(" Exported as: {}", name);
}
}
} else {
println!(" None");
}
println!();
println!("Exported Functions/Symbols:");
let mut exported_symbols = summary.exported_functions.clone();
for export in module_data.export_functions() {
match module_data.function_info()[export.fn_idx.as_u32() as usize].name {
Some(name) => {
println!(" Internal name: {}", name);
// The "internal name" is probably the first exported name for this function.
// Remove it from the exported_symbols list to not double-count
if let Some(idx) = exported_symbols.iter().position(|x| *x == name) {
exported_symbols.remove(idx);
}
}
None => {
println!(" No internal name");
}
}
// Export names do not have the guest_func_ prefix that symbol names get, and as such do
// not need to be removed from `exported_symbols` (which is built entirely from
// ELF-declared exports, with namespaced names)
println!(" Exported as: {}", export.names.join(", "));
}
if!exported_symbols.is_empty() {
println!();
println!(" Other exported symbols (from ELF headers):");
for export in exported_symbols {
println!(" {}", export);
}
}
println!();
println!("Imported Functions/Symbols:");
let mut imported_symbols = summary.imported_symbols.clone();
for import in module_data.import_functions() {
match module_data.function_info()[import.fn_idx.as_u32() as usize].name {
Some(name) => {
println!(" Internal name: {}", name);
}
None => {
println!(" No internal name");
}
}
println!(" Imported as: {}/{}", import.module, import.name);
// Remove from the imported_symbols list to not double-count imported functions
if let Some(idx) = imported_symbols.iter().position(|x| x == &import.name) {
imported_symbols.remove(idx);
}
}
if!imported_symbols.is_empty() {
println!();
println!(" Other imported symbols (from ELF headers):");
for import in &imported_symbols {
println!(" {}", import);
}
}
}
fn print_summary(summary: ArtifactSummary<'_>) {
println!("Required Symbols:");
println!(
" {:30}: {}",
"lucet_module",
exists_to_str(&summary.symbols.lucet_module)
);
if let Some(ref serialized_module) = summary.serialized_module {
println!("Native module components:");
println!(
" {:30}: {}",
"module_data_ptr",
ptr_to_str(serialized_module.module_data_ptr)
);
println!(
" {:30}: {}",
"module_data_len", serialized_module.module_data_len
);
println!(
" {:30}: {}",
"tables_ptr",
ptr_to_str(serialized_module.tables_ptr)
);
println!(" {:30}: {}", "tables_len", serialized_module.tables_len);
println!(
" {:30}: {}",
"function_manifest_ptr",
ptr_to_str(serialized_module.function_manifest_ptr)
);
println!(
" {:30}: {}",
"function_manifest_len", serialized_module.function_manifest_len
);
let tables_bytes = summary
.read_memory(
serialized_module.tables_ptr,
serialized_module.tables_len * mem::size_of::<&[TableElement]>() as u64,
)
.unwrap();
let tables = unsafe {
std::slice::from_raw_parts(
tables_bytes.as_ptr() as *const &[TableElement],
serialized_module.tables_len as usize,
)
};
let mut reconstructed_tables = Vec::new();
// same situation as trap tables - these slices are valid as if the module was
// dlopen'd, but we just read it as a flat file. So read through the ELF view and use
// pointers to that for the real slices.
for table in tables {
let table_bytes = summary
.read_memory(
table.as_ptr() as usize as u64,
(table.len() * mem::size_of::<TableElement>()) as u64,
)
.unwrap();
reconstructed_tables.push(unsafe {
std::slice::from_raw_parts(
table_bytes.as_ptr() as *const TableElement,
table.len() as usize,
)
});
}
let module = load_module(&summary, serialized_module, &reconstructed_tables);
println!("\nModule:");
summarize_module(&summary, &module);
} else {
println!("The symbol `lucet_module` is {}, so lucet-objdump cannot look at most of the interesting parts.", "MISSING".red().bold());
}
println!();
println!("Data Segments:");
if let Some(data_segments) = summary.data_segments {
println!(" {:6}: {}", "Count", data_segments.segments.len());
for segment in &data_segments.segments {
println!(
" {:7}: {:6} {:6}: {:6}",
"Offset", segment.offset, "Length", segment.len,
| StandardSymbols | identifier_name |
vm.rs | 8 {
/// The current opcode.
opcode: u16,
/// The chip's 4096 bytes of memory.
pub memory: [u8; 4096], // TEMPORARY pub for debug purposes
/// The chip's 16 registers, from V0 to VF.
/// VF is used for the 'carry flag'.
v: [u8; 16],
/// Index register.
i: usize,
/// Program counter.
pc: usize,
/// The stack, used for subroutine operations.
/// By default has 16 levels of nesting.
pub stack: [u16; STACK_SIZE],
/// Stack pointer.
pub sp: usize,
// Timer registers, must be updated at 60 Hz by the emulator.
pub delay_timer: u8,
pub sound_timer: u8,
/// Screen component.
pub display: Display,
/// Input component.
pub keypad: Keypad,
/// Is the virtual machine waiting for a keypress?
/// If so, when any key is pressed store its index in VX where X is
/// the value stored in this tuple.
pub wait_for_key: (bool, u8),
/// Implementation option.
/// Should the shifting opcodes 8XY6 and 8XYE use the original implementation,
/// i.e. set VX to VY shifted respectively right and left by one bit?
/// If false, the VM will instead consider as many ROMs seem to do that Y=X.
/// See http://mattmik.com/chip8.html for more detail.
shift_op_use_vy: bool,
}
/// Macro for handling invalid/unimplemented opcodes.
/// As of now only prints a error message, could maybe panic in the future.
macro_rules! op_not_implemented {
($op: expr, $pc: expr) => {
println!(
"Not implemented opcode {:0>4X} at {:0>5X}",
$op as usize, $pc
);
};
}
impl Chip8 {
/// Create and return a new, initialized Chip8 virtual machine.
pub fn new() -> Chip8 {
let mut chip8 = Chip8 {
opcode: 0u16,
memory: [0u8; 4096],
v: [0u8; 16],
i: 0usize,
pc: 0usize,
stack: [0u16; STACK_SIZE],
sp: 0usize,
delay_timer: 0u8,
sound_timer: 0u8,
display: Display::new(),
keypad: Keypad::new(),
wait_for_key: (false, 0x0),
shift_op_use_vy: false,
};
// load the font set in memory in the space [0x0, 0x200[ = [0, 80[
for i in 0..80 {
chip8.memory[i] = FONT_SET[i];
}
// the program space starts at 0x200
chip8.pc = 0x200;
chip8
}
/// Reinitialize the virtual machine's state but keep the loaded program
/// in memory.
pub fn reset(&mut self) {
self.opcode = 0u16;
self.v = [0u8; 16];
self.i = 0usize;
self.pc = 0x200;
self.stack = [0u16; STACK_SIZE];
self.sp = 0usize;
self.delay_timer = 0u8;
self.sound_timer = 0u8;
self.display = Display::new();
self.keypad = Keypad::new();
self.wait_for_key = (false, 0x0);
}
/// Set the shift_op_use_vy flag.
pub fn should_shift_op_use_vy(&mut self, b: bool) {
self.shift_op_use_vy = b;
}
/// Is the CPU waiting for a key press?
pub fn is_waiting_for_key(&self) -> bool {
self.wait_for_key.0
}
/// Called by the emulator application to inform the virtual machine
/// waiting for a key pressed that a key has been pressed.
pub fn end_wait_for_key(&mut self, key_index: usize) {
if!self.is_waiting_for_key() {
warn!(concat!(
"Chip8::end_wait_for_key_press called but the VM ",
"wasn't waiting for a key press - ignoring"
));
return;
}
self.v[self.wait_for_key.1 as usize] = key_index as u8;
self.wait_for_key.0 = false;
self.pc += 2;
}
/// Get the value stored in the register VX.
pub fn register(&self, x: usize) -> u8 {
self.v[x]
}
/// Get the index register.
pub fn index(&self) -> usize {
self.i
}
/// Get the program counter value.
pub fn pc(&self) -> usize {
self.pc
}
/// Load a Chip8 rom from the given filepath.
/// If the operation fails, return a String explaining why.
pub fn load(&mut self, filepath: &Path) -> Option<String> {
let file = match File::open(filepath) {
Ok(f) => f,
Err(ref why) => {
return Some(format!(
"couldn't open rom file \"{}\" : {}",
filepath.display(),
Error::description(why)
));
}
};
for (i, b) in file.bytes().enumerate() {
//if b.is_none() /* EOF */ { break; }
match b {
Ok(byte) => self.memory[self.pc + i] = byte,
Err(e) => {
return Some(format!("error while reading ROM : {}", e.to_string()));
}
}
}
None
}
/// Emulate a Chip8 CPU cycle.
/// Return true if the loaded program is done.
pub fn emulate_cycle(&mut self) -> bool {
// Is the program finished?
if self.pc >= 4094 {
return true;
}
// Fetch and execute the opcode to execute ;
// an opcode being 2 bytes long, we need to read 2 bytes from memory
let op = (self.memory[self.pc] as u16) << 8 | (self.memory[self.pc + 1] as u16);
// println!("{:0>4X} {:0>4X}", self.opcode, self.pc); // DEBUG
self.opcode = op;
self.execute_opcode(op);
false
}
/// Execute a single opcode.
pub fn execute_opcode(&mut self, op: u16) {
// For easier matching, get the values (nibbles) A, B, C, D
// if the opcode is 0xABCD.
let opcode_tuple = (
((op & 0xF000) >> 12) as u8,
((op & 0x0F00) >> 8) as u8,
((op & 0x00F0) >> 4) as u8,
(op & 0x000F) as u8,
);
//println!("{:0>4X}/{:X},{:X},{:X},{:X}", self.opcode, a, b, c, d);
// Opcode decoding
match opcode_tuple {
(0x0, 0x0, 0xE, 0x0) => self.cls(),
(0x0, 0x0, 0xE, 0xE) => self.ret(),
// 0NNN = sys addr : ignore
(0x1, _, _, _) => self.jump_addr(op & 0x0FFF),
(0x2, _, _, _) => self.call_addr(op & 0x0FFF),
(0x3, x, _, _) => self.se_vx_nn(x, (op & 0x00FF) as u8),
(0x4, x, _, _) => self.sne_vx_nn(x, (op & 0x00FF) as u8),
(0x5, x, y, 0x0) => self.se_vx_vy(x, y),
(0x6, x, _, _) => self.ld_vx_nn(x, (op & 0x00FF) as u8),
(0x7, x, _, _) => self.add_vx_nn(x, (op & 0x00FF) as u8),
(0x8, x, y, 0x0) => self.ld_vx_vy(x, y),
(0x8, x, y, 0x1) => self.or_vx_vy(x, y),
(0x8, x, y, 0x2) => self.and_vx_vy(x, y),
(0x8, x, y, 0x3) => self.xor_vx_vy(x, y),
(0x8, x, y, 0x4) => self.add_vx_vy(x, y),
(0x8, x, y, 0x5) => self.sub_vx_vy(x, y),
(0x8, x, y, 0x6) => self.shr_vx_vy(x, y),
(0x8, x, y, 0x7) => self.subn_vx_vy(x, y),
(0x8, x, y, 0xE) => self.shl_vx_vy(x, y),
(0x9, x, y, 0x0) => self.sne_vx_vy(x, y),
(0xA, _, _, _) => self.ld_i_addr(op & 0x0FFF),
(0xB, _, _, _) => {
let v0 = self.v[0] as u16; // sacrifice to the god of borrows
self.jump_addr(op & 0x0FFF + v0);
}
(0xC, x, _, _) => self.rnd_vx_nn(x, (op & 0x00FF) as u8),
(0xD, x, y, n) => self.drw_vx_vy_n(x, y, n),
(0xE, x, 0x9, 0xE) => self.skp_vx(x),
(0xE, x, 0xA, 0x1) => self.sknp_vx(x),
(0xF, x, 0x0, 0x7) => self.ld_vx_dt(x),
(0xF, x, 0x0, 0xA) => self.ld_vx_key(x),
(0xF, x, 0x1, 0x5) => self.ld_dt_vx(x),
(0xF, x, 0x1, 0x8) => self.ld_st_vx(x),
(0xF, x, 0x1, 0xE) => self.add_i_vx(x),
(0xF, x, 0x2, 0x9) => self.ld_i_font_vx(x),
(0xF, x, 0x3, 0x3) => self.ld_mem_i_bcd_vx(x),
(0xF, x, 0x5, 0x5) => self.ld_mem_i_regs(x),
(0xF, x, 0x6, 0x5) => self.ld_regs_mem_i(x),
_ => op_not_implemented!(op, self.pc),
}
}
/// Clear the screen.
fn cls(&mut self) {
self.display.clear();
self.pc += 2;
}
/// Return from a subroutine, by setting the program counter to the address
/// popped from the stack.
fn ret(&mut self) {
self.sp -= 1;
let addr = self.stack[self.sp];
self.jump_addr(addr);
self.pc += 2;
}
/// Jump to the given address of the form 0x0NNN.
fn jump_addr(&mut self, addr: u16) {
self.pc = addr as usize;
}
/// Execute the subroutine at the provided address pushing the current
/// program counter to the stack and jumping to the given address of the
/// form 0x0NNN.
/// TODO : handle stack overflow error?
fn call_addr(&mut self, addr: u16) {
self.stack[self.sp] = self.pc as u16;
self.sp += 1;
self.jump_addr(addr);
}
/// Skip the next instruction if the value of register VX is equal to 0xNN.
fn se_vx_nn(&mut self, x: u8, nn: u8) {
self.pc += if self.v[x as usize] == nn { 4 } else { 2 };
}
/// Skip the next instruction if the value of register VX isn't equal to
/// 0xNN.
fn sne_vx_nn(&mut self, x: u8, nn: u8) {
self.pc += if self.v[x as usize]!= nn { 4 } else { 2 };
}
/// Skip the next instruction if the value of register VX is equal to the
/// value of register VY.
fn se_vx_vy(&mut self, x: u8, y: u8) {
self.pc += if self.v[x as usize] == self.v[y as usize] {
4
} else {
2
};
}
/// Skip the next instruction if the value of register VX is not equal to
/// the value of register VY.
fn sne_vx_vy(&mut self, x: u8, y: u8) {
self.pc += if self.v[x as usize]!= self.v[y as usize] {
4
} else {
2
};
}
/// Skip the next instruction if the key of index VX is currently pressed.
fn skp_vx(&mut self, x: u8) {
self.pc += match self.keypad.get_key_state(self.v[x as usize] as usize) {
Keystate::Pressed => 4,
Keystate::Released => 2,
};
}
/// Skip the next instruction if the key of index VX is currently released.
fn sknp_vx(&mut self, x: u8) {
self.pc += match self.keypad.get_key_state(self.v[x as usize] as usize) {
Keystate::Pressed => 2,
Keystate::Released => 4,
};
}
/// Store the value 0xNN in the the register VX.
fn ld_vx_nn(&mut self, x: u8, nn: u8) {
self.v[x as usize] = nn;
self.pc += 2;
}
/// Store the value of the register VY in the register VX.
fn ld_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] = self.v[y as usize];
self.pc += 2;
}
/// Store the memory address 0x0NNN in the register I.
fn ld_i_addr(&mut self, addr: u16) {
self.i = addr as usize;
self.pc += 2;
}
/// Add the value 0xNN to the register VX, wrapping around the result if
/// needed (VX is an unsigned byte so its maximum value is 255).
fn add_vx_nn(&mut self, x: u8, nn: u8) {
let new_vx_u16 = self.v[x as usize] as u16 + nn as u16; // no overflow
self.v[x as usize] = new_vx_u16 as u8; // wrap around the value
self.pc += 2;
}
/// Add the value of register VX to the value of register I.
fn add_i_vx(&mut self, x: u8) {
self.i += self.v[x as usize] as usize;
self.pc += 2;
}
/// Set VX to (VX OR VY).
fn or_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] |= self.v[y as usize];
self.pc += 2;
}
/// Set VX to (VX AND VY).
fn and_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] &= self.v[y as usize];
self.pc += 2;
}
/// Set VX to (VX XOR VY).
fn xor_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] ^= self.v[y as usize];
self.pc += 2;
}
/// Add the value of register VY to the value of register VX.
/// Set V_FLAG to 0x1 if a carry occurs, and to 0x0 otherwise.
fn add_vx_vy(&mut self, x: u8, y: u8) {
let new_vx_u16 = self.v[x as usize] as u16 + self.v[y as usize] as u16;
self.v[x as usize] = new_vx_u16 as u8;
self.v[FLAG] = if new_vx_u16 > 255 { 0x1 } else { 0x0 };
self.pc += 2;
}
/// Substract the value of register VY from the value of register VX, and
/// store the (wrapped) result in register VX.
/// Set V_FLAG to 0x1 if a borrow occurs, and to 0x0 otherwise.
fn sub_vx_vy(&mut self, x: u8, y: u8) {
let new_vx_i8 = self.v[x as usize] as i8 - self.v[y as usize] as i8;
self.v[x as usize] = new_vx_i8 as u8;
self.v[FLAG] = if new_vx_i8 < 0 { 0x1 } else { 0x0 };
self.pc += 2;
}
/// Substract the value of register VX from the value of register VY, and | fn subn_vx_vy(&mut self, x: u8, y: u8) {
let new_vx_i8 = self.v[y as usize] as i8 - self.v[x as usize] as i8;
self.v[x as usize] = new_vx_i8 as u8;
self.v[FLAG] = if new_vx_i8 < 0 { 0x1 } else { 0x0 };
self.pc += 2;
}
/// Store the value of the register VY shifted right one bit in register VX
/// and set register VF to the least significant bit prior to the shift.
/// NB : references disagree on this opcode, we use the one defined here :
/// http://mattmik.com/chip8.html
/// If shift_op_use_vy is false, will consider VX instead of VY.
fn shr_vx_vy(&mut self, x: u8, y: u8) {
let shift_on = if self.shift_op_use_vy { y } else { x };
self.v[FLAG] = self.v[shift_on as usize] & 0x01;
self.v[x as usize] = self.v[shift_on as usize] >> 1;
self.pc += 2;
}
/// Same as'shr_vx_vy' but with a left shift.
/// Set register VF to the most significant bit prior to the shift.
/// If shift_op_use_vy is false, will consider VX instead of VY.
fn shl_vx_vy(&mut self, x: u8, y: u8) {
let shift_on = if self.shift_op_use_vy { y } else { x };
self.v[FLAG] = self.v[shift_on as usize] & 0x80;
self.v[x as usize] = self.v[shift_on as usize] << 1;
self.pc += 2;
}
/// Set VX to a random byte with a mask of 0xNN.
fn rnd_vx_nn(&mut self, x: u8, nn: u8) {
self.v[x as usize] = random::<u8>() & nn;
self.pc += 2;
}
/// Draw a sprite at position VX, VY with 0xN bytes of sprite data starting
/// at the address stored in I. N is thus the height of the sprite.
/// The drawing is implemented by 'Display' as a XOR operation.
/// VF will act here as a collision flag, i.e. if any set pixel is erased
/// set it to 0x1, and to 0x0 otherwise.
fn drw_vx_vy_n(&mut self, x: u8, y: u8, n: u8) {
let pos_x = self.v[x as usize] as usize;
let pos_y = self.v[y as usize] as usize;
let mem_start = self.i;
let mem_end = self.i + n as usize;
if self
.display
.draw(pos_x, pos_y, &self.memory[mem_start..mem_end])
{
self.v[FLAG] = 0x1;
} else {
self.v[FLAG] = 0x0;
}
self.pc += 2;
}
/// Store the current value of the delay timer in register VX.
fn ld_vx_dt(&mut self, x: u8) {
self.v[x as usize] = self.delay_timer;
self.pc += 2;
}
/// Set the delay timer to the value stored in register VX.
fn ld_dt_vx(&mut self, x: u8) {
self.delay_timer = self.v[x as usize];
self.pc += 2;
}
/// Set the sound timer to the value stored in register VX.
fn ld_st_vx(&mut self, x: u8) {
self.sound_timer = self.v[x as usize];
self.pc += 2;
}
/// Wait for a key press and store the result in the register VX.
/// Implementation : the emulation application must trigger the
/// 'end_wait_for_key_press' function ; this allows to achieve better
/// decoupling from the framerate.
fn ld_vx_key(&mut self, x: u8) {
self.wait_for_key = (true, x);
/*for i in 0..16 {
match self.keypad.get_key_state(i) {
Keystate::Pressed => {
self.v[x as usize] = i as u8;
self.pc += 2;
break;
}
Keystate::Released => {},
}
}*/
}
/// Set I to the memory address of the sprite data corresponding to the
/// hexadecimal digit (0x0..0xF) stored in register VX.
/// Will use the internal fontset stored in memory.
fn ld_i_font_vx(&mut self, x: u8) {
// the font set is in the memory range 0x0..0x80
// and each character is represented by 5 bytes
self.i = (self | /// store the (wrapped) result in register VX.
/// Set V_FLAG to 0x1 if a borrow occurs, and to 0x0 otherwise. | random_line_split |
vm.rs | {
/// The current opcode.
opcode: u16,
/// The chip's 4096 bytes of memory.
pub memory: [u8; 4096], // TEMPORARY pub for debug purposes
/// The chip's 16 registers, from V0 to VF.
/// VF is used for the 'carry flag'.
v: [u8; 16],
/// Index register.
i: usize,
/// Program counter.
pc: usize,
/// The stack, used for subroutine operations.
/// By default has 16 levels of nesting.
pub stack: [u16; STACK_SIZE],
/// Stack pointer.
pub sp: usize,
// Timer registers, must be updated at 60 Hz by the emulator.
pub delay_timer: u8,
pub sound_timer: u8,
/// Screen component.
pub display: Display,
/// Input component.
pub keypad: Keypad,
/// Is the virtual machine waiting for a keypress?
/// If so, when any key is pressed store its index in VX where X is
/// the value stored in this tuple.
pub wait_for_key: (bool, u8),
/// Implementation option.
/// Should the shifting opcodes 8XY6 and 8XYE use the original implementation,
/// i.e. set VX to VY shifted respectively right and left by one bit?
/// If false, the VM will instead consider as many ROMs seem to do that Y=X.
/// See http://mattmik.com/chip8.html for more detail.
shift_op_use_vy: bool,
}
/// Macro for handling invalid/unimplemented opcodes.
/// As of now only prints a error message, could maybe panic in the future.
macro_rules! op_not_implemented {
($op: expr, $pc: expr) => {
println!(
"Not implemented opcode {:0>4X} at {:0>5X}",
$op as usize, $pc
);
};
}
impl Chip8 {
/// Create and return a new, initialized Chip8 virtual machine.
pub fn new() -> Chip8 {
let mut chip8 = Chip8 {
opcode: 0u16,
memory: [0u8; 4096],
v: [0u8; 16],
i: 0usize,
pc: 0usize,
stack: [0u16; STACK_SIZE],
sp: 0usize,
delay_timer: 0u8,
sound_timer: 0u8,
display: Display::new(),
keypad: Keypad::new(),
wait_for_key: (false, 0x0),
shift_op_use_vy: false,
};
// load the font set in memory in the space [0x0, 0x200[ = [0, 80[
for i in 0..80 {
chip8.memory[i] = FONT_SET[i];
}
// the program space starts at 0x200
chip8.pc = 0x200;
chip8
}
/// Reinitialize the virtual machine's state but keep the loaded program
/// in memory.
pub fn reset(&mut self) {
self.opcode = 0u16;
self.v = [0u8; 16];
self.i = 0usize;
self.pc = 0x200;
self.stack = [0u16; STACK_SIZE];
self.sp = 0usize;
self.delay_timer = 0u8;
self.sound_timer = 0u8;
self.display = Display::new();
self.keypad = Keypad::new();
self.wait_for_key = (false, 0x0);
}
/// Set the shift_op_use_vy flag.
pub fn should_shift_op_use_vy(&mut self, b: bool) {
self.shift_op_use_vy = b;
}
/// Is the CPU waiting for a key press?
pub fn is_waiting_for_key(&self) -> bool {
self.wait_for_key.0
}
/// Called by the emulator application to inform the virtual machine
/// waiting for a key pressed that a key has been pressed.
pub fn end_wait_for_key(&mut self, key_index: usize) {
if!self.is_waiting_for_key() {
warn!(concat!(
"Chip8::end_wait_for_key_press called but the VM ",
"wasn't waiting for a key press - ignoring"
));
return;
}
self.v[self.wait_for_key.1 as usize] = key_index as u8;
self.wait_for_key.0 = false;
self.pc += 2;
}
/// Get the value stored in the register VX.
pub fn register(&self, x: usize) -> u8 {
self.v[x]
}
/// Get the index register.
pub fn index(&self) -> usize {
self.i
}
/// Get the program counter value.
pub fn pc(&self) -> usize {
self.pc
}
/// Load a Chip8 rom from the given filepath.
/// If the operation fails, return a String explaining why.
pub fn load(&mut self, filepath: &Path) -> Option<String> {
let file = match File::open(filepath) {
Ok(f) => f,
Err(ref why) => {
return Some(format!(
"couldn't open rom file \"{}\" : {}",
filepath.display(),
Error::description(why)
));
}
};
for (i, b) in file.bytes().enumerate() {
//if b.is_none() /* EOF */ { break; }
match b {
Ok(byte) => self.memory[self.pc + i] = byte,
Err(e) => {
return Some(format!("error while reading ROM : {}", e.to_string()));
}
}
}
None
}
/// Emulate a Chip8 CPU cycle.
/// Return true if the loaded program is done.
pub fn emulate_cycle(&mut self) -> bool {
// Is the program finished?
if self.pc >= 4094 {
return true;
}
// Fetch and execute the opcode to execute ;
// an opcode being 2 bytes long, we need to read 2 bytes from memory
let op = (self.memory[self.pc] as u16) << 8 | (self.memory[self.pc + 1] as u16);
// println!("{:0>4X} {:0>4X}", self.opcode, self.pc); // DEBUG
self.opcode = op;
self.execute_opcode(op);
false
}
/// Execute a single opcode.
pub fn execute_opcode(&mut self, op: u16) | (0x4, x, _, _) => self.sne_vx_nn(x, (op & 0x00FF) as u8),
(0x5, x, y, 0x0) => self.se_vx_vy(x, y),
(0x6, x, _, _) => self.ld_vx_nn(x, (op & 0x00FF) as u8),
(0x7, x, _, _) => self.add_vx_nn(x, (op & 0x00FF) as u8),
(0x8, x, y, 0x0) => self.ld_vx_vy(x, y),
(0x8, x, y, 0x1) => self.or_vx_vy(x, y),
(0x8, x, y, 0x2) => self.and_vx_vy(x, y),
(0x8, x, y, 0x3) => self.xor_vx_vy(x, y),
(0x8, x, y, 0x4) => self.add_vx_vy(x, y),
(0x8, x, y, 0x5) => self.sub_vx_vy(x, y),
(0x8, x, y, 0x6) => self.shr_vx_vy(x, y),
(0x8, x, y, 0x7) => self.subn_vx_vy(x, y),
(0x8, x, y, 0xE) => self.shl_vx_vy(x, y),
(0x9, x, y, 0x0) => self.sne_vx_vy(x, y),
(0xA, _, _, _) => self.ld_i_addr(op & 0x0FFF),
(0xB, _, _, _) => {
let v0 = self.v[0] as u16; // sacrifice to the god of borrows
self.jump_addr(op & 0x0FFF + v0);
}
(0xC, x, _, _) => self.rnd_vx_nn(x, (op & 0x00FF) as u8),
(0xD, x, y, n) => self.drw_vx_vy_n(x, y, n),
(0xE, x, 0x9, 0xE) => self.skp_vx(x),
(0xE, x, 0xA, 0x1) => self.sknp_vx(x),
(0xF, x, 0x0, 0x7) => self.ld_vx_dt(x),
(0xF, x, 0x0, 0xA) => self.ld_vx_key(x),
(0xF, x, 0x1, 0x5) => self.ld_dt_vx(x),
(0xF, x, 0x1, 0x8) => self.ld_st_vx(x),
(0xF, x, 0x1, 0xE) => self.add_i_vx(x),
(0xF, x, 0x2, 0x9) => self.ld_i_font_vx(x),
(0xF, x, 0x3, 0x3) => self.ld_mem_i_bcd_vx(x),
(0xF, x, 0x5, 0x5) => self.ld_mem_i_regs(x),
(0xF, x, 0x6, 0x5) => self.ld_regs_mem_i(x),
_ => op_not_implemented!(op, self.pc),
}
}
/// Clear the screen.
fn cls(&mut self) {
self.display.clear();
self.pc += 2;
}
/// Return from a subroutine, by setting the program counter to the address
/// popped from the stack.
fn ret(&mut self) {
self.sp -= 1;
let addr = self.stack[self.sp];
self.jump_addr(addr);
self.pc += 2;
}
/// Jump to the given address of the form 0x0NNN.
fn jump_addr(&mut self, addr: u16) {
self.pc = addr as usize;
}
/// Execute the subroutine at the provided address pushing the current
/// program counter to the stack and jumping to the given address of the
/// form 0x0NNN.
/// TODO : handle stack overflow error?
fn call_addr(&mut self, addr: u16) {
self.stack[self.sp] = self.pc as u16;
self.sp += 1;
self.jump_addr(addr);
}
/// Skip the next instruction if the value of register VX is equal to 0xNN.
fn se_vx_nn(&mut self, x: u8, nn: u8) {
self.pc += if self.v[x as usize] == nn { 4 } else { 2 };
}
/// Skip the next instruction if the value of register VX isn't equal to
/// 0xNN.
fn sne_vx_nn(&mut self, x: u8, nn: u8) {
self.pc += if self.v[x as usize]!= nn { 4 } else { 2 };
}
/// Skip the next instruction if the value of register VX is equal to the
/// value of register VY.
fn se_vx_vy(&mut self, x: u8, y: u8) {
self.pc += if self.v[x as usize] == self.v[y as usize] {
4
} else {
2
};
}
/// Skip the next instruction if the value of register VX is not equal to
/// the value of register VY.
fn sne_vx_vy(&mut self, x: u8, y: u8) {
self.pc += if self.v[x as usize]!= self.v[y as usize] {
4
} else {
2
};
}
/// Skip the next instruction if the key of index VX is currently pressed.
fn skp_vx(&mut self, x: u8) {
self.pc += match self.keypad.get_key_state(self.v[x as usize] as usize) {
Keystate::Pressed => 4,
Keystate::Released => 2,
};
}
/// Skip the next instruction if the key of index VX is currently released.
fn sknp_vx(&mut self, x: u8) {
self.pc += match self.keypad.get_key_state(self.v[x as usize] as usize) {
Keystate::Pressed => 2,
Keystate::Released => 4,
};
}
/// Store the value 0xNN in the the register VX.
fn ld_vx_nn(&mut self, x: u8, nn: u8) {
self.v[x as usize] = nn;
self.pc += 2;
}
/// Store the value of the register VY in the register VX.
fn ld_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] = self.v[y as usize];
self.pc += 2;
}
/// Store the memory address 0x0NNN in the register I.
fn ld_i_addr(&mut self, addr: u16) {
self.i = addr as usize;
self.pc += 2;
}
/// Add the value 0xNN to the register VX, wrapping around the result if
/// needed (VX is an unsigned byte so its maximum value is 255).
fn add_vx_nn(&mut self, x: u8, nn: u8) {
let new_vx_u16 = self.v[x as usize] as u16 + nn as u16; // no overflow
self.v[x as usize] = new_vx_u16 as u8; // wrap around the value
self.pc += 2;
}
/// Add the value of register VX to the value of register I.
fn add_i_vx(&mut self, x: u8) {
self.i += self.v[x as usize] as usize;
self.pc += 2;
}
/// Set VX to (VX OR VY).
fn or_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] |= self.v[y as usize];
self.pc += 2;
}
/// Set VX to (VX AND VY).
fn and_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] &= self.v[y as usize];
self.pc += 2;
}
/// Set VX to (VX XOR VY).
fn xor_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] ^= self.v[y as usize];
self.pc += 2;
}
/// Add the value of register VY to the value of register VX.
/// Set V_FLAG to 0x1 if a carry occurs, and to 0x0 otherwise.
fn add_vx_vy(&mut self, x: u8, y: u8) {
let new_vx_u16 = self.v[x as usize] as u16 + self.v[y as usize] as u16;
self.v[x as usize] = new_vx_u16 as u8;
self.v[FLAG] = if new_vx_u16 > 255 { 0x1 } else { 0x0 };
self.pc += 2;
}
/// Substract the value of register VY from the value of register VX, and
/// store the (wrapped) result in register VX.
/// Set V_FLAG to 0x1 if a borrow occurs, and to 0x0 otherwise.
fn sub_vx_vy(&mut self, x: u8, y: u8) {
let new_vx_i8 = self.v[x as usize] as i8 - self.v[y as usize] as i8;
self.v[x as usize] = new_vx_i8 as u8;
self.v[FLAG] = if new_vx_i8 < 0 { 0x1 } else { 0x0 };
self.pc += 2;
}
/// Substract the value of register VX from the value of register VY, and
/// store the (wrapped) result in register VX.
/// Set V_FLAG to 0x1 if a borrow occurs, and to 0x0 otherwise.
fn subn_vx_vy(&mut self, x: u8, y: u8) {
let new_vx_i8 = self.v[y as usize] as i8 - self.v[x as usize] as i8;
self.v[x as usize] = new_vx_i8 as u8;
self.v[FLAG] = if new_vx_i8 < 0 { 0x1 } else { 0x0 };
self.pc += 2;
}
/// Store the value of the register VY shifted right one bit in register VX
/// and set register VF to the least significant bit prior to the shift.
/// NB : references disagree on this opcode, we use the one defined here :
/// http://mattmik.com/chip8.html
/// If shift_op_use_vy is false, will consider VX instead of VY.
fn shr_vx_vy(&mut self, x: u8, y: u8) {
let shift_on = if self.shift_op_use_vy { y } else { x };
self.v[FLAG] = self.v[shift_on as usize] & 0x01;
self.v[x as usize] = self.v[shift_on as usize] >> 1;
self.pc += 2;
}
/// Same as'shr_vx_vy' but with a left shift.
/// Set register VF to the most significant bit prior to the shift.
/// If shift_op_use_vy is false, will consider VX instead of VY.
fn shl_vx_vy(&mut self, x: u8, y: u8) {
let shift_on = if self.shift_op_use_vy { y } else { x };
self.v[FLAG] = self.v[shift_on as usize] & 0x80;
self.v[x as usize] = self.v[shift_on as usize] << 1;
self.pc += 2;
}
/// Set VX to a random byte with a mask of 0xNN.
fn rnd_vx_nn(&mut self, x: u8, nn: u8) {
self.v[x as usize] = random::<u8>() & nn;
self.pc += 2;
}
/// Draw a sprite at position VX, VY with 0xN bytes of sprite data starting
/// at the address stored in I. N is thus the height of the sprite.
/// The drawing is implemented by 'Display' as a XOR operation.
/// VF will act here as a collision flag, i.e. if any set pixel is erased
/// set it to 0x1, and to 0x0 otherwise.
fn drw_vx_vy_n(&mut self, x: u8, y: u8, n: u8) {
let pos_x = self.v[x as usize] as usize;
let pos_y = self.v[y as usize] as usize;
let mem_start = self.i;
let mem_end = self.i + n as usize;
if self
.display
.draw(pos_x, pos_y, &self.memory[mem_start..mem_end])
{
self.v[FLAG] = 0x1;
} else {
self.v[FLAG] = 0x0;
}
self.pc += 2;
}
/// Store the current value of the delay timer in register VX.
fn ld_vx_dt(&mut self, x: u8) {
self.v[x as usize] = self.delay_timer;
self.pc += 2;
}
/// Set the delay timer to the value stored in register VX.
fn ld_dt_vx(&mut self, x: u8) {
self.delay_timer = self.v[x as usize];
self.pc += 2;
}
/// Set the sound timer to the value stored in register VX.
fn ld_st_vx(&mut self, x: u8) {
self.sound_timer = self.v[x as usize];
self.pc += 2;
}
/// Wait for a key press and store the result in the register VX.
/// Implementation : the emulation application must trigger the
/// 'end_wait_for_key_press' function ; this allows to achieve better
/// decoupling from the framerate.
fn ld_vx_key(&mut self, x: u8) {
self.wait_for_key = (true, x);
/*for i in 0..16 {
match self.keypad.get_key_state(i) {
Keystate::Pressed => {
self.v[x as usize] = i as u8;
self.pc += 2;
break;
}
Keystate::Released => {},
}
}*/
}
/// Set I to the memory address of the sprite data corresponding to the
/// hexadecimal digit (0x0..0xF) stored in register VX.
/// Will use the internal fontset stored in memory.
fn ld_i_font_vx(&mut self, x: u8) {
// the font set is in the memory range 0x0..0x80
// and each character is represented by 5 bytes
self.i = | {
// For easier matching, get the values (nibbles) A, B, C, D
// if the opcode is 0xABCD.
let opcode_tuple = (
((op & 0xF000) >> 12) as u8,
((op & 0x0F00) >> 8) as u8,
((op & 0x00F0) >> 4) as u8,
(op & 0x000F) as u8,
);
//println!("{:0>4X}/{:X},{:X},{:X},{:X}", self.opcode, a, b, c, d);
// Opcode decoding
match opcode_tuple {
(0x0, 0x0, 0xE, 0x0) => self.cls(),
(0x0, 0x0, 0xE, 0xE) => self.ret(),
// 0NNN = sys addr : ignore
(0x1, _, _, _) => self.jump_addr(op & 0x0FFF),
(0x2, _, _, _) => self.call_addr(op & 0x0FFF),
(0x3, x, _, _) => self.se_vx_nn(x, (op & 0x00FF) as u8), | identifier_body |
vm.rs | {
/// The current opcode.
opcode: u16,
/// The chip's 4096 bytes of memory.
pub memory: [u8; 4096], // TEMPORARY pub for debug purposes
/// The chip's 16 registers, from V0 to VF.
/// VF is used for the 'carry flag'.
v: [u8; 16],
/// Index register.
i: usize,
/// Program counter.
pc: usize,
/// The stack, used for subroutine operations.
/// By default has 16 levels of nesting.
pub stack: [u16; STACK_SIZE],
/// Stack pointer.
pub sp: usize,
// Timer registers, must be updated at 60 Hz by the emulator.
pub delay_timer: u8,
pub sound_timer: u8,
/// Screen component.
pub display: Display,
/// Input component.
pub keypad: Keypad,
/// Is the virtual machine waiting for a keypress?
/// If so, when any key is pressed store its index in VX where X is
/// the value stored in this tuple.
pub wait_for_key: (bool, u8),
/// Implementation option.
/// Should the shifting opcodes 8XY6 and 8XYE use the original implementation,
/// i.e. set VX to VY shifted respectively right and left by one bit?
/// If false, the VM will instead consider as many ROMs seem to do that Y=X.
/// See http://mattmik.com/chip8.html for more detail.
shift_op_use_vy: bool,
}
/// Macro for handling invalid/unimplemented opcodes.
/// As of now only prints a error message, could maybe panic in the future.
macro_rules! op_not_implemented {
($op: expr, $pc: expr) => {
println!(
"Not implemented opcode {:0>4X} at {:0>5X}",
$op as usize, $pc
);
};
}
impl Chip8 {
/// Create and return a new, initialized Chip8 virtual machine.
pub fn new() -> Chip8 {
let mut chip8 = Chip8 {
opcode: 0u16,
memory: [0u8; 4096],
v: [0u8; 16],
i: 0usize,
pc: 0usize,
stack: [0u16; STACK_SIZE],
sp: 0usize,
delay_timer: 0u8,
sound_timer: 0u8,
display: Display::new(),
keypad: Keypad::new(),
wait_for_key: (false, 0x0),
shift_op_use_vy: false,
};
// load the font set in memory in the space [0x0, 0x200[ = [0, 80[
for i in 0..80 {
chip8.memory[i] = FONT_SET[i];
}
// the program space starts at 0x200
chip8.pc = 0x200;
chip8
}
/// Reinitialize the virtual machine's state but keep the loaded program
/// in memory.
pub fn reset(&mut self) {
self.opcode = 0u16;
self.v = [0u8; 16];
self.i = 0usize;
self.pc = 0x200;
self.stack = [0u16; STACK_SIZE];
self.sp = 0usize;
self.delay_timer = 0u8;
self.sound_timer = 0u8;
self.display = Display::new();
self.keypad = Keypad::new();
self.wait_for_key = (false, 0x0);
}
/// Set the shift_op_use_vy flag.
pub fn | (&mut self, b: bool) {
self.shift_op_use_vy = b;
}
/// Is the CPU waiting for a key press?
pub fn is_waiting_for_key(&self) -> bool {
self.wait_for_key.0
}
/// Called by the emulator application to inform the virtual machine
/// waiting for a key pressed that a key has been pressed.
pub fn end_wait_for_key(&mut self, key_index: usize) {
if!self.is_waiting_for_key() {
warn!(concat!(
"Chip8::end_wait_for_key_press called but the VM ",
"wasn't waiting for a key press - ignoring"
));
return;
}
self.v[self.wait_for_key.1 as usize] = key_index as u8;
self.wait_for_key.0 = false;
self.pc += 2;
}
/// Get the value stored in the register VX.
pub fn register(&self, x: usize) -> u8 {
self.v[x]
}
/// Get the index register.
pub fn index(&self) -> usize {
self.i
}
/// Get the program counter value.
pub fn pc(&self) -> usize {
self.pc
}
/// Load a Chip8 rom from the given filepath.
/// If the operation fails, return a String explaining why.
pub fn load(&mut self, filepath: &Path) -> Option<String> {
let file = match File::open(filepath) {
Ok(f) => f,
Err(ref why) => {
return Some(format!(
"couldn't open rom file \"{}\" : {}",
filepath.display(),
Error::description(why)
));
}
};
for (i, b) in file.bytes().enumerate() {
//if b.is_none() /* EOF */ { break; }
match b {
Ok(byte) => self.memory[self.pc + i] = byte,
Err(e) => {
return Some(format!("error while reading ROM : {}", e.to_string()));
}
}
}
None
}
/// Emulate a Chip8 CPU cycle.
/// Return true if the loaded program is done.
pub fn emulate_cycle(&mut self) -> bool {
// Is the program finished?
if self.pc >= 4094 {
return true;
}
// Fetch and execute the opcode to execute ;
// an opcode being 2 bytes long, we need to read 2 bytes from memory
let op = (self.memory[self.pc] as u16) << 8 | (self.memory[self.pc + 1] as u16);
// println!("{:0>4X} {:0>4X}", self.opcode, self.pc); // DEBUG
self.opcode = op;
self.execute_opcode(op);
false
}
/// Execute a single opcode.
pub fn execute_opcode(&mut self, op: u16) {
// For easier matching, get the values (nibbles) A, B, C, D
// if the opcode is 0xABCD.
let opcode_tuple = (
((op & 0xF000) >> 12) as u8,
((op & 0x0F00) >> 8) as u8,
((op & 0x00F0) >> 4) as u8,
(op & 0x000F) as u8,
);
//println!("{:0>4X}/{:X},{:X},{:X},{:X}", self.opcode, a, b, c, d);
// Opcode decoding
match opcode_tuple {
(0x0, 0x0, 0xE, 0x0) => self.cls(),
(0x0, 0x0, 0xE, 0xE) => self.ret(),
// 0NNN = sys addr : ignore
(0x1, _, _, _) => self.jump_addr(op & 0x0FFF),
(0x2, _, _, _) => self.call_addr(op & 0x0FFF),
(0x3, x, _, _) => self.se_vx_nn(x, (op & 0x00FF) as u8),
(0x4, x, _, _) => self.sne_vx_nn(x, (op & 0x00FF) as u8),
(0x5, x, y, 0x0) => self.se_vx_vy(x, y),
(0x6, x, _, _) => self.ld_vx_nn(x, (op & 0x00FF) as u8),
(0x7, x, _, _) => self.add_vx_nn(x, (op & 0x00FF) as u8),
(0x8, x, y, 0x0) => self.ld_vx_vy(x, y),
(0x8, x, y, 0x1) => self.or_vx_vy(x, y),
(0x8, x, y, 0x2) => self.and_vx_vy(x, y),
(0x8, x, y, 0x3) => self.xor_vx_vy(x, y),
(0x8, x, y, 0x4) => self.add_vx_vy(x, y),
(0x8, x, y, 0x5) => self.sub_vx_vy(x, y),
(0x8, x, y, 0x6) => self.shr_vx_vy(x, y),
(0x8, x, y, 0x7) => self.subn_vx_vy(x, y),
(0x8, x, y, 0xE) => self.shl_vx_vy(x, y),
(0x9, x, y, 0x0) => self.sne_vx_vy(x, y),
(0xA, _, _, _) => self.ld_i_addr(op & 0x0FFF),
(0xB, _, _, _) => {
let v0 = self.v[0] as u16; // sacrifice to the god of borrows
self.jump_addr(op & 0x0FFF + v0);
}
(0xC, x, _, _) => self.rnd_vx_nn(x, (op & 0x00FF) as u8),
(0xD, x, y, n) => self.drw_vx_vy_n(x, y, n),
(0xE, x, 0x9, 0xE) => self.skp_vx(x),
(0xE, x, 0xA, 0x1) => self.sknp_vx(x),
(0xF, x, 0x0, 0x7) => self.ld_vx_dt(x),
(0xF, x, 0x0, 0xA) => self.ld_vx_key(x),
(0xF, x, 0x1, 0x5) => self.ld_dt_vx(x),
(0xF, x, 0x1, 0x8) => self.ld_st_vx(x),
(0xF, x, 0x1, 0xE) => self.add_i_vx(x),
(0xF, x, 0x2, 0x9) => self.ld_i_font_vx(x),
(0xF, x, 0x3, 0x3) => self.ld_mem_i_bcd_vx(x),
(0xF, x, 0x5, 0x5) => self.ld_mem_i_regs(x),
(0xF, x, 0x6, 0x5) => self.ld_regs_mem_i(x),
_ => op_not_implemented!(op, self.pc),
}
}
/// Clear the screen.
fn cls(&mut self) {
self.display.clear();
self.pc += 2;
}
/// Return from a subroutine, by setting the program counter to the address
/// popped from the stack.
fn ret(&mut self) {
self.sp -= 1;
let addr = self.stack[self.sp];
self.jump_addr(addr);
self.pc += 2;
}
/// Jump to the given address of the form 0x0NNN.
fn jump_addr(&mut self, addr: u16) {
self.pc = addr as usize;
}
/// Execute the subroutine at the provided address pushing the current
/// program counter to the stack and jumping to the given address of the
/// form 0x0NNN.
/// TODO : handle stack overflow error?
fn call_addr(&mut self, addr: u16) {
self.stack[self.sp] = self.pc as u16;
self.sp += 1;
self.jump_addr(addr);
}
/// Skip the next instruction if the value of register VX is equal to 0xNN.
fn se_vx_nn(&mut self, x: u8, nn: u8) {
self.pc += if self.v[x as usize] == nn { 4 } else { 2 };
}
/// Skip the next instruction if the value of register VX isn't equal to
/// 0xNN.
fn sne_vx_nn(&mut self, x: u8, nn: u8) {
self.pc += if self.v[x as usize]!= nn { 4 } else { 2 };
}
/// Skip the next instruction if the value of register VX is equal to the
/// value of register VY.
fn se_vx_vy(&mut self, x: u8, y: u8) {
self.pc += if self.v[x as usize] == self.v[y as usize] {
4
} else {
2
};
}
/// Skip the next instruction if the value of register VX is not equal to
/// the value of register VY.
fn sne_vx_vy(&mut self, x: u8, y: u8) {
self.pc += if self.v[x as usize]!= self.v[y as usize] {
4
} else {
2
};
}
/// Skip the next instruction if the key of index VX is currently pressed.
fn skp_vx(&mut self, x: u8) {
self.pc += match self.keypad.get_key_state(self.v[x as usize] as usize) {
Keystate::Pressed => 4,
Keystate::Released => 2,
};
}
/// Skip the next instruction if the key of index VX is currently released.
fn sknp_vx(&mut self, x: u8) {
self.pc += match self.keypad.get_key_state(self.v[x as usize] as usize) {
Keystate::Pressed => 2,
Keystate::Released => 4,
};
}
/// Store the value 0xNN in the the register VX.
fn ld_vx_nn(&mut self, x: u8, nn: u8) {
self.v[x as usize] = nn;
self.pc += 2;
}
/// Store the value of the register VY in the register VX.
fn ld_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] = self.v[y as usize];
self.pc += 2;
}
/// Store the memory address 0x0NNN in the register I.
fn ld_i_addr(&mut self, addr: u16) {
self.i = addr as usize;
self.pc += 2;
}
/// Add the value 0xNN to the register VX, wrapping around the result if
/// needed (VX is an unsigned byte so its maximum value is 255).
fn add_vx_nn(&mut self, x: u8, nn: u8) {
let new_vx_u16 = self.v[x as usize] as u16 + nn as u16; // no overflow
self.v[x as usize] = new_vx_u16 as u8; // wrap around the value
self.pc += 2;
}
/// Add the value of register VX to the value of register I.
fn add_i_vx(&mut self, x: u8) {
self.i += self.v[x as usize] as usize;
self.pc += 2;
}
/// Set VX to (VX OR VY).
fn or_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] |= self.v[y as usize];
self.pc += 2;
}
/// Set VX to (VX AND VY).
fn and_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] &= self.v[y as usize];
self.pc += 2;
}
/// Set VX to (VX XOR VY).
fn xor_vx_vy(&mut self, x: u8, y: u8) {
self.v[x as usize] ^= self.v[y as usize];
self.pc += 2;
}
/// Add the value of register VY to the value of register VX.
/// Set V_FLAG to 0x1 if a carry occurs, and to 0x0 otherwise.
fn add_vx_vy(&mut self, x: u8, y: u8) {
let new_vx_u16 = self.v[x as usize] as u16 + self.v[y as usize] as u16;
self.v[x as usize] = new_vx_u16 as u8;
self.v[FLAG] = if new_vx_u16 > 255 { 0x1 } else { 0x0 };
self.pc += 2;
}
/// Substract the value of register VY from the value of register VX, and
/// store the (wrapped) result in register VX.
/// Set V_FLAG to 0x1 if a borrow occurs, and to 0x0 otherwise.
fn sub_vx_vy(&mut self, x: u8, y: u8) {
let new_vx_i8 = self.v[x as usize] as i8 - self.v[y as usize] as i8;
self.v[x as usize] = new_vx_i8 as u8;
self.v[FLAG] = if new_vx_i8 < 0 { 0x1 } else { 0x0 };
self.pc += 2;
}
/// Substract the value of register VX from the value of register VY, and
/// store the (wrapped) result in register VX.
/// Set V_FLAG to 0x1 if a borrow occurs, and to 0x0 otherwise.
fn subn_vx_vy(&mut self, x: u8, y: u8) {
let new_vx_i8 = self.v[y as usize] as i8 - self.v[x as usize] as i8;
self.v[x as usize] = new_vx_i8 as u8;
self.v[FLAG] = if new_vx_i8 < 0 { 0x1 } else { 0x0 };
self.pc += 2;
}
/// Store the value of the register VY shifted right one bit in register VX
/// and set register VF to the least significant bit prior to the shift.
/// NB : references disagree on this opcode, we use the one defined here :
/// http://mattmik.com/chip8.html
/// If shift_op_use_vy is false, will consider VX instead of VY.
fn shr_vx_vy(&mut self, x: u8, y: u8) {
let shift_on = if self.shift_op_use_vy { y } else { x };
self.v[FLAG] = self.v[shift_on as usize] & 0x01;
self.v[x as usize] = self.v[shift_on as usize] >> 1;
self.pc += 2;
}
/// Same as'shr_vx_vy' but with a left shift.
/// Set register VF to the most significant bit prior to the shift.
/// If shift_op_use_vy is false, will consider VX instead of VY.
fn shl_vx_vy(&mut self, x: u8, y: u8) {
let shift_on = if self.shift_op_use_vy { y } else { x };
self.v[FLAG] = self.v[shift_on as usize] & 0x80;
self.v[x as usize] = self.v[shift_on as usize] << 1;
self.pc += 2;
}
/// Set VX to a random byte with a mask of 0xNN.
fn rnd_vx_nn(&mut self, x: u8, nn: u8) {
self.v[x as usize] = random::<u8>() & nn;
self.pc += 2;
}
/// Draw a sprite at position VX, VY with 0xN bytes of sprite data starting
/// at the address stored in I. N is thus the height of the sprite.
/// The drawing is implemented by 'Display' as a XOR operation.
/// VF will act here as a collision flag, i.e. if any set pixel is erased
/// set it to 0x1, and to 0x0 otherwise.
fn drw_vx_vy_n(&mut self, x: u8, y: u8, n: u8) {
let pos_x = self.v[x as usize] as usize;
let pos_y = self.v[y as usize] as usize;
let mem_start = self.i;
let mem_end = self.i + n as usize;
if self
.display
.draw(pos_x, pos_y, &self.memory[mem_start..mem_end])
{
self.v[FLAG] = 0x1;
} else {
self.v[FLAG] = 0x0;
}
self.pc += 2;
}
/// Store the current value of the delay timer in register VX.
fn ld_vx_dt(&mut self, x: u8) {
self.v[x as usize] = self.delay_timer;
self.pc += 2;
}
/// Set the delay timer to the value stored in register VX.
fn ld_dt_vx(&mut self, x: u8) {
self.delay_timer = self.v[x as usize];
self.pc += 2;
}
/// Set the sound timer to the value stored in register VX.
fn ld_st_vx(&mut self, x: u8) {
self.sound_timer = self.v[x as usize];
self.pc += 2;
}
/// Wait for a key press and store the result in the register VX.
/// Implementation : the emulation application must trigger the
/// 'end_wait_for_key_press' function ; this allows to achieve better
/// decoupling from the framerate.
fn ld_vx_key(&mut self, x: u8) {
self.wait_for_key = (true, x);
/*for i in 0..16 {
match self.keypad.get_key_state(i) {
Keystate::Pressed => {
self.v[x as usize] = i as u8;
self.pc += 2;
break;
}
Keystate::Released => {},
}
}*/
}
/// Set I to the memory address of the sprite data corresponding to the
/// hexadecimal digit (0x0..0xF) stored in register VX.
/// Will use the internal fontset stored in memory.
fn ld_i_font_vx(&mut self, x: u8) {
// the font set is in the memory range 0x0..0x80
// and each character is represented by 5 bytes
self.i = | should_shift_op_use_vy | identifier_name |
mod.rs | use md5;
use rustc_serialize::hex::ToHex;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
enum Dir {
Up,
Down,
Left,
Right,
}
impl Dir {
fn as_char(&self) -> char {
match *self {
Dir::Up => 'U',
Dir::Down => 'D',
Dir::Left => 'L',
Dir::Right => 'R',
}
}
}
fn path_as_string(path: &Vec<Dir>) -> String {
path.iter().map(|d| d.as_char()).collect()
}
trait CanBeDoor {
fn is_door(&self) -> bool;
}
impl CanBeDoor for char {
fn is_door(&self) -> bool {
match *self {
'b' | 'c' | 'd' | 'e' | 'f' => true,
_ => false,
}
}
}
fn open_doors_here(passcode: &str, path: &Vec<Dir>) -> Vec<Dir> {
let mut hash_source = passcode.to_owned();
hash_source.push_str(&path_as_string(path));
let hash = md5::compute(hash_source.as_bytes()).to_hex();
// println!("hash computed {} from {}",
// hash.chars().take(4).collect::<String>(),
// hash_source);
let mut i = hash.chars();
let first = i.next().unwrap();
let second = i.next().unwrap();
let third = i.next().unwrap();
let fourth = i.next().unwrap();
let mut result = Vec::new();
if first.is_door() {
result.push(Dir::Up);
}
if second.is_door() {
result.push(Dir::Down);
}
if third.is_door() {
result.push(Dir::Left);
}
if fourth.is_door() {
result.push(Dir::Right);
}
result
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct Point {
x: usize,
y: usize,
}
impl Point {
fn go(&self, dir: Dir) -> Point {
match dir {
Dir::Left => Point { x: self.x - 1,..*self },
Dir::Right => Point { x: self.x + 1,..*self },
Dir::Up => Point { y: self.y - 1,..*self },
Dir::Down => Point { y: self.y + 1,..*self },
}
}
}
#[derive(Debug)]
struct Maze {
width: usize,
height: usize,
destination: Point,
calculated: HashMap<Point, HashMap<Vec<Dir>, Vec<Dir>>>,
passcode: String,
}
impl Maze {
fn | (passcode: String) -> Maze {
Maze {
width: 4,
height: 4,
destination: Point { x: 3, y: 3 },
calculated: HashMap::new(),
passcode: passcode,
}
}
/// have we visited this room and had this set of doors before?
fn have_visited(&mut self, room: Point, path: &Vec<Dir>) -> bool {
let doors = self.get_doors_for(room.clone(), path.clone());
// println!("Have I been to {:?} via {:?} before? I see doors {:?}",
// room,
// path,
// doors);
let r = self.calculated.get(&room);
let result = match r {
Some(r) => {
let previous_door_sets_here =
r.iter().filter(|&(k, _)| k!= path).map(|(_, v)| v).collect::<Vec<_>>();
// println!("Previous doors here {:?}", previous_door_sets_here);
previous_door_sets_here.into_iter().any(|d| d.clone() == doors)
}
None => false,
};
result
}
fn get_doors_for(&mut self, room: Point, path: Vec<Dir>) -> Vec<Dir> {
if room == self.destination {
// don't need to add doors here
let r = self.calculated.entry(room).or_insert(HashMap::new());
r.insert(path, Vec::new());
return Vec::new();
}
if let Some(r) = self.calculated.clone().get_mut(&room) {
match r.clone().get(&path) {
Some(p) => p.clone(),
None => {
let doors = open_doors_here(&self.passcode, &path);
r.insert(path.clone(), doors.clone());
doors
}
}
} else {
let doors = open_doors_here(&self.passcode, &path);
let mut newmap = HashMap::new();
newmap.insert(path.clone(), doors.clone());
self.calculated.insert(room, newmap);
doors
}
}
fn follow_all_routes(&mut self) {
// this turns out to be completely specialised for short route finding and is
// absolutely not finding all routes at all because it doesn't
// search exhaustively
let mut current_room = Point { x: 0, y: 0 };
let mut current_path = Vec::new();
// collection of (room, path taken to that room, door)
let mut doors_to_follow = Vec::new();
let mut iteration = 0;
loop {
iteration += 1;
if iteration % 100 == 0 {
println!("Iteration {} and I have {} doors to follow",
iteration,
doors_to_follow.len());
}
// println!("I am at {:?} and I came by path {:?}",
// current_room,
// current_path);
let doors_here = self.get_doors_for(current_room, current_path.clone())
.into_iter()
.filter(|d|!self.is_wall(current_room, *d))
.collect::<Vec<_>>();
// println!("These are the doors here: {:?}", doors_here);
for door in doors_here {
let mut new_path = current_path.clone();
new_path.push(door);
let new_room = current_room.go(door);
if!self.have_visited(new_room, &new_path) {
let to_add = (current_room, current_path.clone(), door);
// println!("Adding to my search list {:?}", to_add);
doors_to_follow.push(to_add);
}
}
let next_room = doors_to_follow.pop();
match next_room {
None => break, // we're done!
Some((room, path, door)) => {
// go to that room
current_room = room.go(door);
// go through that door
current_path = path;
current_path.push(door);
}
}
}
}
fn is_wall(&self, room: Point, dir: Dir) -> bool {
match dir {
Dir::Left => room.x == 0,
Dir::Right => room.x >= self.width - 1,
Dir::Up => room.y == 0,
Dir::Down => room.y >= self.height - 1,
}
}
fn get_routes_for_destination(&self) -> Vec<Vec<Dir>> {
let room = self.calculated.get(&self.destination);
match room {
None => Vec::new(),
Some(r) => r.keys().cloned().collect(),
}
}
fn find_longest_route(&self, pos: Point, path: &Vec<Dir>, steps: usize) -> usize {
// based on the nicely elegant C solution by GitHub user rhardih
let doors = open_doors_here(&self.passcode, path);
let mut longest = 0;
let can_up = doors.contains(&Dir::Up) &&!self.is_wall(pos.clone(), Dir::Up);
let can_down = doors.contains(&Dir::Down) &&!self.is_wall(pos.clone(), Dir::Down);
let can_left = doors.contains(&Dir::Left) &&!self.is_wall(pos.clone(), Dir::Left);
let can_right = doors.contains(&Dir::Right) &&!self.is_wall(pos.clone(), Dir::Right);
// can only go down and we're above the destination
if pos.x == self.destination.x && pos.y == self.destination.y - 1 && can_down &&
!can_up &&!can_left &&!can_right {
return steps + 1;
}
// can only go right and we're left of the destination
if pos.x == self.destination.x - 1 && pos.y == self.destination.y && can_right &&
!can_up &&!can_left &&!can_down {
return steps + 1;
}
// more generally
for &(can, dir) in [(can_up, Dir::Up),
(can_down && pos.go(Dir::Down)!= self.destination, Dir::Down),
(can_left, Dir::Left),
(can_right && pos.go(Dir::Right)!= self.destination, Dir::Right)]
.into_iter() {
if can {
let mut try_route = path.clone();
try_route.push(dir);
let r = self.find_longest_route(pos.go(dir), &try_route, steps + 1);
if r > longest {
longest = r;
}
}
}
if longest > 0 {
return longest;
}
if pos.go(Dir::Down) == self.destination && can_down {
return steps + 1;
} else if pos.go(Dir::Right) == self.destination && can_right {
return steps + 1;
}
// or there is no path at all
return 0;
}
}
fn shortest_vec(vecs: &Vec<Vec<Dir>>) -> Option<Vec<Dir>> {
let mut shortest_so_far = None;
let mut shortest_size = usize::max_value();
for v in vecs {
if v.len() < shortest_size {
shortest_so_far = Some(v);
shortest_size = v.len();
}
}
shortest_so_far.map(|v| v.clone())
}
fn find_shortest_route_with_key(key: &str) -> String {
let mut maze = Maze::new(key.to_owned());
maze.follow_all_routes();
let routes = maze.get_routes_for_destination();
let shortest = shortest_vec(&routes);
format_route(&shortest)
}
fn find_longest_route_length_with_key(key: &str) -> usize {
let maze = Maze::new(key.to_owned());
maze.find_longest_route(Point { x: 0, y: 0 }, &Vec::new(), 0)
}
fn format_route(route: &Option<Vec<Dir>>) -> String {
route.clone()
.map(|p| p.into_iter().map(|d| d.as_char()).collect::<String>())
.unwrap_or("No route found".to_owned())
}
pub fn do_day17() {
let key = "gdjjyniy";
let shortest = find_shortest_route_with_key(key);
println!("Shortest: {}", shortest);
println!("Longest: {}", find_longest_route_length_with_key(key));
}
#[test]
fn test_it_1_shortest() {
let shortest = find_shortest_route_with_key("ihgpwlah");
assert_eq!(shortest, "DDRRRD".to_owned());
// assert_eq!(longest.len(), 370);
}
#[test]
fn test_it_1_longest() {
let longest = find_longest_route_length_with_key("ihgpwlah");
assert_eq!(longest, 370);
}
#[test]
fn test_it_2_shortest() {
let shortest = find_shortest_route_with_key("kglvqrro");
assert_eq!(shortest, "DDUDRLRRUDRD".to_owned());
// assert_eq!(longest.len(), 492);
}
#[test]
fn test_it_2_longest() {
assert_eq!(find_longest_route_length_with_key("kglvqrro"), 492);
}
#[test]
fn test_it_3_shortest() {
let shortest = find_shortest_route_with_key("ulqzkmiv");
assert_eq!(shortest, "DRURDRUDDLLDLUURRDULRLDUUDDDRR".to_owned());
}
#[test]
fn test_it_3_longest() {
assert_eq!(find_longest_route_length_with_key("ulqzkmiv"), 830);
}
#[test]
fn test_open_doors_here() {
assert_eq!(open_doors_here("hijkl", &vec![]),
vec![Dir::Up, Dir::Down, Dir::Left]);
assert_eq!(open_doors_here("hijkl", &vec![Dir::Down]),
vec![Dir::Up, Dir::Left, Dir::Right]);
}
#[test]
fn test_get_doors_for() {
let mut maze = Maze::new("hijkl".to_owned());
assert_eq!(maze.get_doors_for(Point { x: 0, y: 0 }, vec![]),
vec![Dir::Up, Dir::Down, Dir::Left]);
// check it cached it
assert_eq!(*maze.calculated.get(&Point { x: 0, y: 0 }).unwrap().get(&vec![]).unwrap(),
vec![Dir::Up, Dir::Down, Dir::Left]);
}
| new | identifier_name |
mod.rs | use md5;
use rustc_serialize::hex::ToHex;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
enum Dir {
Up,
Down,
Left,
Right,
}
impl Dir {
fn as_char(&self) -> char {
match *self {
Dir::Up => 'U',
Dir::Down => 'D',
Dir::Left => 'L',
Dir::Right => 'R',
}
}
}
fn path_as_string(path: &Vec<Dir>) -> String {
path.iter().map(|d| d.as_char()).collect()
}
trait CanBeDoor {
fn is_door(&self) -> bool;
}
impl CanBeDoor for char {
fn is_door(&self) -> bool {
match *self {
'b' | 'c' | 'd' | 'e' | 'f' => true,
_ => false,
}
}
}
fn open_doors_here(passcode: &str, path: &Vec<Dir>) -> Vec<Dir> {
let mut hash_source = passcode.to_owned();
hash_source.push_str(&path_as_string(path));
let hash = md5::compute(hash_source.as_bytes()).to_hex();
// println!("hash computed {} from {}",
// hash.chars().take(4).collect::<String>(),
// hash_source);
let mut i = hash.chars();
let first = i.next().unwrap();
let second = i.next().unwrap();
let third = i.next().unwrap();
let fourth = i.next().unwrap();
let mut result = Vec::new();
if first.is_door() {
result.push(Dir::Up);
}
if second.is_door() {
result.push(Dir::Down);
}
if third.is_door() {
result.push(Dir::Left);
}
if fourth.is_door() {
result.push(Dir::Right);
}
result
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct Point {
x: usize,
y: usize,
}
impl Point {
fn go(&self, dir: Dir) -> Point {
match dir {
Dir::Left => Point { x: self.x - 1,..*self },
Dir::Right => Point { x: self.x + 1,..*self },
Dir::Up => Point { y: self.y - 1,..*self },
Dir::Down => Point { y: self.y + 1,..*self },
}
}
}
#[derive(Debug)]
struct Maze {
width: usize,
height: usize,
destination: Point,
calculated: HashMap<Point, HashMap<Vec<Dir>, Vec<Dir>>>,
passcode: String,
}
impl Maze {
fn new(passcode: String) -> Maze {
Maze {
width: 4,
height: 4,
destination: Point { x: 3, y: 3 },
calculated: HashMap::new(),
passcode: passcode,
}
}
/// have we visited this room and had this set of doors before?
fn have_visited(&mut self, room: Point, path: &Vec<Dir>) -> bool {
let doors = self.get_doors_for(room.clone(), path.clone());
// println!("Have I been to {:?} via {:?} before? I see doors {:?}",
// room,
// path,
// doors);
let r = self.calculated.get(&room);
let result = match r {
Some(r) => {
let previous_door_sets_here =
r.iter().filter(|&(k, _)| k!= path).map(|(_, v)| v).collect::<Vec<_>>(); | // println!("Previous doors here {:?}", previous_door_sets_here);
previous_door_sets_here.into_iter().any(|d| d.clone() == doors)
}
None => false,
};
result
}
fn get_doors_for(&mut self, room: Point, path: Vec<Dir>) -> Vec<Dir> {
if room == self.destination {
// don't need to add doors here
let r = self.calculated.entry(room).or_insert(HashMap::new());
r.insert(path, Vec::new());
return Vec::new();
}
if let Some(r) = self.calculated.clone().get_mut(&room) {
match r.clone().get(&path) {
Some(p) => p.clone(),
None => {
let doors = open_doors_here(&self.passcode, &path);
r.insert(path.clone(), doors.clone());
doors
}
}
} else {
let doors = open_doors_here(&self.passcode, &path);
let mut newmap = HashMap::new();
newmap.insert(path.clone(), doors.clone());
self.calculated.insert(room, newmap);
doors
}
}
fn follow_all_routes(&mut self) {
// this turns out to be completely specialised for short route finding and is
// absolutely not finding all routes at all because it doesn't
// search exhaustively
let mut current_room = Point { x: 0, y: 0 };
let mut current_path = Vec::new();
// collection of (room, path taken to that room, door)
let mut doors_to_follow = Vec::new();
let mut iteration = 0;
loop {
iteration += 1;
if iteration % 100 == 0 {
println!("Iteration {} and I have {} doors to follow",
iteration,
doors_to_follow.len());
}
// println!("I am at {:?} and I came by path {:?}",
// current_room,
// current_path);
let doors_here = self.get_doors_for(current_room, current_path.clone())
.into_iter()
.filter(|d|!self.is_wall(current_room, *d))
.collect::<Vec<_>>();
// println!("These are the doors here: {:?}", doors_here);
for door in doors_here {
let mut new_path = current_path.clone();
new_path.push(door);
let new_room = current_room.go(door);
if!self.have_visited(new_room, &new_path) {
let to_add = (current_room, current_path.clone(), door);
// println!("Adding to my search list {:?}", to_add);
doors_to_follow.push(to_add);
}
}
let next_room = doors_to_follow.pop();
match next_room {
None => break, // we're done!
Some((room, path, door)) => {
// go to that room
current_room = room.go(door);
// go through that door
current_path = path;
current_path.push(door);
}
}
}
}
fn is_wall(&self, room: Point, dir: Dir) -> bool {
match dir {
Dir::Left => room.x == 0,
Dir::Right => room.x >= self.width - 1,
Dir::Up => room.y == 0,
Dir::Down => room.y >= self.height - 1,
}
}
fn get_routes_for_destination(&self) -> Vec<Vec<Dir>> {
let room = self.calculated.get(&self.destination);
match room {
None => Vec::new(),
Some(r) => r.keys().cloned().collect(),
}
}
fn find_longest_route(&self, pos: Point, path: &Vec<Dir>, steps: usize) -> usize {
// based on the nicely elegant C solution by GitHub user rhardih
let doors = open_doors_here(&self.passcode, path);
let mut longest = 0;
let can_up = doors.contains(&Dir::Up) &&!self.is_wall(pos.clone(), Dir::Up);
let can_down = doors.contains(&Dir::Down) &&!self.is_wall(pos.clone(), Dir::Down);
let can_left = doors.contains(&Dir::Left) &&!self.is_wall(pos.clone(), Dir::Left);
let can_right = doors.contains(&Dir::Right) &&!self.is_wall(pos.clone(), Dir::Right);
// can only go down and we're above the destination
if pos.x == self.destination.x && pos.y == self.destination.y - 1 && can_down &&
!can_up &&!can_left &&!can_right {
return steps + 1;
}
// can only go right and we're left of the destination
if pos.x == self.destination.x - 1 && pos.y == self.destination.y && can_right &&
!can_up &&!can_left &&!can_down {
return steps + 1;
}
// more generally
for &(can, dir) in [(can_up, Dir::Up),
(can_down && pos.go(Dir::Down)!= self.destination, Dir::Down),
(can_left, Dir::Left),
(can_right && pos.go(Dir::Right)!= self.destination, Dir::Right)]
.into_iter() {
if can {
let mut try_route = path.clone();
try_route.push(dir);
let r = self.find_longest_route(pos.go(dir), &try_route, steps + 1);
if r > longest {
longest = r;
}
}
}
if longest > 0 {
return longest;
}
if pos.go(Dir::Down) == self.destination && can_down {
return steps + 1;
} else if pos.go(Dir::Right) == self.destination && can_right {
return steps + 1;
}
// or there is no path at all
return 0;
}
}
fn shortest_vec(vecs: &Vec<Vec<Dir>>) -> Option<Vec<Dir>> {
let mut shortest_so_far = None;
let mut shortest_size = usize::max_value();
for v in vecs {
if v.len() < shortest_size {
shortest_so_far = Some(v);
shortest_size = v.len();
}
}
shortest_so_far.map(|v| v.clone())
}
fn find_shortest_route_with_key(key: &str) -> String {
let mut maze = Maze::new(key.to_owned());
maze.follow_all_routes();
let routes = maze.get_routes_for_destination();
let shortest = shortest_vec(&routes);
format_route(&shortest)
}
fn find_longest_route_length_with_key(key: &str) -> usize {
let maze = Maze::new(key.to_owned());
maze.find_longest_route(Point { x: 0, y: 0 }, &Vec::new(), 0)
}
fn format_route(route: &Option<Vec<Dir>>) -> String {
route.clone()
.map(|p| p.into_iter().map(|d| d.as_char()).collect::<String>())
.unwrap_or("No route found".to_owned())
}
pub fn do_day17() {
let key = "gdjjyniy";
let shortest = find_shortest_route_with_key(key);
println!("Shortest: {}", shortest);
println!("Longest: {}", find_longest_route_length_with_key(key));
}
#[test]
fn test_it_1_shortest() {
let shortest = find_shortest_route_with_key("ihgpwlah");
assert_eq!(shortest, "DDRRRD".to_owned());
// assert_eq!(longest.len(), 370);
}
#[test]
fn test_it_1_longest() {
let longest = find_longest_route_length_with_key("ihgpwlah");
assert_eq!(longest, 370);
}
#[test]
fn test_it_2_shortest() {
let shortest = find_shortest_route_with_key("kglvqrro");
assert_eq!(shortest, "DDUDRLRRUDRD".to_owned());
// assert_eq!(longest.len(), 492);
}
#[test]
fn test_it_2_longest() {
assert_eq!(find_longest_route_length_with_key("kglvqrro"), 492);
}
#[test]
fn test_it_3_shortest() {
let shortest = find_shortest_route_with_key("ulqzkmiv");
assert_eq!(shortest, "DRURDRUDDLLDLUURRDULRLDUUDDDRR".to_owned());
}
#[test]
fn test_it_3_longest() {
assert_eq!(find_longest_route_length_with_key("ulqzkmiv"), 830);
}
#[test]
fn test_open_doors_here() {
assert_eq!(open_doors_here("hijkl", &vec![]),
vec![Dir::Up, Dir::Down, Dir::Left]);
assert_eq!(open_doors_here("hijkl", &vec![Dir::Down]),
vec![Dir::Up, Dir::Left, Dir::Right]);
}
#[test]
fn test_get_doors_for() {
let mut maze = Maze::new("hijkl".to_owned());
assert_eq!(maze.get_doors_for(Point { x: 0, y: 0 }, vec![]),
vec![Dir::Up, Dir::Down, Dir::Left]);
// check it cached it
assert_eq!(*maze.calculated.get(&Point { x: 0, y: 0 }).unwrap().get(&vec![]).unwrap(),
vec![Dir::Up, Dir::Down, Dir::Left]);
} | random_line_split |
|
mod.rs | use md5;
use rustc_serialize::hex::ToHex;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
enum Dir {
Up,
Down,
Left,
Right,
}
impl Dir {
fn as_char(&self) -> char {
match *self {
Dir::Up => 'U',
Dir::Down => 'D',
Dir::Left => 'L',
Dir::Right => 'R',
}
}
}
fn path_as_string(path: &Vec<Dir>) -> String {
path.iter().map(|d| d.as_char()).collect()
}
trait CanBeDoor {
fn is_door(&self) -> bool;
}
impl CanBeDoor for char {
fn is_door(&self) -> bool {
match *self {
'b' | 'c' | 'd' | 'e' | 'f' => true,
_ => false,
}
}
}
fn open_doors_here(passcode: &str, path: &Vec<Dir>) -> Vec<Dir> {
let mut hash_source = passcode.to_owned();
hash_source.push_str(&path_as_string(path));
let hash = md5::compute(hash_source.as_bytes()).to_hex();
// println!("hash computed {} from {}",
// hash.chars().take(4).collect::<String>(),
// hash_source);
let mut i = hash.chars();
let first = i.next().unwrap();
let second = i.next().unwrap();
let third = i.next().unwrap();
let fourth = i.next().unwrap();
let mut result = Vec::new();
if first.is_door() {
result.push(Dir::Up);
}
if second.is_door() {
result.push(Dir::Down);
}
if third.is_door() {
result.push(Dir::Left);
}
if fourth.is_door() {
result.push(Dir::Right);
}
result
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct Point {
x: usize,
y: usize,
}
impl Point {
fn go(&self, dir: Dir) -> Point {
match dir {
Dir::Left => Point { x: self.x - 1,..*self },
Dir::Right => Point { x: self.x + 1,..*self },
Dir::Up => Point { y: self.y - 1,..*self },
Dir::Down => Point { y: self.y + 1,..*self },
}
}
}
#[derive(Debug)]
struct Maze {
width: usize,
height: usize,
destination: Point,
calculated: HashMap<Point, HashMap<Vec<Dir>, Vec<Dir>>>,
passcode: String,
}
impl Maze {
fn new(passcode: String) -> Maze {
Maze {
width: 4,
height: 4,
destination: Point { x: 3, y: 3 },
calculated: HashMap::new(),
passcode: passcode,
}
}
/// have we visited this room and had this set of doors before?
fn have_visited(&mut self, room: Point, path: &Vec<Dir>) -> bool {
let doors = self.get_doors_for(room.clone(), path.clone());
// println!("Have I been to {:?} via {:?} before? I see doors {:?}",
// room,
// path,
// doors);
let r = self.calculated.get(&room);
let result = match r {
Some(r) => {
let previous_door_sets_here =
r.iter().filter(|&(k, _)| k!= path).map(|(_, v)| v).collect::<Vec<_>>();
// println!("Previous doors here {:?}", previous_door_sets_here);
previous_door_sets_here.into_iter().any(|d| d.clone() == doors)
}
None => false,
};
result
}
fn get_doors_for(&mut self, room: Point, path: Vec<Dir>) -> Vec<Dir> {
if room == self.destination {
// don't need to add doors here
let r = self.calculated.entry(room).or_insert(HashMap::new());
r.insert(path, Vec::new());
return Vec::new();
}
if let Some(r) = self.calculated.clone().get_mut(&room) {
match r.clone().get(&path) {
Some(p) => p.clone(),
None => {
let doors = open_doors_here(&self.passcode, &path);
r.insert(path.clone(), doors.clone());
doors
}
}
} else {
let doors = open_doors_here(&self.passcode, &path);
let mut newmap = HashMap::new();
newmap.insert(path.clone(), doors.clone());
self.calculated.insert(room, newmap);
doors
}
}
fn follow_all_routes(&mut self) {
// this turns out to be completely specialised for short route finding and is
// absolutely not finding all routes at all because it doesn't
// search exhaustively
let mut current_room = Point { x: 0, y: 0 };
let mut current_path = Vec::new();
// collection of (room, path taken to that room, door)
let mut doors_to_follow = Vec::new();
let mut iteration = 0;
loop {
iteration += 1;
if iteration % 100 == 0 {
println!("Iteration {} and I have {} doors to follow",
iteration,
doors_to_follow.len());
}
// println!("I am at {:?} and I came by path {:?}",
// current_room,
// current_path);
let doors_here = self.get_doors_for(current_room, current_path.clone())
.into_iter()
.filter(|d|!self.is_wall(current_room, *d))
.collect::<Vec<_>>();
// println!("These are the doors here: {:?}", doors_here);
for door in doors_here {
let mut new_path = current_path.clone();
new_path.push(door);
let new_room = current_room.go(door);
if!self.have_visited(new_room, &new_path) {
let to_add = (current_room, current_path.clone(), door);
// println!("Adding to my search list {:?}", to_add);
doors_to_follow.push(to_add);
}
}
let next_room = doors_to_follow.pop();
match next_room {
None => break, // we're done!
Some((room, path, door)) => {
// go to that room
current_room = room.go(door);
// go through that door
current_path = path;
current_path.push(door);
}
}
}
}
fn is_wall(&self, room: Point, dir: Dir) -> bool {
match dir {
Dir::Left => room.x == 0,
Dir::Right => room.x >= self.width - 1,
Dir::Up => room.y == 0,
Dir::Down => room.y >= self.height - 1,
}
}
fn get_routes_for_destination(&self) -> Vec<Vec<Dir>> |
fn find_longest_route(&self, pos: Point, path: &Vec<Dir>, steps: usize) -> usize {
// based on the nicely elegant C solution by GitHub user rhardih
let doors = open_doors_here(&self.passcode, path);
let mut longest = 0;
let can_up = doors.contains(&Dir::Up) &&!self.is_wall(pos.clone(), Dir::Up);
let can_down = doors.contains(&Dir::Down) &&!self.is_wall(pos.clone(), Dir::Down);
let can_left = doors.contains(&Dir::Left) &&!self.is_wall(pos.clone(), Dir::Left);
let can_right = doors.contains(&Dir::Right) &&!self.is_wall(pos.clone(), Dir::Right);
// can only go down and we're above the destination
if pos.x == self.destination.x && pos.y == self.destination.y - 1 && can_down &&
!can_up &&!can_left &&!can_right {
return steps + 1;
}
// can only go right and we're left of the destination
if pos.x == self.destination.x - 1 && pos.y == self.destination.y && can_right &&
!can_up &&!can_left &&!can_down {
return steps + 1;
}
// more generally
for &(can, dir) in [(can_up, Dir::Up),
(can_down && pos.go(Dir::Down)!= self.destination, Dir::Down),
(can_left, Dir::Left),
(can_right && pos.go(Dir::Right)!= self.destination, Dir::Right)]
.into_iter() {
if can {
let mut try_route = path.clone();
try_route.push(dir);
let r = self.find_longest_route(pos.go(dir), &try_route, steps + 1);
if r > longest {
longest = r;
}
}
}
if longest > 0 {
return longest;
}
if pos.go(Dir::Down) == self.destination && can_down {
return steps + 1;
} else if pos.go(Dir::Right) == self.destination && can_right {
return steps + 1;
}
// or there is no path at all
return 0;
}
}
fn shortest_vec(vecs: &Vec<Vec<Dir>>) -> Option<Vec<Dir>> {
let mut shortest_so_far = None;
let mut shortest_size = usize::max_value();
for v in vecs {
if v.len() < shortest_size {
shortest_so_far = Some(v);
shortest_size = v.len();
}
}
shortest_so_far.map(|v| v.clone())
}
fn find_shortest_route_with_key(key: &str) -> String {
let mut maze = Maze::new(key.to_owned());
maze.follow_all_routes();
let routes = maze.get_routes_for_destination();
let shortest = shortest_vec(&routes);
format_route(&shortest)
}
fn find_longest_route_length_with_key(key: &str) -> usize {
let maze = Maze::new(key.to_owned());
maze.find_longest_route(Point { x: 0, y: 0 }, &Vec::new(), 0)
}
fn format_route(route: &Option<Vec<Dir>>) -> String {
route.clone()
.map(|p| p.into_iter().map(|d| d.as_char()).collect::<String>())
.unwrap_or("No route found".to_owned())
}
pub fn do_day17() {
let key = "gdjjyniy";
let shortest = find_shortest_route_with_key(key);
println!("Shortest: {}", shortest);
println!("Longest: {}", find_longest_route_length_with_key(key));
}
#[test]
fn test_it_1_shortest() {
let shortest = find_shortest_route_with_key("ihgpwlah");
assert_eq!(shortest, "DDRRRD".to_owned());
// assert_eq!(longest.len(), 370);
}
#[test]
fn test_it_1_longest() {
let longest = find_longest_route_length_with_key("ihgpwlah");
assert_eq!(longest, 370);
}
#[test]
fn test_it_2_shortest() {
let shortest = find_shortest_route_with_key("kglvqrro");
assert_eq!(shortest, "DDUDRLRRUDRD".to_owned());
// assert_eq!(longest.len(), 492);
}
#[test]
fn test_it_2_longest() {
assert_eq!(find_longest_route_length_with_key("kglvqrro"), 492);
}
#[test]
fn test_it_3_shortest() {
let shortest = find_shortest_route_with_key("ulqzkmiv");
assert_eq!(shortest, "DRURDRUDDLLDLUURRDULRLDUUDDDRR".to_owned());
}
#[test]
fn test_it_3_longest() {
assert_eq!(find_longest_route_length_with_key("ulqzkmiv"), 830);
}
#[test]
fn test_open_doors_here() {
assert_eq!(open_doors_here("hijkl", &vec![]),
vec![Dir::Up, Dir::Down, Dir::Left]);
assert_eq!(open_doors_here("hijkl", &vec![Dir::Down]),
vec![Dir::Up, Dir::Left, Dir::Right]);
}
#[test]
fn test_get_doors_for() {
let mut maze = Maze::new("hijkl".to_owned());
assert_eq!(maze.get_doors_for(Point { x: 0, y: 0 }, vec![]),
vec![Dir::Up, Dir::Down, Dir::Left]);
// check it cached it
assert_eq!(*maze.calculated.get(&Point { x: 0, y: 0 }).unwrap().get(&vec![]).unwrap(),
vec![Dir::Up, Dir::Down, Dir::Left]);
}
| {
let room = self.calculated.get(&self.destination);
match room {
None => Vec::new(),
Some(r) => r.keys().cloned().collect(),
}
} | identifier_body |
main.rs | <<<<<<< HEAD
/*
* word correction
*
* Reads text from the corpus text and
* Count the frequency of each word, then correct the candidate word in input text, output with the most frequetly
* used one
*
* Background
*
* The purpose of correct is to find possible corrections for misspelled words. It consists of two phases:
* The first phase is a training module, which consumes a corpus of correctly spelled words and counts the
* number of occurrences of each word. The second phase uses the results of the first to check individual words.
* Specifically, it checks whether each word is spelled correctly according to the training module and, if not,
* whether “small edits” can reach a variant that is correctly spelled.
*
* Given a word, an edit action is one of the following:
* the deletion of one letter;
*
* the transposition of two neighboring letters;
*
* the replacement of one letter with another letter; and
*
* the insertion of a letter at any position.
*
* In this context, Norvig suggests that “small edits” means the application of one edit action possibly
* followed by the application of a second one to the result of the first.
* Once the second part has generated all possible candidate for a potentially misspelled word,
* it picks the most frequently used one from the training corpus. If none of the candidates is a correct word,
* correct reports a failure.
*
* INPUT
*
* The input format is using two standard input consuming text. It could contain anything like words, numbers or some marks.
* writtten in ASCII.
*
* Hello world! Where are you now?
* www333
* github.com/rust
* !!!!!@@@@@@@
*
* Any non-alphabetic will be regarded as noise and will not be counted:
*
* 23232
* ++--!!!@@
* ...???''''""""
*
*
* The input terminates with end-of-file.
*
*
* OUTPUT
*
* The correct program consumes a training file on the command line and then reads words—one per line—from
* standard input. For each word from standard in, correct prints one line. The line consists of just the word
* if it is spelled correctly. If the word is not correctly spelled, correct prints the word and the best
* improvement or “-” if there aren’t any improvements found.
*
* hello
*
* hell, hello
*
* word
*
* wordl, world
*
* wor, world
*
* wo, word
*
* w, -
*
* ASSUMPTIONS
*
* - Words are reading according to the language's reading routines,
*
* - A word contained numbers will be count only the alphabetic character
* and ignore the numbers.
*
* - All the symbol, space and numbers will be considered as noise and ignored.
*
* - The input only terminate in the end-of-file, which is kind of unconvenient
* if you want to use console to input your data.
*
* - Once the word has been edited, we would pick the most frequently used one after
* two editions.
*
* - Except fot the normal edition, we add the corner case handler to accelerate the algorithm
*
*
*/
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
//#![allow(dead_code)]
//#![allow(unused_variables)]
use std::io::{stdin};
use std::env;
use std::collections::HashMap;
use trie::Trie;
use trie::Result;
use std::fs::File;
mod readinput;
mod trie;
mod counter;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len()!= 2 {
panic!("Missing input file"); //check training file
}
let f = File::open(&args[1]).expect("Error opening training file!");
//calculate the freq. of training file and stored in a hashmap
let dict: HashMap<String, usize> = counter::word_count(&counter::read_input(f));
//read input.txt and store in a vector
let check_words: Vec<String> = readinput::read_input(stdin());
//initialize the Trie
let mut t:Trie = Trie::new();
for (key,value) in &dict {
t.insert(&mut key.to_string(), *value);
}
//check each word in input.txt
for word in check_words {
let mut changeword = word.clone();
let mut changeword2 = word.clone();
let temp = find(&t, &mut changeword,&mut changeword2,&mut "".to_string(), 2).key;
if temp.is_empty(){
println!("{}, -", word);
}
else if temp == word{
println!("{}", word);
}
else {
println!("{}, {}", word, temp);
}
}
}
/*
* This is the main search function for this program. We implement the DFS(Depth-First-Search)+Regression
* Algorithm to travel the whole trie and find all the candidate word, then pick the most frequently one.
*
* Input : trie: The trie made from corpus.txt, contains all the word
* path: The misspelled word
* pathclone: The remained string need to match
* cur: The trie path
* op: The edit times left for current matching
*
* The stop condition is that current trie path consist a word and match the input/edited word.
*
* We separate each character in the string and find the matched node in current trie. In the meantime,
* we also edit the word in case we can't find the original word in tries. But we set the original search
* with the highest priority.
*
* Output is a Struct with key: String the most frequently used word
* value: maximum frequency.
*/
fn find(trie: & Trie, path: & String,pathclone: & mut String,cur: & mut String, op: i64)-> Result{
if pathclone.len()==0 && trie.value>0 {
return Result{
value: trie.value,
key: cur.clone(),
}
}
else{
let mut max= Result::new();
let mut temp: Result;
let mut temppath =pathclone.clone();
let mut currtrie :&Trie;
if pathclone.len()>0{
let mut curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar) {
cur.push(curchar);
max = find(currtrie,path,& mut temppath, cur, op);
if op==2 && max.key == *path{
return max;
}
cur.pop();
}
//deletion
//if we can get a word after deleting current character
if op > 0{
if pathclone.len()==1 && trie.value>0{
temp= Result{
value: trie.value,
key: cur.clone(),
};
if temp.value>max.value{
max = temp;
}
}
if pathclone.len()==2 &&op==2&& trie.value>0{
temp= Result{
value: trie.value,
key: cur.clone(),
};
if temp.value>max.value{
max = temp;
}
}
if pathclone.len()>1{
| if let Some(currtrie) = trie.children.get(&curchar){
let counter = 0;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
}
}
/
/transpose
if pathclone.len()>1{
temppath = pathclone.clone();
curchar = temppath.remove(0);
temppath.insert(1,curchar);
curchar = temppath.remove(0);
cur.push(curchar);
if let Some(currtrie) = trie.children.get(&curchar) {
let counter = op-1;
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
}
cur.pop();
}
// replace
for key in trie.children.keys(){
temppath = pathclone.clone();
if temppath.len()>1{
temppath.remove(0);
}
else{temppath="".to_string();}
currtrie = trie.children.get(&key).unwrap();
cur.push(*key);
let counter = op-1;
temp = find(&currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
}
if op> 0{
//insertion
for key in trie.children.keys(){
cur.push(*key);
currtrie = trie.children.get(&key).unwrap();
let counter = op-1;
temp = find(&currtrie,path,pathclone,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
return max;
}
}
#[test]
fn test_find_edit_value(){
//use super::{trie,Result};
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bce".to_string(),&mut "bce".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "acd".to_string(),&mut "acd".to_string(),&mut "".to_string(), 2).value, 4);
assert_eq!(find(&t, &mut "acd".to_string(),&mut "acd".to_string(),&mut "".to_string(), 2).key, "acd");
assert_eq!(find(&t, &mut "".to_string(),&mut "".to_string(),&mut "".to_string(), 2).key, "gg");
assert_eq!(find(&t, &mut "cbdca".to_string(),&mut "cbdca".to_string(),&mut "".to_string(), 2).value, 3);
}
#[test]
fn test_find_replace_value(){
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bed".to_string(),&mut "bed".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "b".to_string(),&mut "b".to_string(),&mut "".to_string(), 2).value, 100);
}
#[test]
fn test_find_delete_value(){
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bcdea".to_string(),&mut "bed".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "ggag".to_string(),&mut "b".to_string(),&mut "".to_string(), 2).value, 100);
} | temppath = pathclone.clone();
temppath.remove(0);
curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar){
let counter = op-1;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
if pathclone.len()>2 &&op==2{
temppath = pathclone.clone();
temppath.remove(0);
temppath.remove(0);
curchar = temppath.remove(0); | conditional_block |
main.rs | <<<<<<< HEAD
/*
* word correction
*
* Reads text from the corpus text and
* Count the frequency of each word, then correct the candidate word in input text, output with the most frequetly
* used one
*
* Background
*
* The purpose of correct is to find possible corrections for misspelled words. It consists of two phases:
* The first phase is a training module, which consumes a corpus of correctly spelled words and counts the
* number of occurrences of each word. The second phase uses the results of the first to check individual words.
* Specifically, it checks whether each word is spelled correctly according to the training module and, if not,
* whether “small edits” can reach a variant that is correctly spelled.
*
* Given a word, an edit action is one of the following:
* the deletion of one letter;
*
* the transposition of two neighboring letters;
*
* the replacement of one letter with another letter; and
*
* the insertion of a letter at any position.
*
* In this context, Norvig suggests that “small edits” means the application of one edit action possibly
* followed by the application of a second one to the result of the first.
* Once the second part has generated all possible candidate for a potentially misspelled word,
* it picks the most frequently used one from the training corpus. If none of the candidates is a correct word,
* correct reports a failure.
*
* INPUT
*
* The input format is using two standard input consuming text. It could contain anything like words, numbers or some marks.
* writtten in ASCII.
*
* Hello world! Where are you now?
* www333
* github.com/rust
* !!!!!@@@@@@@
*
* Any non-alphabetic will be regarded as noise and will not be counted:
*
* 23232
* ++--!!!@@
* ...???''''""""
*
*
* The input terminates with end-of-file.
*
*
* OUTPUT
*
* The correct program consumes a training file on the command line and then reads words—one per line—from
* standard input. For each word from standard in, correct prints one line. The line consists of just the word
* if it is spelled correctly. If the word is not correctly spelled, correct prints the word and the best
* improvement or “-” if there aren’t any improvements found.
*
* hello
*
* hell, hello
*
* word
*
* wordl, world
*
* wor, world
*
* wo, word
*
* w, -
*
* ASSUMPTIONS
*
* - Words are reading according to the language's reading routines,
*
* - A word contained numbers will be count only the alphabetic character
* and ignore the numbers.
*
* - All the symbol, space and numbers will be considered as noise and ignored.
*
* - The input only terminate in the end-of-file, which is kind of unconvenient
* if you want to use console to input your data.
*
* - Once the word has been edited, we would pick the most frequently used one after
* two editions.
*
* - Except fot the normal edition, we add the corner case handler to accelerate the algorithm
*
*
*/
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
//#![allow(dead_code)]
//#![allow(unused_variables)]
use std::io::{stdin};
use std::env;
use std::collections::HashMap;
use trie::Trie;
use trie::Result;
use std::fs::File;
mod readinput;
mod trie;
mod counter;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len()!= 2 {
panic!("Missing input file"); //check training file
}
let f = File::open(&args[1]).expect("Error opening training file!");
//calculate the freq. of training file and stored in a hashmap
let dict: HashMap<String, usize> = counter::word_count(&counter::read_input(f));
//read input.txt and store in a vector
let check_words: Vec<String> = readinput::read_input(stdin());
//initialize the Trie
let mut t:Trie = Trie::new();
for (key,value) in &dict {
t.insert(&mut key.to_string(), *value);
}
//check each word in input.txt
for word in check_words {
let mut changeword = word.clone();
let mut changeword2 = word.clone();
let temp = find(&t, &mut changeword,&mut changeword2,&mut "".to_string(), 2).key;
if temp.is_empty(){
println!("{}, -", word);
}
else if temp == word{
println!("{}", word);
}
else {
println!("{}, {}", word, temp);
}
}
}
/* | *
* Input : trie: The trie made from corpus.txt, contains all the word
* path: The misspelled word
* pathclone: The remained string need to match
* cur: The trie path
* op: The edit times left for current matching
*
* The stop condition is that current trie path consist a word and match the input/edited word.
*
* We separate each character in the string and find the matched node in current trie. In the meantime,
* we also edit the word in case we can't find the original word in tries. But we set the original search
* with the highest priority.
*
* Output is a Struct with key: String the most frequently used word
* value: maximum frequency.
*/
fn find(trie: & Trie, path: & String,pathclone: & mut String,cur: & mut String, op: i64)-> Result{
if pathclone.len()==0 && trie.value>0 {
return Result{
value: trie.value,
key: cur.clone(),
}
}
else{
let mut max= Result::new();
let mut temp: Result;
let mut temppath =pathclone.clone();
let mut currtrie :&Trie;
if pathclone.len()>0{
let mut curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar) {
cur.push(curchar);
max = find(currtrie,path,& mut temppath, cur, op);
if op==2 && max.key == *path{
return max;
}
cur.pop();
}
//deletion
//if we can get a word after deleting current character
if op > 0{
if pathclone.len()==1 && trie.value>0{
temp= Result{
value: trie.value,
key: cur.clone(),
};
if temp.value>max.value{
max = temp;
}
}
if pathclone.len()==2 &&op==2&& trie.value>0{
temp= Result{
value: trie.value,
key: cur.clone(),
};
if temp.value>max.value{
max = temp;
}
}
if pathclone.len()>1{
temppath = pathclone.clone();
temppath.remove(0);
curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar){
let counter = op-1;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
if pathclone.len()>2 &&op==2{
temppath = pathclone.clone();
temppath.remove(0);
temppath.remove(0);
curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar){
let counter = 0;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
}
}
//transpose
if pathclone.len()>1{
temppath = pathclone.clone();
curchar = temppath.remove(0);
temppath.insert(1,curchar);
curchar = temppath.remove(0);
cur.push(curchar);
if let Some(currtrie) = trie.children.get(&curchar) {
let counter = op-1;
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
}
cur.pop();
}
// replace
for key in trie.children.keys(){
temppath = pathclone.clone();
if temppath.len()>1{
temppath.remove(0);
}
else{temppath="".to_string();}
currtrie = trie.children.get(&key).unwrap();
cur.push(*key);
let counter = op-1;
temp = find(&currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
}
if op> 0{
//insertion
for key in trie.children.keys(){
cur.push(*key);
currtrie = trie.children.get(&key).unwrap();
let counter = op-1;
temp = find(&currtrie,path,pathclone,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
return max;
}
}
#[test]
fn test_find_edit_value(){
//use super::{trie,Result};
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bce".to_string(),&mut "bce".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "acd".to_string(),&mut "acd".to_string(),&mut "".to_string(), 2).value, 4);
assert_eq!(find(&t, &mut "acd".to_string(),&mut "acd".to_string(),&mut "".to_string(), 2).key, "acd");
assert_eq!(find(&t, &mut "".to_string(),&mut "".to_string(),&mut "".to_string(), 2).key, "gg");
assert_eq!(find(&t, &mut "cbdca".to_string(),&mut "cbdca".to_string(),&mut "".to_string(), 2).value, 3);
}
#[test]
fn test_find_replace_value(){
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bed".to_string(),&mut "bed".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "b".to_string(),&mut "b".to_string(),&mut "".to_string(), 2).value, 100);
}
#[test]
fn test_find_delete_value(){
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bcdea".to_string(),&mut "bed".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "ggag".to_string(),&mut "b".to_string(),&mut "".to_string(), 2).value, 100);
} | * This is the main search function for this program. We implement the DFS(Depth-First-Search)+Regression
* Algorithm to travel the whole trie and find all the candidate word, then pick the most frequently one. | random_line_split |
main.rs | <<<<<<< HEAD
/*
* word correction
*
* Reads text from the corpus text and
* Count the frequency of each word, then correct the candidate word in input text, output with the most frequetly
* used one
*
* Background
*
* The purpose of correct is to find possible corrections for misspelled words. It consists of two phases:
* The first phase is a training module, which consumes a corpus of correctly spelled words and counts the
* number of occurrences of each word. The second phase uses the results of the first to check individual words.
* Specifically, it checks whether each word is spelled correctly according to the training module and, if not,
* whether “small edits” can reach a variant that is correctly spelled.
*
* Given a word, an edit action is one of the following:
* the deletion of one letter;
*
* the transposition of two neighboring letters;
*
* the replacement of one letter with another letter; and
*
* the insertion of a letter at any position.
*
* In this context, Norvig suggests that “small edits” means the application of one edit action possibly
* followed by the application of a second one to the result of the first.
* Once the second part has generated all possible candidate for a potentially misspelled word,
* it picks the most frequently used one from the training corpus. If none of the candidates is a correct word,
* correct reports a failure.
*
* INPUT
*
* The input format is using two standard input consuming text. It could contain anything like words, numbers or some marks.
* writtten in ASCII.
*
* Hello world! Where are you now?
* www333
* github.com/rust
* !!!!!@@@@@@@
*
* Any non-alphabetic will be regarded as noise and will not be counted:
*
* 23232
* ++--!!!@@
* ...???''''""""
*
*
* The input terminates with end-of-file.
*
*
* OUTPUT
*
* The correct program consumes a training file on the command line and then reads words—one per line—from
* standard input. For each word from standard in, correct prints one line. The line consists of just the word
* if it is spelled correctly. If the word is not correctly spelled, correct prints the word and the best
* improvement or “-” if there aren’t any improvements found.
*
* hello
*
* hell, hello
*
* word
*
* wordl, world
*
* wor, world
*
* wo, word
*
* w, -
*
* ASSUMPTIONS
*
* - Words are reading according to the language's reading routines,
*
* - A word contained numbers will be count only the alphabetic character
* and ignore the numbers.
*
* - All the symbol, space and numbers will be considered as noise and ignored.
*
* - The input only terminate in the end-of-file, which is kind of unconvenient
* if you want to use console to input your data.
*
* - Once the word has been edited, we would pick the most frequently used one after
* two editions.
*
* - Except fot the normal edition, we add the corner case handler to accelerate the algorithm
*
*
*/
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
//#![allow(dead_code)]
//#![allow(unused_variables)]
use std::io::{stdin};
use std::env;
use std::collections::HashMap;
use trie::Trie;
use trie::Result;
use std::fs::File;
mod readinput;
mod trie;
mod counter;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len()!= 2 {
panic!("Missing input file"); //check training file
}
let f = File::open(&args[1]).expect("Error opening training file!");
//calculate the freq. of training file and stored in a hashmap
let dict: HashMap<String, usize> = counter::word_count(&counter::read_input(f));
//read input.txt and store in a vector
let check_words: Vec<String> = readinput::read_input(stdin());
//initialize the Trie
let mut t:Trie = Trie::new();
for (key,value) in &dict {
t.insert(&mut key.to_string(), *value);
}
//check each word in input.txt
for word in check_words {
let mut changeword = word.clone();
let mut changeword2 = word.clone();
let temp = find(&t, &mut changeword,&mut changeword2,&mut "".to_string(), 2).key;
if temp.is_empty(){
println!("{}, -", word);
}
else if temp == word{
println!("{}", word);
}
else {
println!("{}, {}", word, temp);
}
}
}
/*
* This is the main search function for this program. We implement the DFS(Depth-First-Search)+Regression
* Algorithm to travel the whole trie and find all the candidate word, then pick the most frequently one.
*
* Input : trie: The trie made from corpus.txt, contains all the word
* path: The misspelled word
* pathclone: The remained string need to match
* cur: The trie path
* op: The edit times left for current matching
*
* The stop condition is that current trie path consist a word and match the input/edited word.
*
* We separate each character in the string and find the matched node in current trie. In the meantime,
* we also edit the word in case we can't find the original word in tries. But we set the original search
* with the highest priority.
*
* Output is a Struct with key: String the most frequently used word
* value: maximum frequency.
*/
fn find(trie: & Trie, path: & String,pathclone: & mut String,cur: & mut String, op: i64)-> Result{
if pathclone.le | }
cur.pop();
}
//deletion
//if we can get a word after deleting current character
if op > 0{
if pathclone.len()==1 && trie.value>0{
temp= Result{
value: trie.value,
key: cur.clone(),
};
if temp.value>max.value{
max = temp;
}
}
if pathclone.len()==2 &&op==2&& trie.value>0{
temp= Result{
value: trie.value,
key: cur.clone(),
};
if temp.value>max.value{
max = temp;
}
}
if pathclone.len()>1{
temppath = pathclone.clone();
temppath.remove(0);
curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar){
let counter = op-1;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
if pathclone.len()>2 &&op==2{
temppath = pathclone.clone();
temppath.remove(0);
temppath.remove(0);
curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar){
let counter = 0;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
}
}
//transpose
if pathclone.len()>1{
temppath = pathclone.clone();
curchar = temppath.remove(0);
temppath.insert(1,curchar);
curchar = temppath.remove(0);
cur.push(curchar);
if let Some(currtrie) = trie.children.get(&curchar) {
let counter = op-1;
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
}
cur.pop();
}
// replace
for key in trie.children.keys(){
temppath = pathclone.clone();
if temppath.len()>1{
temppath.remove(0);
}
else{temppath="".to_string();}
currtrie = trie.children.get(&key).unwrap();
cur.push(*key);
let counter = op-1;
temp = find(&currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
}
if op> 0{
//insertion
for key in trie.children.keys(){
cur.push(*key);
currtrie = trie.children.get(&key).unwrap();
let counter = op-1;
temp = find(&currtrie,path,pathclone,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
return max;
}
}
#[test]
fn test_find_edit_value(){
//use super::{trie,Result};
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bce".to_string(),&mut "bce".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "acd".to_string(),&mut "acd".to_string(),&mut "".to_string(), 2).value, 4);
assert_eq!(find(&t, &mut "acd".to_string(),&mut "acd".to_string(),&mut "".to_string(), 2).key, "acd");
assert_eq!(find(&t, &mut "".to_string(),&mut "".to_string(),&mut "".to_string(), 2).key, "gg");
assert_eq!(find(&t, &mut "cbdca".to_string(),&mut "cbdca".to_string(),&mut "".to_string(), 2).value, 3);
}
#[test]
fn test_find_replace_value(){
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bed".to_string(),&mut "bed".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "b".to_string(),&mut "b".to_string(),&mut "".to_string(), 2).value, 100);
}
#[test]
fn test_find_delete_value(){
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bcdea".to_string(),&mut "bed".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "ggag".to_string(),&mut "b".to_string(),&mut "".to_string(), 2).value, 100);
} | n()==0 && trie.value>0 {
return Result{
value: trie.value,
key: cur.clone(),
}
}
else{
let mut max= Result::new();
let mut temp: Result;
let mut temppath =pathclone.clone();
let mut currtrie :&Trie;
if pathclone.len()>0{
let mut curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar) {
cur.push(curchar);
max = find(currtrie,path,& mut temppath, cur, op);
if op==2 && max.key == *path{
return max; | identifier_body |
main.rs | <<<<<<< HEAD
/*
* word correction
*
* Reads text from the corpus text and
* Count the frequency of each word, then correct the candidate word in input text, output with the most frequetly
* used one
*
* Background
*
* The purpose of correct is to find possible corrections for misspelled words. It consists of two phases:
* The first phase is a training module, which consumes a corpus of correctly spelled words and counts the
* number of occurrences of each word. The second phase uses the results of the first to check individual words.
* Specifically, it checks whether each word is spelled correctly according to the training module and, if not,
* whether “small edits” can reach a variant that is correctly spelled.
*
* Given a word, an edit action is one of the following:
* the deletion of one letter;
*
* the transposition of two neighboring letters;
*
* the replacement of one letter with another letter; and
*
* the insertion of a letter at any position.
*
* In this context, Norvig suggests that “small edits” means the application of one edit action possibly
* followed by the application of a second one to the result of the first.
* Once the second part has generated all possible candidate for a potentially misspelled word,
* it picks the most frequently used one from the training corpus. If none of the candidates is a correct word,
* correct reports a failure.
*
* INPUT
*
* The input format is using two standard input consuming text. It could contain anything like words, numbers or some marks.
* writtten in ASCII.
*
* Hello world! Where are you now?
* www333
* github.com/rust
* !!!!!@@@@@@@
*
* Any non-alphabetic will be regarded as noise and will not be counted:
*
* 23232
* ++--!!!@@
* ...???''''""""
*
*
* The input terminates with end-of-file.
*
*
* OUTPUT
*
* The correct program consumes a training file on the command line and then reads words—one per line—from
* standard input. For each word from standard in, correct prints one line. The line consists of just the word
* if it is spelled correctly. If the word is not correctly spelled, correct prints the word and the best
* improvement or “-” if there aren’t any improvements found.
*
* hello
*
* hell, hello
*
* word
*
* wordl, world
*
* wor, world
*
* wo, word
*
* w, -
*
* ASSUMPTIONS
*
* - Words are reading according to the language's reading routines,
*
* - A word contained numbers will be count only the alphabetic character
* and ignore the numbers.
*
* - All the symbol, space and numbers will be considered as noise and ignored.
*
* - The input only terminate in the end-of-file, which is kind of unconvenient
* if you want to use console to input your data.
*
* - Once the word has been edited, we would pick the most frequently used one after
* two editions.
*
* - Except fot the normal edition, we add the corner case handler to accelerate the algorithm
*
*
*/
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
//#![allow(dead_code)]
//#![allow(unused_variables)]
use std::io::{stdin};
use std::env;
use std::collections::HashMap;
use trie::Trie;
use trie::Result;
use std::fs::File;
mod readinput;
mod trie;
mod counter;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len()!= 2 {
panic!("Missing input file"); //check training file
}
let f = File::open(&args[1]).expect("Error opening training file!");
//calculate the freq. of training file and stored in a hashmap
let dict: HashMap<String, usize> = counter::word_count(&counter::read_input(f));
//read input.txt and store in a vector
let check_words: Vec<String> = readinput::read_input(stdin());
//initialize the Trie
let mut t:Trie = Trie::new();
for (key,value) in &dict {
t.insert(&mut key.to_string(), *value);
}
//check each word in input.txt
for word in check_words {
let mut changeword = word.clone();
let mut changeword2 = word.clone();
let temp = find(&t, &mut changeword,&mut changeword2,&mut "".to_string(), 2).key;
if temp.is_empty(){
println!("{}, -", word);
}
else if temp == word{
println!("{}", word);
}
else {
println!("{}, {}", word, temp);
}
}
}
/*
* This is the main search function for this program. We implement the DFS(Depth-First-Search)+Regression
* Algorithm to travel the whole trie and find all the candidate word, then pick the most frequently one.
*
* Input : trie: The trie made from corpus.txt, contains all the word
* path: The misspelled word
* pathclone: The remained string need to match
* cur: The trie path
* op: The edit times left for current matching
*
* The stop condition is that current trie path consist a word and match the input/edited word.
*
* We separate each character in the string and find the matched node in current trie. In the meantime,
* we also edit the word in case we can't find the original word in tries. But we set the original search
* with the highest priority.
*
* Output is a Struct with key: String the most frequently used word
* value: maximum frequency.
*/
fn find(trie: & Trie, | h: & String,pathclone: & mut String,cur: & mut String, op: i64)-> Result{
if pathclone.len()==0 && trie.value>0 {
return Result{
value: trie.value,
key: cur.clone(),
}
}
else{
let mut max= Result::new();
let mut temp: Result;
let mut temppath =pathclone.clone();
let mut currtrie :&Trie;
if pathclone.len()>0{
let mut curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar) {
cur.push(curchar);
max = find(currtrie,path,& mut temppath, cur, op);
if op==2 && max.key == *path{
return max;
}
cur.pop();
}
//deletion
//if we can get a word after deleting current character
if op > 0{
if pathclone.len()==1 && trie.value>0{
temp= Result{
value: trie.value,
key: cur.clone(),
};
if temp.value>max.value{
max = temp;
}
}
if pathclone.len()==2 &&op==2&& trie.value>0{
temp= Result{
value: trie.value,
key: cur.clone(),
};
if temp.value>max.value{
max = temp;
}
}
if pathclone.len()>1{
temppath = pathclone.clone();
temppath.remove(0);
curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar){
let counter = op-1;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
if pathclone.len()>2 &&op==2{
temppath = pathclone.clone();
temppath.remove(0);
temppath.remove(0);
curchar = temppath.remove(0);
if let Some(currtrie) = trie.children.get(&curchar){
let counter = 0;
cur.push(curchar);
<<<<<<< HEAD
=======
>>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
}
}
//transpose
if pathclone.len()>1{
temppath = pathclone.clone();
curchar = temppath.remove(0);
temppath.insert(1,curchar);
curchar = temppath.remove(0);
cur.push(curchar);
if let Some(currtrie) = trie.children.get(&curchar) {
let counter = op-1;
temp = find(currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
}
cur.pop();
}
// replace
for key in trie.children.keys(){
temppath = pathclone.clone();
if temppath.len()>1{
temppath.remove(0);
}
else{temppath="".to_string();}
currtrie = trie.children.get(&key).unwrap();
cur.push(*key);
let counter = op-1;
temp = find(&currtrie,path,&mut temppath,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
}
if op> 0{
//insertion
for key in trie.children.keys(){
cur.push(*key);
currtrie = trie.children.get(&key).unwrap();
let counter = op-1;
temp = find(&currtrie,path,pathclone,cur,counter);
if temp.value>max.value{
max = temp;
}
cur.pop();
}
}
return max;
}
}
#[test]
fn test_find_edit_value(){
//use super::{trie,Result};
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bce".to_string(),&mut "bce".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "acd".to_string(),&mut "acd".to_string(),&mut "".to_string(), 2).value, 4);
assert_eq!(find(&t, &mut "acd".to_string(),&mut "acd".to_string(),&mut "".to_string(), 2).key, "acd");
assert_eq!(find(&t, &mut "".to_string(),&mut "".to_string(),&mut "".to_string(), 2).key, "gg");
assert_eq!(find(&t, &mut "cbdca".to_string(),&mut "cbdca".to_string(),&mut "".to_string(), 2).value, 3);
}
#[test]
fn test_find_replace_value(){
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bed".to_string(),&mut "bed".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "b".to_string(),&mut "b".to_string(),&mut "".to_string(), 2).value, 100);
}
#[test]
fn test_find_delete_value(){
let mut t = Trie::new();
t.insert(&mut "acd".to_string(), 4);
t.insert(&mut "bce".to_string(), 5);
t.insert(&mut "cbdca".to_string(),3);
t.insert(&mut "gg".to_string(),100);
assert_eq!(find(&t, &mut "bcdea".to_string(),&mut "bed".to_string(),&mut "".to_string(), 2).value, 5);
assert_eq!(find(&t, &mut "ggag".to_string(),&mut "b".to_string(),&mut "".to_string(), 2).value, 100);
} | pat | identifier_name |
lisplike.rs | extern mod std;
use std::hashmap::HashMap;
use std::to_str::ToStr;
use std::rc::Rc;
use std::io::stdio::{print, println};
use sexpr;
// A very simple LISP-like language
// Globally scoped, no closures
/// Our value types
#[deriving(Clone)]
pub enum LispValue {
List(~[LispValue]),
Atom(~str),
Str(~str),
Num(f64),
Fn(~[~str], ~sexpr::Value), // args, body
BIF(~str, int, ~[~str], fn(Rc<HashMap<~str, ~LispValue>>, ~[~LispValue])->~LispValue) // built-in function (args, closure)
}
// XXX: this is ugly but it won't automatically derive Eq because of the extern fn
impl Eq for LispValue {
fn eq(&self, other: &LispValue) -> bool {
match (self.clone(), other.clone()) {
(BIF(ref x, _, _, _), BIF(ref y, _, _, _)) if *x == *y => true,
(Str(ref x), Str(ref y)) if *x == *y => true,
(Num(ref x), Num(ref y)) if *x == *y => true,
(Atom(ref x), Atom(ref y)) if *x == *y => true,
(List(ref x), List(ref y)) if *x == *y => true,
(Fn(ref x, ref x2), Fn(ref y, ref y2)) if *x == *y && *x2 == *y2 => true,
_ => false
}
}
}
impl LispValue {
/// Coerces this Lisp value to a native boolean. Empty lists (nil) are falsey,
/// everything else is truthy.
fn as_bool(&self) -> bool {
match *self {
List([]) => false, // nil
_ => true
}
}
}
impl ToStr for LispValue {
fn to_str(&self) -> ~str {
match *self {
Atom(ref s) => s.clone(),
Str(ref s) => s.clone(),
Num(ref f) => f.to_str(),
Fn(ref args, _) => format!("<fn({:u})>", args.len()),
BIF(ref name, ref arity, _, _) => format!("<fn {:s}({:i})>", name.clone(), *arity),
List(ref v) => {
let values: ~[~str] = v.iter().map(|x: &LispValue| x.to_str()).collect();
format!("({:s})", values.connect(" "))
}
}
}
}
fn from_sexpr(sexpr: &sexpr::Value) -> ~LispValue {
match *sexpr {
sexpr::List(ref v) => ~List(v.map(|x| *from_sexpr(x))),
sexpr::Num(v) => ~Num(v),
sexpr::Str(ref v) => ~Str(v.clone()),
sexpr::Atom(ref v) => ~Atom(v.clone())
}
}
fn to_sexpr(value: &LispValue) -> sexpr::Value {
match *value {
Num(ref v) => sexpr::Num(v.clone()),
Str(ref s) => sexpr::Str(s.clone()),
Atom(ref s) => sexpr::Atom(s.clone()),
List(ref v) => sexpr::List(v.iter().map(to_sexpr).to_owned_vec()),
Fn(..) => fail!("can't convert fn to an s-expression"),
BIF(..) => fail!("can't convert BIF to an s-expression"),
}
}
/// The type of the global symbol table (string to a value mapping).
type SymbolTable = HashMap<~str, ~LispValue>;
/// Returns a value representing the empty list
#[inline]
pub fn nil() -> ~LispValue {
~List(~[])
}
/// Creates a new symbol table and returns it
pub fn new_symt() -> SymbolTable {
HashMap::new()
}
/// Binds a symbol in the symbol table. Replaces if it already exists.
pub fn bind(symt: Rc<SymbolTable>, name: ~str, value: ~LispValue) {
symt.borrow().insert(name, value);
}
/// Look up a symbol in the symbol table. Fails if not found.
pub fn lookup(symt: Rc<SymbolTable>, name: ~str) -> ~LispValue {
match symt.borrow().find(&name) {
Some(v) => v.clone(),
None => fail!("couldn't find symbol: {}", name)
}
}
/// Identity function
fn id_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue { v[0] }
fn cons_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v {
[~a, ~b,..] => ~List(~[a, b]),
_ => fail!("cons: requires two arguments")
}
}
fn car_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~List(v_) => ~v_[0],
_ => fail!("car: need a list")
}
}
fn cdr_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~List(v_) => ~v_[1],
_ => fail!("cdr: need a list")
}
}
// Print function
fn print_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~Str(s) => println(s),
_ => fail!("print takes an str")
}
nil()
}
// There are several bugs in the macroing system (#8853, or, #8852 and #8851)
// that prevent us from making these functions macros. In addition, we can't
// return a closure because the type needs to be `extern "Rust" fn`, which
// closures aren't. So we have a little bit of code duplication.
fn plus_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("+ needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let add = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() + y.clone()),
(Str(ref x), &~Str(ref y)) => ~Str(x.clone() + y.clone()),
_ => fail!("invalid operands to +")
}
};
v.iter().skip(1).fold(v[0].clone(), add)
}
fn minus_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("- needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let sub = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() - y.clone()),
_ => fail!("invalid operands to -")
}
};
v.iter().skip(1).fold(v[0].clone(), sub)
}
fn mul_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("* needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let mul = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() * y.clone()),
_ => fail!("invalid operands to *")
}
};
v.iter().skip(1).fold(v[0].clone(), mul)
}
fn div_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("/ needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let div = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() / y.clone()),
_ => fail!("invalid operands to /")
}
};
v.iter().skip(1).fold(v[0].clone(), div)
}
fn equals_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v {
[a, b] => {
if a == b { ~Num(1.0) }
else { nil() }
}
_ => fail!("invalid operands to =")
}
}
/// Initializes standard library functions
pub fn init_std(symt: Rc<SymbolTable>) {
bind(symt, ~"id", ~BIF(~"id", 1, ~[~"x"], id_));
bind(symt, ~"print", ~BIF(~"print", 1, ~[~"msg"], print_));
bind(symt, ~"cons", ~BIF(~"cons", 2, ~[~"x", ~"y"], cons_));
bind(symt, ~"car", ~BIF(~"car", 1, ~[~"x"], car_));
bind(symt, ~"cdr", ~BIF(~"cdr", 1, ~[~"x"], cdr_));
bind(symt, ~"+", ~BIF(~"+", -1, ~[], plus_));
bind(symt, ~"*", ~BIF(~"*", -1, ~[], mul_));
bind(symt, ~"-", ~BIF(~"-", -1, ~[], minus_));
bind(symt, ~"/", ~BIF(~"/", -1, ~[], div_));
bind(symt, ~"=", ~BIF(~"=", 2, ~[~"x", ~"y"], equals_));
bind(symt, ~"true", ~Num(1.0));
bind(symt, ~"nil", nil());
}
fn apply(symt: Rc<SymbolTable>, f: ~LispValue, args: ~[~LispValue]) -> ~LispValue {
match *f {
BIF(name, arity, fnargs, bif) => {
// apply built-in function
if arity > 0 && fnargs.len() as int!= arity {
fail!("function '{:s}' requires {:d} arguments, but it received {:u} arguments",
name, arity, args.len())
}
bif(symt, args)
}
Fn(fnargs, body) => {
// apply a defined function
if args.len()!= fnargs.len() {
fail!("function requires {:u} arguments, but it received {:u} arguments",
fnargs.len(), args.len())
}
// bind its arguments in the environemnt and evaluate its body
for (name,value) in fnargs.iter().zip(args.iter()) {
bind(symt, name.clone(), value.clone());
}
eval(symt, *body)
}
v => fail!("") //fail!("apply: need function, received {}", v)
}
}
/// Evaluates an s-expression and returns a value.
pub fn eval(symt: Rc<SymbolTable>, input: sexpr::Value) -> ~LispValue {
match input {
sexpr::List(v) => {
if(v.len() == 0) {
fail!("eval given empty list")
}
// evaluate a list as a function call
match v {
[sexpr::Atom(~"quote"), arg] => from_sexpr(&arg),
[sexpr::Atom(~"def"), name, value] => {
// bind a value to an identifier
let ident = match name {
sexpr::Atom(s) => s,
sexpr::Str(s) => s,
_ => fail!("def requires an atom or a string")
};
bind(symt, ident, eval(symt, value));
nil()
},
[sexpr::Atom(~"cond"),..conds] => {
//let conds = conds.iter().map(|x: &sexpr::Value| from_sexpr(x));
for cond in conds.iter() {
match *cond {
sexpr::List([ref c, ref e]) => {
if eval(symt, c.clone()).as_bool() {
return eval(symt, e.clone())
}
}
_ => fail!("cond: need list of (condition expression)")
}
}
nil()
}
[sexpr::Atom(~"eval"),..args] => {
// takes an argument, evaluates it (like a function does)
// and then uses that as an argument to eval().
// e.g. (= (eval (quote (+ 1 2))) 3)
assert!(args.len() == 1);
eval(symt, to_sexpr(eval(symt, args[0].clone())))
}
[sexpr::Atom(~"fn"), sexpr::List(args), body] => {
// construct a function
let args_ = args.iter().map(|x| {
match x {
&sexpr::Atom(ref s) => s.clone(),
_ => fail!("fn: arguments need to be atoms")
}
}).collect();
~Fn(args_, ~body)
}
[ref fnval,..args] => {
let f = eval(symt, fnval.clone());
let xargs = args.map(|x| eval(symt, x.clone())); // eval'd args
apply(symt, f, xargs)
}
_ => fail!("eval: requires a variable or an application"),
}
}
sexpr::Atom(v) => {
// variable
lookup(symt, v)
}
_ => from_sexpr(&input) // return non-list values as they are
}
}
#[cfg(test)]
mod test {
use super::{SymbolTable, eval, init_std, new_symt, nil, Num, Str, Fn, List, Atom};
use sexpr;
use sexpr::from_str;
use std::rc::Rc;
fn read(input: &str) -> sexpr::Value {
from_str(input).unwrap()
}
#[test]
fn test_eval() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("123")), ~Num(123.0));
assert_eq!(eval(symt, read("(id 123)")), ~Num(123.0));
assert_eq!(eval(symt, read("(id (id (id 123)))")), ~Num(123.0));
// should fail: assert_eq!(eval(&mut symt, read("(1 2 3)")), ~List(~[Num(1.0), Num(2.0), Num(3.0)]));
}
#[test]
fn test_str() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(id \"hi\")")), ~Str(~"hi"));
assert_eq!(eval(symt, read("(car (cons \"a\" \"b\"))")), ~Str(~"a"));
// string concatenation
assert_eq!(eval(symt, read("(+ \"hi\" \" there\")")), ~Str(~"hi there"));
assert_eq!(eval(symt, read("(+ \"hi\" \" there\" \" variadic\")")), ~Str(~"hi there variadic"));
}
#[test]
fn test_cons() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cons 1 2)")), ~List(~[Num(1.0), Num(2.0)]));
assert_eq!(eval(symt, read("(cons 1 (cons 2 3))")), ~List(~[Num(1.0),
List(~[Num(2.0), Num(3.0)])]));
}
#[test]
fn test_car() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(car (cons 1 2))")), ~Num(1.0));
}
#[test]
fn test_cdr() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cdr (cons 1 2))")), ~Num(2.0));
assert_eq!(eval(symt, read("(cdr (cons 1 (cons 2 3)))")), ~List(~[Num(2.0), Num(3.0)]));
}
#[test]
fn test_arithmetic() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(+ 1 3)")), ~Num(4.0));
assert_eq!(eval(symt, read("(+ 1.5 3)")), ~Num(4.5));
assert_eq!(eval(symt, read("(+ 5 -3)")), ~Num(2.0));
assert_eq!(eval(symt, read("(- 5 3)")), ~Num(2.0));
assert_eq!(eval(symt, read("(- 3 5)")), ~Num(-2.0));
assert_eq!(eval(symt, read("(- 5 -3)")), ~Num(8.0));
assert_eq!(eval(symt, read("(* 2 5)")), ~Num(10.0));
assert_eq!(eval(symt, read("(* 2 -5)")), ~Num(-10.0));
assert_eq!(eval(symt, read("(/ 10 2)")), ~Num(5.0));
assert_eq!(eval(symt, read("(/ 10 -2)")), ~Num(-5.0));
assert_eq!(eval(symt, read("(+ 6 (+ 1 3))")), ~Num(10.0));
assert_eq!(eval(symt, read("(- 6 (- 3 2))")), ~Num(5.0));
assert_eq!(eval(symt, read("(+ 1 (+ 2 3) 4)")), ~Num(10.0));
assert_eq!(eval(symt, read("(+ 5)")), ~Num(5.0));
assert_eq!(eval(symt, read("(+ -5)")), ~Num(-5.0));
}
#[test]
fn test_quote() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(quote 5)")), ~Num(5.0));
assert_eq!(eval(symt, read("(quote x)")), ~Atom(~"x"));
assert_eq!(eval(symt, read("(quote (1 2 3))")), ~List(~[Num(1.0), Num(2.0), Num(3.0)]));
assert_eq!(eval(symt, read("(quote (x y z))")), ~List(~[Atom(~"x"), Atom(~"y"), Atom(~"z")]))
assert_eq!(eval(symt, read("(quote (quote x))")), ~List(~[Atom(~"quote"), Atom(~"x")]));
assert_eq!(eval(symt, read("(+ (quote 1) 2)")), ~Num(3.0));
//assert_eq!(eval(symt, read("(quote 1 2 3 4 5)")), ~Num(5.0));
}
#[test]
fn test_def() {
let mut symt = Rc::new(new_symt());
init_std(symt);
eval(symt, read("(def x 5)"));
eval(symt, read("(def y 10)"));
assert_eq!(eval(symt, read("x")), ~Num(5.0));
assert_eq!(eval(symt, read("y")), ~Num(10.0));
assert_eq!(eval(symt, read("(+ x y)")), ~Num(15.0));
}
#[test]
fn test_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(fn () ())")), ~Fn(~[], ~sexpr::List(~[])));
assert_eq!(eval(symt, read("(fn (x) (x))")), ~Fn(~[~"x"], ~sexpr::List(~[sexpr::Atom(~"x")])));
eval(symt, read("(def f (fn (x) (+ 1 x)))"));
assert_eq!(eval(symt, read("f")), ~Fn(~[~"x"],
~sexpr::List(~[sexpr::Atom(~"+"), sexpr::Num(1.0), sexpr::Atom(~"x")])));
assert_eq!(eval(symt, read("(f 5)")), ~Num(6.0));
}
#[test]
fn test_apply_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("((fn () 0))")), ~Num(0.0));
assert_eq!(eval(symt, read("((fn (x) x) 5)")), ~Num(5.0));
}
#[test]
fn test_cond() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cond (true 2) (nil 3))")), ~Num(2.0));
assert_eq!(eval(symt, read("(cond (nil 2) (true 3))")), ~Num(3.0));
assert_eq!(eval(symt, read("(cond (nil 2) (true 3) (true 4))")), ~Num(3.0));
}
#[test]
fn test_equals() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(= 1 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= 1.0 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= 1 2)")), nil());
assert_eq!(eval(symt, read("(= true 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil (quote ()))")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil nil)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil true)")), nil());
assert_eq!(eval(symt, read("(= \"a\" \"a\")")), ~Num(1.0));
assert_eq!(eval(symt, read("(= \"a\" \"b\")")), nil());
assert_eq!(eval(symt, read("(= (quote (1 2 3)) (quote (1 2 3)))")), ~Num(1.0));
}
#[test]
fn test_factorial() |
#[test]
fn test_eval_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(eval 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(eval \"hi\")")), ~Str(~"hi"));
assert_eq!(eval(symt, read("(eval (quote (+ 1 2)))")), ~Num(3.0));
assert_eq!(eval(symt, read("(eval (quote ( (fn () 0) )))")), ~Num(0.0));
}
}
#[ignore(test)]
#[main]
fn main() {
// A simple REPL
let mut stdinReader = std::io::buffered::BufferedReader::new(std::io::stdin());
let mut symt = Rc::new(new_symt());
init_std(symt);
loop {
print("> ");
let line = stdinReader.read_line();
match line {
Some(~".q") => break,
Some(~".newsym") => {
// use a fresh symbol table
symt = Rc::new(new_symt());
init_std(symt);
println("ok");
}
Some(line) => {
match sexpr::from_str(line) {
Some(sexpr) => println(eval(symt, sexpr).to_str()),
None => println("syntax error")
}
}
None => ()
}
}
} | {
let mut symt = Rc::new(new_symt());
init_std(symt);
eval(symt, read("(def fac (fn (n) (cond ((= n 0) 1) (true (* n (fac (- n 1)))))))"));
assert_eq!(eval(symt, read("(fac 10)")), ~Num(3628800.0));
} | identifier_body |
lisplike.rs | extern mod std;
use std::hashmap::HashMap;
use std::to_str::ToStr;
use std::rc::Rc;
use std::io::stdio::{print, println};
use sexpr;
// A very simple LISP-like language
// Globally scoped, no closures
/// Our value types
#[deriving(Clone)]
pub enum LispValue {
List(~[LispValue]),
Atom(~str),
Str(~str),
Num(f64),
Fn(~[~str], ~sexpr::Value), // args, body
BIF(~str, int, ~[~str], fn(Rc<HashMap<~str, ~LispValue>>, ~[~LispValue])->~LispValue) // built-in function (args, closure)
}
// XXX: this is ugly but it won't automatically derive Eq because of the extern fn
impl Eq for LispValue {
fn eq(&self, other: &LispValue) -> bool {
match (self.clone(), other.clone()) {
(BIF(ref x, _, _, _), BIF(ref y, _, _, _)) if *x == *y => true,
(Str(ref x), Str(ref y)) if *x == *y => true,
(Num(ref x), Num(ref y)) if *x == *y => true,
(Atom(ref x), Atom(ref y)) if *x == *y => true,
(List(ref x), List(ref y)) if *x == *y => true,
(Fn(ref x, ref x2), Fn(ref y, ref y2)) if *x == *y && *x2 == *y2 => true,
_ => false
}
}
}
impl LispValue {
/// Coerces this Lisp value to a native boolean. Empty lists (nil) are falsey,
/// everything else is truthy.
fn as_bool(&self) -> bool {
match *self {
List([]) => false, // nil
_ => true
}
}
}
impl ToStr for LispValue {
fn to_str(&self) -> ~str {
match *self {
Atom(ref s) => s.clone(),
Str(ref s) => s.clone(),
Num(ref f) => f.to_str(),
Fn(ref args, _) => format!("<fn({:u})>", args.len()),
BIF(ref name, ref arity, _, _) => format!("<fn {:s}({:i})>", name.clone(), *arity),
List(ref v) => {
let values: ~[~str] = v.iter().map(|x: &LispValue| x.to_str()).collect();
format!("({:s})", values.connect(" "))
}
}
}
}
fn from_sexpr(sexpr: &sexpr::Value) -> ~LispValue {
match *sexpr {
sexpr::List(ref v) => ~List(v.map(|x| *from_sexpr(x))),
sexpr::Num(v) => ~Num(v),
sexpr::Str(ref v) => ~Str(v.clone()),
sexpr::Atom(ref v) => ~Atom(v.clone())
}
}
fn to_sexpr(value: &LispValue) -> sexpr::Value {
match *value {
Num(ref v) => sexpr::Num(v.clone()),
Str(ref s) => sexpr::Str(s.clone()),
Atom(ref s) => sexpr::Atom(s.clone()),
List(ref v) => sexpr::List(v.iter().map(to_sexpr).to_owned_vec()),
Fn(..) => fail!("can't convert fn to an s-expression"),
BIF(..) => fail!("can't convert BIF to an s-expression"),
}
}
/// The type of the global symbol table (string to a value mapping).
type SymbolTable = HashMap<~str, ~LispValue>;
/// Returns a value representing the empty list
#[inline]
pub fn nil() -> ~LispValue {
~List(~[])
}
/// Creates a new symbol table and returns it
pub fn | () -> SymbolTable {
HashMap::new()
}
/// Binds a symbol in the symbol table. Replaces if it already exists.
pub fn bind(symt: Rc<SymbolTable>, name: ~str, value: ~LispValue) {
symt.borrow().insert(name, value);
}
/// Look up a symbol in the symbol table. Fails if not found.
pub fn lookup(symt: Rc<SymbolTable>, name: ~str) -> ~LispValue {
match symt.borrow().find(&name) {
Some(v) => v.clone(),
None => fail!("couldn't find symbol: {}", name)
}
}
/// Identity function
fn id_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue { v[0] }
fn cons_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v {
[~a, ~b,..] => ~List(~[a, b]),
_ => fail!("cons: requires two arguments")
}
}
fn car_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~List(v_) => ~v_[0],
_ => fail!("car: need a list")
}
}
fn cdr_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~List(v_) => ~v_[1],
_ => fail!("cdr: need a list")
}
}
// Print function
fn print_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~Str(s) => println(s),
_ => fail!("print takes an str")
}
nil()
}
// There are several bugs in the macroing system (#8853, or, #8852 and #8851)
// that prevent us from making these functions macros. In addition, we can't
// return a closure because the type needs to be `extern "Rust" fn`, which
// closures aren't. So we have a little bit of code duplication.
fn plus_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("+ needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let add = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() + y.clone()),
(Str(ref x), &~Str(ref y)) => ~Str(x.clone() + y.clone()),
_ => fail!("invalid operands to +")
}
};
v.iter().skip(1).fold(v[0].clone(), add)
}
fn minus_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("- needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let sub = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() - y.clone()),
_ => fail!("invalid operands to -")
}
};
v.iter().skip(1).fold(v[0].clone(), sub)
}
fn mul_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("* needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let mul = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() * y.clone()),
_ => fail!("invalid operands to *")
}
};
v.iter().skip(1).fold(v[0].clone(), mul)
}
fn div_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("/ needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let div = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() / y.clone()),
_ => fail!("invalid operands to /")
}
};
v.iter().skip(1).fold(v[0].clone(), div)
}
fn equals_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v {
[a, b] => {
if a == b { ~Num(1.0) }
else { nil() }
}
_ => fail!("invalid operands to =")
}
}
/// Initializes standard library functions
pub fn init_std(symt: Rc<SymbolTable>) {
bind(symt, ~"id", ~BIF(~"id", 1, ~[~"x"], id_));
bind(symt, ~"print", ~BIF(~"print", 1, ~[~"msg"], print_));
bind(symt, ~"cons", ~BIF(~"cons", 2, ~[~"x", ~"y"], cons_));
bind(symt, ~"car", ~BIF(~"car", 1, ~[~"x"], car_));
bind(symt, ~"cdr", ~BIF(~"cdr", 1, ~[~"x"], cdr_));
bind(symt, ~"+", ~BIF(~"+", -1, ~[], plus_));
bind(symt, ~"*", ~BIF(~"*", -1, ~[], mul_));
bind(symt, ~"-", ~BIF(~"-", -1, ~[], minus_));
bind(symt, ~"/", ~BIF(~"/", -1, ~[], div_));
bind(symt, ~"=", ~BIF(~"=", 2, ~[~"x", ~"y"], equals_));
bind(symt, ~"true", ~Num(1.0));
bind(symt, ~"nil", nil());
}
fn apply(symt: Rc<SymbolTable>, f: ~LispValue, args: ~[~LispValue]) -> ~LispValue {
match *f {
BIF(name, arity, fnargs, bif) => {
// apply built-in function
if arity > 0 && fnargs.len() as int!= arity {
fail!("function '{:s}' requires {:d} arguments, but it received {:u} arguments",
name, arity, args.len())
}
bif(symt, args)
}
Fn(fnargs, body) => {
// apply a defined function
if args.len()!= fnargs.len() {
fail!("function requires {:u} arguments, but it received {:u} arguments",
fnargs.len(), args.len())
}
// bind its arguments in the environemnt and evaluate its body
for (name,value) in fnargs.iter().zip(args.iter()) {
bind(symt, name.clone(), value.clone());
}
eval(symt, *body)
}
v => fail!("") //fail!("apply: need function, received {}", v)
}
}
/// Evaluates an s-expression and returns a value.
pub fn eval(symt: Rc<SymbolTable>, input: sexpr::Value) -> ~LispValue {
match input {
sexpr::List(v) => {
if(v.len() == 0) {
fail!("eval given empty list")
}
// evaluate a list as a function call
match v {
[sexpr::Atom(~"quote"), arg] => from_sexpr(&arg),
[sexpr::Atom(~"def"), name, value] => {
// bind a value to an identifier
let ident = match name {
sexpr::Atom(s) => s,
sexpr::Str(s) => s,
_ => fail!("def requires an atom or a string")
};
bind(symt, ident, eval(symt, value));
nil()
},
[sexpr::Atom(~"cond"),..conds] => {
//let conds = conds.iter().map(|x: &sexpr::Value| from_sexpr(x));
for cond in conds.iter() {
match *cond {
sexpr::List([ref c, ref e]) => {
if eval(symt, c.clone()).as_bool() {
return eval(symt, e.clone())
}
}
_ => fail!("cond: need list of (condition expression)")
}
}
nil()
}
[sexpr::Atom(~"eval"),..args] => {
// takes an argument, evaluates it (like a function does)
// and then uses that as an argument to eval().
// e.g. (= (eval (quote (+ 1 2))) 3)
assert!(args.len() == 1);
eval(symt, to_sexpr(eval(symt, args[0].clone())))
}
[sexpr::Atom(~"fn"), sexpr::List(args), body] => {
// construct a function
let args_ = args.iter().map(|x| {
match x {
&sexpr::Atom(ref s) => s.clone(),
_ => fail!("fn: arguments need to be atoms")
}
}).collect();
~Fn(args_, ~body)
}
[ref fnval,..args] => {
let f = eval(symt, fnval.clone());
let xargs = args.map(|x| eval(symt, x.clone())); // eval'd args
apply(symt, f, xargs)
}
_ => fail!("eval: requires a variable or an application"),
}
}
sexpr::Atom(v) => {
// variable
lookup(symt, v)
}
_ => from_sexpr(&input) // return non-list values as they are
}
}
#[cfg(test)]
mod test {
use super::{SymbolTable, eval, init_std, new_symt, nil, Num, Str, Fn, List, Atom};
use sexpr;
use sexpr::from_str;
use std::rc::Rc;
fn read(input: &str) -> sexpr::Value {
from_str(input).unwrap()
}
#[test]
fn test_eval() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("123")), ~Num(123.0));
assert_eq!(eval(symt, read("(id 123)")), ~Num(123.0));
assert_eq!(eval(symt, read("(id (id (id 123)))")), ~Num(123.0));
// should fail: assert_eq!(eval(&mut symt, read("(1 2 3)")), ~List(~[Num(1.0), Num(2.0), Num(3.0)]));
}
#[test]
fn test_str() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(id \"hi\")")), ~Str(~"hi"));
assert_eq!(eval(symt, read("(car (cons \"a\" \"b\"))")), ~Str(~"a"));
// string concatenation
assert_eq!(eval(symt, read("(+ \"hi\" \" there\")")), ~Str(~"hi there"));
assert_eq!(eval(symt, read("(+ \"hi\" \" there\" \" variadic\")")), ~Str(~"hi there variadic"));
}
#[test]
fn test_cons() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cons 1 2)")), ~List(~[Num(1.0), Num(2.0)]));
assert_eq!(eval(symt, read("(cons 1 (cons 2 3))")), ~List(~[Num(1.0),
List(~[Num(2.0), Num(3.0)])]));
}
#[test]
fn test_car() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(car (cons 1 2))")), ~Num(1.0));
}
#[test]
fn test_cdr() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cdr (cons 1 2))")), ~Num(2.0));
assert_eq!(eval(symt, read("(cdr (cons 1 (cons 2 3)))")), ~List(~[Num(2.0), Num(3.0)]));
}
#[test]
fn test_arithmetic() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(+ 1 3)")), ~Num(4.0));
assert_eq!(eval(symt, read("(+ 1.5 3)")), ~Num(4.5));
assert_eq!(eval(symt, read("(+ 5 -3)")), ~Num(2.0));
assert_eq!(eval(symt, read("(- 5 3)")), ~Num(2.0));
assert_eq!(eval(symt, read("(- 3 5)")), ~Num(-2.0));
assert_eq!(eval(symt, read("(- 5 -3)")), ~Num(8.0));
assert_eq!(eval(symt, read("(* 2 5)")), ~Num(10.0));
assert_eq!(eval(symt, read("(* 2 -5)")), ~Num(-10.0));
assert_eq!(eval(symt, read("(/ 10 2)")), ~Num(5.0));
assert_eq!(eval(symt, read("(/ 10 -2)")), ~Num(-5.0));
assert_eq!(eval(symt, read("(+ 6 (+ 1 3))")), ~Num(10.0));
assert_eq!(eval(symt, read("(- 6 (- 3 2))")), ~Num(5.0));
assert_eq!(eval(symt, read("(+ 1 (+ 2 3) 4)")), ~Num(10.0));
assert_eq!(eval(symt, read("(+ 5)")), ~Num(5.0));
assert_eq!(eval(symt, read("(+ -5)")), ~Num(-5.0));
}
#[test]
fn test_quote() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(quote 5)")), ~Num(5.0));
assert_eq!(eval(symt, read("(quote x)")), ~Atom(~"x"));
assert_eq!(eval(symt, read("(quote (1 2 3))")), ~List(~[Num(1.0), Num(2.0), Num(3.0)]));
assert_eq!(eval(symt, read("(quote (x y z))")), ~List(~[Atom(~"x"), Atom(~"y"), Atom(~"z")]))
assert_eq!(eval(symt, read("(quote (quote x))")), ~List(~[Atom(~"quote"), Atom(~"x")]));
assert_eq!(eval(symt, read("(+ (quote 1) 2)")), ~Num(3.0));
//assert_eq!(eval(symt, read("(quote 1 2 3 4 5)")), ~Num(5.0));
}
#[test]
fn test_def() {
let mut symt = Rc::new(new_symt());
init_std(symt);
eval(symt, read("(def x 5)"));
eval(symt, read("(def y 10)"));
assert_eq!(eval(symt, read("x")), ~Num(5.0));
assert_eq!(eval(symt, read("y")), ~Num(10.0));
assert_eq!(eval(symt, read("(+ x y)")), ~Num(15.0));
}
#[test]
fn test_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(fn () ())")), ~Fn(~[], ~sexpr::List(~[])));
assert_eq!(eval(symt, read("(fn (x) (x))")), ~Fn(~[~"x"], ~sexpr::List(~[sexpr::Atom(~"x")])));
eval(symt, read("(def f (fn (x) (+ 1 x)))"));
assert_eq!(eval(symt, read("f")), ~Fn(~[~"x"],
~sexpr::List(~[sexpr::Atom(~"+"), sexpr::Num(1.0), sexpr::Atom(~"x")])));
assert_eq!(eval(symt, read("(f 5)")), ~Num(6.0));
}
#[test]
fn test_apply_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("((fn () 0))")), ~Num(0.0));
assert_eq!(eval(symt, read("((fn (x) x) 5)")), ~Num(5.0));
}
#[test]
fn test_cond() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cond (true 2) (nil 3))")), ~Num(2.0));
assert_eq!(eval(symt, read("(cond (nil 2) (true 3))")), ~Num(3.0));
assert_eq!(eval(symt, read("(cond (nil 2) (true 3) (true 4))")), ~Num(3.0));
}
#[test]
fn test_equals() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(= 1 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= 1.0 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= 1 2)")), nil());
assert_eq!(eval(symt, read("(= true 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil (quote ()))")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil nil)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil true)")), nil());
assert_eq!(eval(symt, read("(= \"a\" \"a\")")), ~Num(1.0));
assert_eq!(eval(symt, read("(= \"a\" \"b\")")), nil());
assert_eq!(eval(symt, read("(= (quote (1 2 3)) (quote (1 2 3)))")), ~Num(1.0));
}
#[test]
fn test_factorial() {
let mut symt = Rc::new(new_symt());
init_std(symt);
eval(symt, read("(def fac (fn (n) (cond ((= n 0) 1) (true (* n (fac (- n 1)))))))"));
assert_eq!(eval(symt, read("(fac 10)")), ~Num(3628800.0));
}
#[test]
fn test_eval_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(eval 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(eval \"hi\")")), ~Str(~"hi"));
assert_eq!(eval(symt, read("(eval (quote (+ 1 2)))")), ~Num(3.0));
assert_eq!(eval(symt, read("(eval (quote ( (fn () 0) )))")), ~Num(0.0));
}
}
#[ignore(test)]
#[main]
fn main() {
// A simple REPL
let mut stdinReader = std::io::buffered::BufferedReader::new(std::io::stdin());
let mut symt = Rc::new(new_symt());
init_std(symt);
loop {
print("> ");
let line = stdinReader.read_line();
match line {
Some(~".q") => break,
Some(~".newsym") => {
// use a fresh symbol table
symt = Rc::new(new_symt());
init_std(symt);
println("ok");
}
Some(line) => {
match sexpr::from_str(line) {
Some(sexpr) => println(eval(symt, sexpr).to_str()),
None => println("syntax error")
}
}
None => ()
}
}
} | new_symt | identifier_name |
lisplike.rs | extern mod std;
use std::hashmap::HashMap;
use std::to_str::ToStr;
use std::rc::Rc;
use std::io::stdio::{print, println};
use sexpr;
// A very simple LISP-like language
// Globally scoped, no closures
/// Our value types
#[deriving(Clone)]
pub enum LispValue {
List(~[LispValue]),
Atom(~str),
Str(~str),
Num(f64),
Fn(~[~str], ~sexpr::Value), // args, body
BIF(~str, int, ~[~str], fn(Rc<HashMap<~str, ~LispValue>>, ~[~LispValue])->~LispValue) // built-in function (args, closure) |
// XXX: this is ugly but it won't automatically derive Eq because of the extern fn
impl Eq for LispValue {
fn eq(&self, other: &LispValue) -> bool {
match (self.clone(), other.clone()) {
(BIF(ref x, _, _, _), BIF(ref y, _, _, _)) if *x == *y => true,
(Str(ref x), Str(ref y)) if *x == *y => true,
(Num(ref x), Num(ref y)) if *x == *y => true,
(Atom(ref x), Atom(ref y)) if *x == *y => true,
(List(ref x), List(ref y)) if *x == *y => true,
(Fn(ref x, ref x2), Fn(ref y, ref y2)) if *x == *y && *x2 == *y2 => true,
_ => false
}
}
}
impl LispValue {
/// Coerces this Lisp value to a native boolean. Empty lists (nil) are falsey,
/// everything else is truthy.
fn as_bool(&self) -> bool {
match *self {
List([]) => false, // nil
_ => true
}
}
}
impl ToStr for LispValue {
fn to_str(&self) -> ~str {
match *self {
Atom(ref s) => s.clone(),
Str(ref s) => s.clone(),
Num(ref f) => f.to_str(),
Fn(ref args, _) => format!("<fn({:u})>", args.len()),
BIF(ref name, ref arity, _, _) => format!("<fn {:s}({:i})>", name.clone(), *arity),
List(ref v) => {
let values: ~[~str] = v.iter().map(|x: &LispValue| x.to_str()).collect();
format!("({:s})", values.connect(" "))
}
}
}
}
fn from_sexpr(sexpr: &sexpr::Value) -> ~LispValue {
match *sexpr {
sexpr::List(ref v) => ~List(v.map(|x| *from_sexpr(x))),
sexpr::Num(v) => ~Num(v),
sexpr::Str(ref v) => ~Str(v.clone()),
sexpr::Atom(ref v) => ~Atom(v.clone())
}
}
fn to_sexpr(value: &LispValue) -> sexpr::Value {
match *value {
Num(ref v) => sexpr::Num(v.clone()),
Str(ref s) => sexpr::Str(s.clone()),
Atom(ref s) => sexpr::Atom(s.clone()),
List(ref v) => sexpr::List(v.iter().map(to_sexpr).to_owned_vec()),
Fn(..) => fail!("can't convert fn to an s-expression"),
BIF(..) => fail!("can't convert BIF to an s-expression"),
}
}
/// The type of the global symbol table (string to a value mapping).
type SymbolTable = HashMap<~str, ~LispValue>;
/// Returns a value representing the empty list
#[inline]
pub fn nil() -> ~LispValue {
~List(~[])
}
/// Creates a new symbol table and returns it
pub fn new_symt() -> SymbolTable {
HashMap::new()
}
/// Binds a symbol in the symbol table. Replaces if it already exists.
pub fn bind(symt: Rc<SymbolTable>, name: ~str, value: ~LispValue) {
symt.borrow().insert(name, value);
}
/// Look up a symbol in the symbol table. Fails if not found.
pub fn lookup(symt: Rc<SymbolTable>, name: ~str) -> ~LispValue {
match symt.borrow().find(&name) {
Some(v) => v.clone(),
None => fail!("couldn't find symbol: {}", name)
}
}
/// Identity function
fn id_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue { v[0] }
fn cons_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v {
[~a, ~b,..] => ~List(~[a, b]),
_ => fail!("cons: requires two arguments")
}
}
fn car_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~List(v_) => ~v_[0],
_ => fail!("car: need a list")
}
}
fn cdr_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~List(v_) => ~v_[1],
_ => fail!("cdr: need a list")
}
}
// Print function
fn print_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~Str(s) => println(s),
_ => fail!("print takes an str")
}
nil()
}
// There are several bugs in the macroing system (#8853, or, #8852 and #8851)
// that prevent us from making these functions macros. In addition, we can't
// return a closure because the type needs to be `extern "Rust" fn`, which
// closures aren't. So we have a little bit of code duplication.
fn plus_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("+ needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let add = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() + y.clone()),
(Str(ref x), &~Str(ref y)) => ~Str(x.clone() + y.clone()),
_ => fail!("invalid operands to +")
}
};
v.iter().skip(1).fold(v[0].clone(), add)
}
fn minus_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("- needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let sub = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() - y.clone()),
_ => fail!("invalid operands to -")
}
};
v.iter().skip(1).fold(v[0].clone(), sub)
}
fn mul_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("* needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let mul = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() * y.clone()),
_ => fail!("invalid operands to *")
}
};
v.iter().skip(1).fold(v[0].clone(), mul)
}
fn div_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("/ needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let div = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() / y.clone()),
_ => fail!("invalid operands to /")
}
};
v.iter().skip(1).fold(v[0].clone(), div)
}
fn equals_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v {
[a, b] => {
if a == b { ~Num(1.0) }
else { nil() }
}
_ => fail!("invalid operands to =")
}
}
/// Initializes standard library functions
pub fn init_std(symt: Rc<SymbolTable>) {
bind(symt, ~"id", ~BIF(~"id", 1, ~[~"x"], id_));
bind(symt, ~"print", ~BIF(~"print", 1, ~[~"msg"], print_));
bind(symt, ~"cons", ~BIF(~"cons", 2, ~[~"x", ~"y"], cons_));
bind(symt, ~"car", ~BIF(~"car", 1, ~[~"x"], car_));
bind(symt, ~"cdr", ~BIF(~"cdr", 1, ~[~"x"], cdr_));
bind(symt, ~"+", ~BIF(~"+", -1, ~[], plus_));
bind(symt, ~"*", ~BIF(~"*", -1, ~[], mul_));
bind(symt, ~"-", ~BIF(~"-", -1, ~[], minus_));
bind(symt, ~"/", ~BIF(~"/", -1, ~[], div_));
bind(symt, ~"=", ~BIF(~"=", 2, ~[~"x", ~"y"], equals_));
bind(symt, ~"true", ~Num(1.0));
bind(symt, ~"nil", nil());
}
fn apply(symt: Rc<SymbolTable>, f: ~LispValue, args: ~[~LispValue]) -> ~LispValue {
match *f {
BIF(name, arity, fnargs, bif) => {
// apply built-in function
if arity > 0 && fnargs.len() as int!= arity {
fail!("function '{:s}' requires {:d} arguments, but it received {:u} arguments",
name, arity, args.len())
}
bif(symt, args)
}
Fn(fnargs, body) => {
// apply a defined function
if args.len()!= fnargs.len() {
fail!("function requires {:u} arguments, but it received {:u} arguments",
fnargs.len(), args.len())
}
// bind its arguments in the environemnt and evaluate its body
for (name,value) in fnargs.iter().zip(args.iter()) {
bind(symt, name.clone(), value.clone());
}
eval(symt, *body)
}
v => fail!("") //fail!("apply: need function, received {}", v)
}
}
/// Evaluates an s-expression and returns a value.
pub fn eval(symt: Rc<SymbolTable>, input: sexpr::Value) -> ~LispValue {
match input {
sexpr::List(v) => {
if(v.len() == 0) {
fail!("eval given empty list")
}
// evaluate a list as a function call
match v {
[sexpr::Atom(~"quote"), arg] => from_sexpr(&arg),
[sexpr::Atom(~"def"), name, value] => {
// bind a value to an identifier
let ident = match name {
sexpr::Atom(s) => s,
sexpr::Str(s) => s,
_ => fail!("def requires an atom or a string")
};
bind(symt, ident, eval(symt, value));
nil()
},
[sexpr::Atom(~"cond"),..conds] => {
//let conds = conds.iter().map(|x: &sexpr::Value| from_sexpr(x));
for cond in conds.iter() {
match *cond {
sexpr::List([ref c, ref e]) => {
if eval(symt, c.clone()).as_bool() {
return eval(symt, e.clone())
}
}
_ => fail!("cond: need list of (condition expression)")
}
}
nil()
}
[sexpr::Atom(~"eval"),..args] => {
// takes an argument, evaluates it (like a function does)
// and then uses that as an argument to eval().
// e.g. (= (eval (quote (+ 1 2))) 3)
assert!(args.len() == 1);
eval(symt, to_sexpr(eval(symt, args[0].clone())))
}
[sexpr::Atom(~"fn"), sexpr::List(args), body] => {
// construct a function
let args_ = args.iter().map(|x| {
match x {
&sexpr::Atom(ref s) => s.clone(),
_ => fail!("fn: arguments need to be atoms")
}
}).collect();
~Fn(args_, ~body)
}
[ref fnval,..args] => {
let f = eval(symt, fnval.clone());
let xargs = args.map(|x| eval(symt, x.clone())); // eval'd args
apply(symt, f, xargs)
}
_ => fail!("eval: requires a variable or an application"),
}
}
sexpr::Atom(v) => {
// variable
lookup(symt, v)
}
_ => from_sexpr(&input) // return non-list values as they are
}
}
#[cfg(test)]
mod test {
use super::{SymbolTable, eval, init_std, new_symt, nil, Num, Str, Fn, List, Atom};
use sexpr;
use sexpr::from_str;
use std::rc::Rc;
fn read(input: &str) -> sexpr::Value {
from_str(input).unwrap()
}
#[test]
fn test_eval() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("123")), ~Num(123.0));
assert_eq!(eval(symt, read("(id 123)")), ~Num(123.0));
assert_eq!(eval(symt, read("(id (id (id 123)))")), ~Num(123.0));
// should fail: assert_eq!(eval(&mut symt, read("(1 2 3)")), ~List(~[Num(1.0), Num(2.0), Num(3.0)]));
}
#[test]
fn test_str() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(id \"hi\")")), ~Str(~"hi"));
assert_eq!(eval(symt, read("(car (cons \"a\" \"b\"))")), ~Str(~"a"));
// string concatenation
assert_eq!(eval(symt, read("(+ \"hi\" \" there\")")), ~Str(~"hi there"));
assert_eq!(eval(symt, read("(+ \"hi\" \" there\" \" variadic\")")), ~Str(~"hi there variadic"));
}
#[test]
fn test_cons() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cons 1 2)")), ~List(~[Num(1.0), Num(2.0)]));
assert_eq!(eval(symt, read("(cons 1 (cons 2 3))")), ~List(~[Num(1.0),
List(~[Num(2.0), Num(3.0)])]));
}
#[test]
fn test_car() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(car (cons 1 2))")), ~Num(1.0));
}
#[test]
fn test_cdr() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cdr (cons 1 2))")), ~Num(2.0));
assert_eq!(eval(symt, read("(cdr (cons 1 (cons 2 3)))")), ~List(~[Num(2.0), Num(3.0)]));
}
#[test]
fn test_arithmetic() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(+ 1 3)")), ~Num(4.0));
assert_eq!(eval(symt, read("(+ 1.5 3)")), ~Num(4.5));
assert_eq!(eval(symt, read("(+ 5 -3)")), ~Num(2.0));
assert_eq!(eval(symt, read("(- 5 3)")), ~Num(2.0));
assert_eq!(eval(symt, read("(- 3 5)")), ~Num(-2.0));
assert_eq!(eval(symt, read("(- 5 -3)")), ~Num(8.0));
assert_eq!(eval(symt, read("(* 2 5)")), ~Num(10.0));
assert_eq!(eval(symt, read("(* 2 -5)")), ~Num(-10.0));
assert_eq!(eval(symt, read("(/ 10 2)")), ~Num(5.0));
assert_eq!(eval(symt, read("(/ 10 -2)")), ~Num(-5.0));
assert_eq!(eval(symt, read("(+ 6 (+ 1 3))")), ~Num(10.0));
assert_eq!(eval(symt, read("(- 6 (- 3 2))")), ~Num(5.0));
assert_eq!(eval(symt, read("(+ 1 (+ 2 3) 4)")), ~Num(10.0));
assert_eq!(eval(symt, read("(+ 5)")), ~Num(5.0));
assert_eq!(eval(symt, read("(+ -5)")), ~Num(-5.0));
}
#[test]
fn test_quote() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(quote 5)")), ~Num(5.0));
assert_eq!(eval(symt, read("(quote x)")), ~Atom(~"x"));
assert_eq!(eval(symt, read("(quote (1 2 3))")), ~List(~[Num(1.0), Num(2.0), Num(3.0)]));
assert_eq!(eval(symt, read("(quote (x y z))")), ~List(~[Atom(~"x"), Atom(~"y"), Atom(~"z")]))
assert_eq!(eval(symt, read("(quote (quote x))")), ~List(~[Atom(~"quote"), Atom(~"x")]));
assert_eq!(eval(symt, read("(+ (quote 1) 2)")), ~Num(3.0));
//assert_eq!(eval(symt, read("(quote 1 2 3 4 5)")), ~Num(5.0));
}
#[test]
fn test_def() {
let mut symt = Rc::new(new_symt());
init_std(symt);
eval(symt, read("(def x 5)"));
eval(symt, read("(def y 10)"));
assert_eq!(eval(symt, read("x")), ~Num(5.0));
assert_eq!(eval(symt, read("y")), ~Num(10.0));
assert_eq!(eval(symt, read("(+ x y)")), ~Num(15.0));
}
#[test]
fn test_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(fn () ())")), ~Fn(~[], ~sexpr::List(~[])));
assert_eq!(eval(symt, read("(fn (x) (x))")), ~Fn(~[~"x"], ~sexpr::List(~[sexpr::Atom(~"x")])));
eval(symt, read("(def f (fn (x) (+ 1 x)))"));
assert_eq!(eval(symt, read("f")), ~Fn(~[~"x"],
~sexpr::List(~[sexpr::Atom(~"+"), sexpr::Num(1.0), sexpr::Atom(~"x")])));
assert_eq!(eval(symt, read("(f 5)")), ~Num(6.0));
}
#[test]
fn test_apply_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("((fn () 0))")), ~Num(0.0));
assert_eq!(eval(symt, read("((fn (x) x) 5)")), ~Num(5.0));
}
#[test]
fn test_cond() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cond (true 2) (nil 3))")), ~Num(2.0));
assert_eq!(eval(symt, read("(cond (nil 2) (true 3))")), ~Num(3.0));
assert_eq!(eval(symt, read("(cond (nil 2) (true 3) (true 4))")), ~Num(3.0));
}
#[test]
fn test_equals() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(= 1 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= 1.0 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= 1 2)")), nil());
assert_eq!(eval(symt, read("(= true 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil (quote ()))")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil nil)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil true)")), nil());
assert_eq!(eval(symt, read("(= \"a\" \"a\")")), ~Num(1.0));
assert_eq!(eval(symt, read("(= \"a\" \"b\")")), nil());
assert_eq!(eval(symt, read("(= (quote (1 2 3)) (quote (1 2 3)))")), ~Num(1.0));
}
#[test]
fn test_factorial() {
let mut symt = Rc::new(new_symt());
init_std(symt);
eval(symt, read("(def fac (fn (n) (cond ((= n 0) 1) (true (* n (fac (- n 1)))))))"));
assert_eq!(eval(symt, read("(fac 10)")), ~Num(3628800.0));
}
#[test]
fn test_eval_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(eval 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(eval \"hi\")")), ~Str(~"hi"));
assert_eq!(eval(symt, read("(eval (quote (+ 1 2)))")), ~Num(3.0));
assert_eq!(eval(symt, read("(eval (quote ( (fn () 0) )))")), ~Num(0.0));
}
}
#[ignore(test)]
#[main]
fn main() {
// A simple REPL
let mut stdinReader = std::io::buffered::BufferedReader::new(std::io::stdin());
let mut symt = Rc::new(new_symt());
init_std(symt);
loop {
print("> ");
let line = stdinReader.read_line();
match line {
Some(~".q") => break,
Some(~".newsym") => {
// use a fresh symbol table
symt = Rc::new(new_symt());
init_std(symt);
println("ok");
}
Some(line) => {
match sexpr::from_str(line) {
Some(sexpr) => println(eval(symt, sexpr).to_str()),
None => println("syntax error")
}
}
None => ()
}
}
} | } | random_line_split |
apply.rs | use crate::{
patch::{Hunk, Line, Patch},
utils::LineIter,
};
use std::collections::VecDeque;
use std::{fmt, iter};
/// An error returned when [`apply`]ing a `Patch` fails
///
/// [`apply`]: fn.apply.html
#[derive(Debug)]
pub struct ApplyError(usize);
impl fmt::Display for ApplyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "error applying hunk #{}", self.0)
}
}
impl std::error::Error for ApplyError {}
#[derive(Debug)]
enum ImageLine<'a, T:?Sized> {
Unpatched(&'a T),
Patched(&'a T),
}
impl<'a, T:?Sized> ImageLine<'a, T> {
fn inner(&self) -> &'a T {
match self {
ImageLine::Unpatched(inner) | ImageLine::Patched(inner) => inner,
}
}
fn into_inner(self) -> &'a T {
self.inner()
}
fn is_patched(&self) -> bool {
match self {
ImageLine::Unpatched(_) => false,
ImageLine::Patched(_) => true,
}
}
}
impl<T:?Sized> Copy for ImageLine<'_, T> {}
impl<T:?Sized> Clone for ImageLine<'_, T> {
fn clone(&self) -> Self {
*self
}
}
#[derive(Debug)]
pub struct ApplyOptions {
max_fuzzy: usize,
}
impl Default for ApplyOptions {
fn default() -> Self {
ApplyOptions::new()
}
}
impl ApplyOptions {
pub fn new() -> Self {
ApplyOptions { max_fuzzy: 0 }
}
pub fn with_max_fuzzy(mut self, max_fuzzy: usize) -> Self {
self.max_fuzzy = max_fuzzy;
self
}
}
/// Apply a `Patch` to a base image
///
/// ```
/// use diffy::{apply, Patch};
///
/// let s = "\
/// --- a/ideals
/// +++ b/ideals
/// @@ -1,4 +1,6 @@
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// +Second:
/// + I will protect those who cannot protect themselves.
/// ";
///
/// let patch = Patch::from_str(s).unwrap();
///
/// let base_image = "\
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// ";
///
/// let expected = "\
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// Second:
/// I will protect those who cannot protect themselves.
/// ";
///
/// assert_eq!(apply(base_image, &patch).unwrap(), expected);
/// ```
pub fn apply(base_image: &str, patch: &Patch<'_, str>) -> Result<String, ApplyError> {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
for (i, hunk) in patch.hunks().iter().enumerate() {
apply_hunk(&mut image, hunk, &ApplyOptions::new()).map_err(|_| ApplyError(i + 1))?;
}
Ok(image.into_iter().map(ImageLine::into_inner).collect())
}
/// Apply a non-utf8 `Patch` to a base image
pub fn apply_bytes(base_image: &[u8], patch: &Patch<'_, [u8]>) -> Result<Vec<u8>, ApplyError> {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
for (i, hunk) in patch.hunks().iter().enumerate() {
apply_hunk(&mut image, hunk, &ApplyOptions::new()).map_err(|_| ApplyError(i + 1))?;
}
Ok(image
.into_iter()
.flat_map(ImageLine::into_inner)
.copied()
.collect())
}
/// Try applying all hunks a `Patch` to a base image
pub fn apply_all_bytes(
base_image: &[u8],
patch: &Patch<'_, [u8]>,
options: ApplyOptions,
) -> (Vec<u8>, Vec<usize>) {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
let mut failed_indices = Vec::new();
for (i, hunk) in patch.hunks().iter().enumerate() {
if let Some(_) = apply_hunk(&mut image, hunk, &options).err() {
failed_indices.push(i);
}
}
(
image
.into_iter()
.flat_map(ImageLine::into_inner)
.copied()
.collect(),
failed_indices,
)
}
/// Try applying all hunks a `Patch` to a base image
pub fn apply_all(
base_image: &str,
patch: &Patch<'_, str>,
options: ApplyOptions,
) -> (String, Vec<usize>) {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
let mut failed_indices = Vec::new();
for (i, hunk) in patch.hunks().iter().enumerate() {
if let Some(_) = apply_hunk(&mut image, hunk, &options).err() {
failed_indices.push(i);
}
}
(
image.into_iter().map(ImageLine::into_inner).collect(),
failed_indices,
)
}
fn apply_hunk<'a, T: PartialEq +?Sized>(
image: &mut Vec<ImageLine<'a, T>>,
hunk: &Hunk<'a, T>,
options: &ApplyOptions,
) -> Result<(), ()> {
// Find position
let max_fuzzy = pre_context_line_count(hunk.lines())
.min(post_context_line_count(hunk.lines()))
.min(options.max_fuzzy);
let (pos, fuzzy) = find_position(image, hunk, max_fuzzy).ok_or(())?;
let begin = pos + fuzzy;
let end = pos
+ pre_image_line_count(hunk.lines())
.checked_sub(fuzzy)
.unwrap_or(0);
// update image
image.splice(
begin..end,
skip_last(post_image(hunk.lines()).skip(fuzzy), fuzzy).map(ImageLine::Patched),
);
Ok(())
}
// Search in `image` for a palce to apply hunk.
// This follows the general algorithm (minus fuzzy-matching context lines) described in GNU patch's
// man page.
//
// It might be worth looking into other possible positions to apply the hunk to as described here:
// https://neil.fraser.name/writing/patch/
fn find_position<T: PartialEq +?Sized>(
image: &[ImageLine<T>],
hunk: &Hunk<'_, T>,
max_fuzzy: usize,
) -> Option<(usize, usize)> {
let pos = hunk.new_range().start().saturating_sub(1);
for fuzzy in 0..=max_fuzzy {
// Create an iterator that starts with 'pos' and then interleaves
// moving pos backward/foward by one.
let backward = (0..pos).rev();
let forward = pos + 1..image.len();
for pos in iter::once(pos).chain(interleave(backward, forward)) {
if match_fragment(image, hunk.lines(), pos, fuzzy) {
return Some((pos, fuzzy));
}
}
}
None
}
fn pre_context_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
lines
.iter()
.take_while(|x| matches!(x, Line::Context(_)))
.count()
}
fn post_context_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
lines
.iter()
.rev()
.take_while(|x| matches!(x, Line::Context(_)))
.count()
}
fn pre_image_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
pre_image(lines).count()
}
fn post_image<'a, 'b, T:?Sized>(lines: &'b [Line<'a, T>]) -> impl Iterator<Item = &'a T> + 'b {
lines.iter().filter_map(|line| match line {
Line::Context(l) | Line::Insert(l) => Some(*l),
Line::Delete(_) => None,
})
}
fn pre_image<'a, 'b, T:?Sized>(lines: &'b [Line<'a, T>]) -> impl Iterator<Item = &'a T> + 'b {
lines.iter().filter_map(|line| match line {
Line::Context(l) | Line::Delete(l) => Some(*l),
Line::Insert(_) => None,
})
}
fn match_fragment<T: PartialEq +?Sized>(
image: &[ImageLine<T>],
lines: &[Line<'_, T>],
pos: usize,
fuzzy: usize,
) -> bool {
let len = pre_image_line_count(lines);
let begin = pos + fuzzy;
let end = pos + len.checked_sub(fuzzy).unwrap_or(0);
let image = if let Some(image) = image.get(begin..end) {
image
} else | ;
// If any of these lines have already been patched then we can't match at this position
if image.iter().any(ImageLine::is_patched) {
return false;
}
pre_image(lines).eq(image.iter().map(ImageLine::inner))
}
#[derive(Debug)]
struct Interleave<I, J> {
a: iter::Fuse<I>,
b: iter::Fuse<J>,
flag: bool,
}
fn interleave<I, J>(
i: I,
j: J,
) -> Interleave<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter>
where
I: IntoIterator,
J: IntoIterator<Item = I::Item>,
{
Interleave {
a: i.into_iter().fuse(),
b: j.into_iter().fuse(),
flag: false,
}
}
impl<I, J> Iterator for Interleave<I, J>
where
I: Iterator,
J: Iterator<Item = I::Item>,
{
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
self.flag =!self.flag;
if self.flag {
match self.a.next() {
None => self.b.next(),
item => item,
}
} else {
match self.b.next() {
None => self.a.next(),
item => item,
}
}
}
}
fn skip_last<I: Iterator>(iter: I, count: usize) -> SkipLast<I, I::Item> {
SkipLast {
iter: iter.fuse(),
buffer: VecDeque::with_capacity(count),
count,
}
}
#[derive(Debug)]
struct SkipLast<Iter: Iterator<Item = Item>, Item> {
iter: iter::Fuse<Iter>,
buffer: VecDeque<Item>,
count: usize,
}
impl<Iter: Iterator<Item = Item>, Item> Iterator for SkipLast<Iter, Item> {
type Item = Item;
fn next(&mut self) -> Option<Self::Item> {
if self.count == 0 {
return self.iter.next();
}
while self.buffer.len()!= self.count {
self.buffer.push_front(self.iter.next()?);
}
let next = self.iter.next()?;
let res = self.buffer.pop_back()?;
self.buffer.push_front(next);
Some(res)
}
}
#[cfg(test)]
mod skip_last_test {
use crate::apply::skip_last;
#[test]
fn skip_last_test() {
let a = [1, 2, 3, 4, 5, 6, 7];
assert_eq!(
skip_last(a.iter().copied(), 0)
.collect::<Vec<_>>()
.as_slice(),
&[1, 2, 3, 4, 5, 6, 7]
);
assert_eq!(
skip_last(a.iter().copied(), 5)
.collect::<Vec<_>>()
.as_slice(),
&[1, 2]
);
assert_eq!(
skip_last(a.iter().copied(), 7)
.collect::<Vec<_>>()
.as_slice(),
&[]
);
}
}
| {
return false;
} | conditional_block |
apply.rs | use crate::{
patch::{Hunk, Line, Patch},
utils::LineIter,
};
use std::collections::VecDeque;
use std::{fmt, iter};
/// An error returned when [`apply`]ing a `Patch` fails
///
/// [`apply`]: fn.apply.html
#[derive(Debug)]
pub struct ApplyError(usize);
impl fmt::Display for ApplyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "error applying hunk #{}", self.0)
}
}
impl std::error::Error for ApplyError {}
#[derive(Debug)]
enum ImageLine<'a, T:?Sized> {
Unpatched(&'a T),
Patched(&'a T),
}
impl<'a, T:?Sized> ImageLine<'a, T> {
fn inner(&self) -> &'a T {
match self {
ImageLine::Unpatched(inner) | ImageLine::Patched(inner) => inner,
}
}
fn into_inner(self) -> &'a T {
self.inner()
}
fn is_patched(&self) -> bool {
match self {
ImageLine::Unpatched(_) => false,
ImageLine::Patched(_) => true,
}
}
}
impl<T:?Sized> Copy for ImageLine<'_, T> {}
impl<T:?Sized> Clone for ImageLine<'_, T> {
fn clone(&self) -> Self {
*self
}
}
#[derive(Debug)]
pub struct ApplyOptions {
max_fuzzy: usize,
}
impl Default for ApplyOptions {
fn default() -> Self {
ApplyOptions::new()
}
}
impl ApplyOptions {
pub fn new() -> Self {
ApplyOptions { max_fuzzy: 0 }
}
pub fn with_max_fuzzy(mut self, max_fuzzy: usize) -> Self {
self.max_fuzzy = max_fuzzy;
self
}
}
/// Apply a `Patch` to a base image
///
/// ```
/// use diffy::{apply, Patch};
///
/// let s = "\
/// --- a/ideals
/// +++ b/ideals
/// @@ -1,4 +1,6 @@
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// +Second:
/// + I will protect those who cannot protect themselves.
/// ";
///
/// let patch = Patch::from_str(s).unwrap();
///
/// let base_image = "\
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// ";
///
/// let expected = "\
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// Second:
/// I will protect those who cannot protect themselves.
/// ";
///
/// assert_eq!(apply(base_image, &patch).unwrap(), expected);
/// ```
pub fn apply(base_image: &str, patch: &Patch<'_, str>) -> Result<String, ApplyError> {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
for (i, hunk) in patch.hunks().iter().enumerate() {
apply_hunk(&mut image, hunk, &ApplyOptions::new()).map_err(|_| ApplyError(i + 1))?;
}
Ok(image.into_iter().map(ImageLine::into_inner).collect())
}
/// Apply a non-utf8 `Patch` to a base image
pub fn apply_bytes(base_image: &[u8], patch: &Patch<'_, [u8]>) -> Result<Vec<u8>, ApplyError> {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
for (i, hunk) in patch.hunks().iter().enumerate() {
apply_hunk(&mut image, hunk, &ApplyOptions::new()).map_err(|_| ApplyError(i + 1))?;
}
Ok(image
.into_iter()
.flat_map(ImageLine::into_inner)
.copied()
.collect())
}
/// Try applying all hunks a `Patch` to a base image
pub fn apply_all_bytes(
base_image: &[u8],
patch: &Patch<'_, [u8]>,
options: ApplyOptions,
) -> (Vec<u8>, Vec<usize>) {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
let mut failed_indices = Vec::new();
for (i, hunk) in patch.hunks().iter().enumerate() {
if let Some(_) = apply_hunk(&mut image, hunk, &options).err() {
failed_indices.push(i);
}
}
(
image
.into_iter()
.flat_map(ImageLine::into_inner)
.copied()
.collect(),
failed_indices,
)
}
/// Try applying all hunks a `Patch` to a base image
pub fn apply_all(
base_image: &str,
patch: &Patch<'_, str>,
options: ApplyOptions,
) -> (String, Vec<usize>) {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
let mut failed_indices = Vec::new();
for (i, hunk) in patch.hunks().iter().enumerate() {
if let Some(_) = apply_hunk(&mut image, hunk, &options).err() {
failed_indices.push(i);
}
}
(
image.into_iter().map(ImageLine::into_inner).collect(),
failed_indices,
)
}
fn apply_hunk<'a, T: PartialEq +?Sized>(
image: &mut Vec<ImageLine<'a, T>>,
hunk: &Hunk<'a, T>,
options: &ApplyOptions,
) -> Result<(), ()> {
// Find position
let max_fuzzy = pre_context_line_count(hunk.lines())
.min(post_context_line_count(hunk.lines()))
.min(options.max_fuzzy);
let (pos, fuzzy) = find_position(image, hunk, max_fuzzy).ok_or(())?;
let begin = pos + fuzzy;
let end = pos
+ pre_image_line_count(hunk.lines())
.checked_sub(fuzzy)
.unwrap_or(0);
// update image
image.splice(
begin..end,
skip_last(post_image(hunk.lines()).skip(fuzzy), fuzzy).map(ImageLine::Patched),
);
Ok(())
}
// Search in `image` for a palce to apply hunk.
// This follows the general algorithm (minus fuzzy-matching context lines) described in GNU patch's
// man page.
//
// It might be worth looking into other possible positions to apply the hunk to as described here:
// https://neil.fraser.name/writing/patch/
fn find_position<T: PartialEq +?Sized>(
image: &[ImageLine<T>],
hunk: &Hunk<'_, T>,
max_fuzzy: usize,
) -> Option<(usize, usize)> {
let pos = hunk.new_range().start().saturating_sub(1);
for fuzzy in 0..=max_fuzzy {
// Create an iterator that starts with 'pos' and then interleaves
// moving pos backward/foward by one.
let backward = (0..pos).rev();
let forward = pos + 1..image.len();
for pos in iter::once(pos).chain(interleave(backward, forward)) {
if match_fragment(image, hunk.lines(), pos, fuzzy) {
return Some((pos, fuzzy));
}
}
}
None
}
fn pre_context_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
lines
.iter()
.take_while(|x| matches!(x, Line::Context(_)))
.count()
}
fn post_context_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
lines
.iter()
.rev()
.take_while(|x| matches!(x, Line::Context(_)))
.count()
}
fn pre_image_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
pre_image(lines).count()
}
fn post_image<'a, 'b, T:?Sized>(lines: &'b [Line<'a, T>]) -> impl Iterator<Item = &'a T> + 'b {
lines.iter().filter_map(|line| match line {
Line::Context(l) | Line::Insert(l) => Some(*l),
Line::Delete(_) => None,
})
}
fn pre_image<'a, 'b, T:?Sized>(lines: &'b [Line<'a, T>]) -> impl Iterator<Item = &'a T> + 'b {
lines.iter().filter_map(|line| match line {
Line::Context(l) | Line::Delete(l) => Some(*l),
Line::Insert(_) => None,
})
}
fn match_fragment<T: PartialEq +?Sized>(
image: &[ImageLine<T>],
lines: &[Line<'_, T>],
pos: usize,
fuzzy: usize,
) -> bool {
let len = pre_image_line_count(lines);
let begin = pos + fuzzy;
let end = pos + len.checked_sub(fuzzy).unwrap_or(0);
let image = if let Some(image) = image.get(begin..end) {
image
} else {
return false;
};
// If any of these lines have already been patched then we can't match at this position
if image.iter().any(ImageLine::is_patched) {
return false;
}
pre_image(lines).eq(image.iter().map(ImageLine::inner))
}
#[derive(Debug)]
struct Interleave<I, J> {
a: iter::Fuse<I>,
b: iter::Fuse<J>,
flag: bool,
}
fn interleave<I, J>(
i: I,
j: J,
) -> Interleave<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter>
where
I: IntoIterator,
J: IntoIterator<Item = I::Item>,
{
Interleave {
a: i.into_iter().fuse(),
b: j.into_iter().fuse(),
flag: false,
}
}
impl<I, J> Iterator for Interleave<I, J>
where
I: Iterator,
J: Iterator<Item = I::Item>,
{
type Item = I::Item;
fn | (&mut self) -> Option<I::Item> {
self.flag =!self.flag;
if self.flag {
match self.a.next() {
None => self.b.next(),
item => item,
}
} else {
match self.b.next() {
None => self.a.next(),
item => item,
}
}
}
}
fn skip_last<I: Iterator>(iter: I, count: usize) -> SkipLast<I, I::Item> {
SkipLast {
iter: iter.fuse(),
buffer: VecDeque::with_capacity(count),
count,
}
}
#[derive(Debug)]
struct SkipLast<Iter: Iterator<Item = Item>, Item> {
iter: iter::Fuse<Iter>,
buffer: VecDeque<Item>,
count: usize,
}
impl<Iter: Iterator<Item = Item>, Item> Iterator for SkipLast<Iter, Item> {
type Item = Item;
fn next(&mut self) -> Option<Self::Item> {
if self.count == 0 {
return self.iter.next();
}
while self.buffer.len()!= self.count {
self.buffer.push_front(self.iter.next()?);
}
let next = self.iter.next()?;
let res = self.buffer.pop_back()?;
self.buffer.push_front(next);
Some(res)
}
}
#[cfg(test)]
mod skip_last_test {
use crate::apply::skip_last;
#[test]
fn skip_last_test() {
let a = [1, 2, 3, 4, 5, 6, 7];
assert_eq!(
skip_last(a.iter().copied(), 0)
.collect::<Vec<_>>()
.as_slice(),
&[1, 2, 3, 4, 5, 6, 7]
);
assert_eq!(
skip_last(a.iter().copied(), 5)
.collect::<Vec<_>>()
.as_slice(),
&[1, 2]
);
assert_eq!(
skip_last(a.iter().copied(), 7)
.collect::<Vec<_>>()
.as_slice(),
&[]
);
}
}
| next | identifier_name |
apply.rs | use crate::{
patch::{Hunk, Line, Patch},
utils::LineIter,
};
use std::collections::VecDeque;
use std::{fmt, iter};
/// An error returned when [`apply`]ing a `Patch` fails
///
/// [`apply`]: fn.apply.html
#[derive(Debug)]
pub struct ApplyError(usize);
impl fmt::Display for ApplyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "error applying hunk #{}", self.0)
}
}
impl std::error::Error for ApplyError {}
#[derive(Debug)]
enum ImageLine<'a, T:?Sized> {
Unpatched(&'a T),
Patched(&'a T),
}
impl<'a, T:?Sized> ImageLine<'a, T> {
fn inner(&self) -> &'a T |
fn into_inner(self) -> &'a T {
self.inner()
}
fn is_patched(&self) -> bool {
match self {
ImageLine::Unpatched(_) => false,
ImageLine::Patched(_) => true,
}
}
}
impl<T:?Sized> Copy for ImageLine<'_, T> {}
impl<T:?Sized> Clone for ImageLine<'_, T> {
fn clone(&self) -> Self {
*self
}
}
#[derive(Debug)]
pub struct ApplyOptions {
max_fuzzy: usize,
}
impl Default for ApplyOptions {
fn default() -> Self {
ApplyOptions::new()
}
}
impl ApplyOptions {
pub fn new() -> Self {
ApplyOptions { max_fuzzy: 0 }
}
pub fn with_max_fuzzy(mut self, max_fuzzy: usize) -> Self {
self.max_fuzzy = max_fuzzy;
self
}
}
/// Apply a `Patch` to a base image
///
/// ```
/// use diffy::{apply, Patch};
///
/// let s = "\
/// --- a/ideals
/// +++ b/ideals
/// @@ -1,4 +1,6 @@
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// +Second:
/// + I will protect those who cannot protect themselves.
/// ";
///
/// let patch = Patch::from_str(s).unwrap();
///
/// let base_image = "\
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// ";
///
/// let expected = "\
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// Second:
/// I will protect those who cannot protect themselves.
/// ";
///
/// assert_eq!(apply(base_image, &patch).unwrap(), expected);
/// ```
pub fn apply(base_image: &str, patch: &Patch<'_, str>) -> Result<String, ApplyError> {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
for (i, hunk) in patch.hunks().iter().enumerate() {
apply_hunk(&mut image, hunk, &ApplyOptions::new()).map_err(|_| ApplyError(i + 1))?;
}
Ok(image.into_iter().map(ImageLine::into_inner).collect())
}
/// Apply a non-utf8 `Patch` to a base image
pub fn apply_bytes(base_image: &[u8], patch: &Patch<'_, [u8]>) -> Result<Vec<u8>, ApplyError> {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
for (i, hunk) in patch.hunks().iter().enumerate() {
apply_hunk(&mut image, hunk, &ApplyOptions::new()).map_err(|_| ApplyError(i + 1))?;
}
Ok(image
.into_iter()
.flat_map(ImageLine::into_inner)
.copied()
.collect())
}
/// Try applying all hunks a `Patch` to a base image
pub fn apply_all_bytes(
base_image: &[u8],
patch: &Patch<'_, [u8]>,
options: ApplyOptions,
) -> (Vec<u8>, Vec<usize>) {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
let mut failed_indices = Vec::new();
for (i, hunk) in patch.hunks().iter().enumerate() {
if let Some(_) = apply_hunk(&mut image, hunk, &options).err() {
failed_indices.push(i);
}
}
(
image
.into_iter()
.flat_map(ImageLine::into_inner)
.copied()
.collect(),
failed_indices,
)
}
/// Try applying all hunks a `Patch` to a base image
pub fn apply_all(
base_image: &str,
patch: &Patch<'_, str>,
options: ApplyOptions,
) -> (String, Vec<usize>) {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
let mut failed_indices = Vec::new();
for (i, hunk) in patch.hunks().iter().enumerate() {
if let Some(_) = apply_hunk(&mut image, hunk, &options).err() {
failed_indices.push(i);
}
}
(
image.into_iter().map(ImageLine::into_inner).collect(),
failed_indices,
)
}
fn apply_hunk<'a, T: PartialEq +?Sized>(
image: &mut Vec<ImageLine<'a, T>>,
hunk: &Hunk<'a, T>,
options: &ApplyOptions,
) -> Result<(), ()> {
// Find position
let max_fuzzy = pre_context_line_count(hunk.lines())
.min(post_context_line_count(hunk.lines()))
.min(options.max_fuzzy);
let (pos, fuzzy) = find_position(image, hunk, max_fuzzy).ok_or(())?;
let begin = pos + fuzzy;
let end = pos
+ pre_image_line_count(hunk.lines())
.checked_sub(fuzzy)
.unwrap_or(0);
// update image
image.splice(
begin..end,
skip_last(post_image(hunk.lines()).skip(fuzzy), fuzzy).map(ImageLine::Patched),
);
Ok(())
}
// Search in `image` for a palce to apply hunk.
// This follows the general algorithm (minus fuzzy-matching context lines) described in GNU patch's
// man page.
//
// It might be worth looking into other possible positions to apply the hunk to as described here:
// https://neil.fraser.name/writing/patch/
fn find_position<T: PartialEq +?Sized>(
image: &[ImageLine<T>],
hunk: &Hunk<'_, T>,
max_fuzzy: usize,
) -> Option<(usize, usize)> {
let pos = hunk.new_range().start().saturating_sub(1);
for fuzzy in 0..=max_fuzzy {
// Create an iterator that starts with 'pos' and then interleaves
// moving pos backward/foward by one.
let backward = (0..pos).rev();
let forward = pos + 1..image.len();
for pos in iter::once(pos).chain(interleave(backward, forward)) {
if match_fragment(image, hunk.lines(), pos, fuzzy) {
return Some((pos, fuzzy));
}
}
}
None
}
fn pre_context_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
lines
.iter()
.take_while(|x| matches!(x, Line::Context(_)))
.count()
}
fn post_context_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
lines
.iter()
.rev()
.take_while(|x| matches!(x, Line::Context(_)))
.count()
}
fn pre_image_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
pre_image(lines).count()
}
fn post_image<'a, 'b, T:?Sized>(lines: &'b [Line<'a, T>]) -> impl Iterator<Item = &'a T> + 'b {
lines.iter().filter_map(|line| match line {
Line::Context(l) | Line::Insert(l) => Some(*l),
Line::Delete(_) => None,
})
}
fn pre_image<'a, 'b, T:?Sized>(lines: &'b [Line<'a, T>]) -> impl Iterator<Item = &'a T> + 'b {
lines.iter().filter_map(|line| match line {
Line::Context(l) | Line::Delete(l) => Some(*l),
Line::Insert(_) => None,
})
}
fn match_fragment<T: PartialEq +?Sized>(
image: &[ImageLine<T>],
lines: &[Line<'_, T>],
pos: usize,
fuzzy: usize,
) -> bool {
let len = pre_image_line_count(lines);
let begin = pos + fuzzy;
let end = pos + len.checked_sub(fuzzy).unwrap_or(0);
let image = if let Some(image) = image.get(begin..end) {
image
} else {
return false;
};
// If any of these lines have already been patched then we can't match at this position
if image.iter().any(ImageLine::is_patched) {
return false;
}
pre_image(lines).eq(image.iter().map(ImageLine::inner))
}
#[derive(Debug)]
struct Interleave<I, J> {
a: iter::Fuse<I>,
b: iter::Fuse<J>,
flag: bool,
}
fn interleave<I, J>(
i: I,
j: J,
) -> Interleave<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter>
where
I: IntoIterator,
J: IntoIterator<Item = I::Item>,
{
Interleave {
a: i.into_iter().fuse(),
b: j.into_iter().fuse(),
flag: false,
}
}
impl<I, J> Iterator for Interleave<I, J>
where
I: Iterator,
J: Iterator<Item = I::Item>,
{
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
self.flag =!self.flag;
if self.flag {
match self.a.next() {
None => self.b.next(),
item => item,
}
} else {
match self.b.next() {
None => self.a.next(),
item => item,
}
}
}
}
fn skip_last<I: Iterator>(iter: I, count: usize) -> SkipLast<I, I::Item> {
SkipLast {
iter: iter.fuse(),
buffer: VecDeque::with_capacity(count),
count,
}
}
#[derive(Debug)]
struct SkipLast<Iter: Iterator<Item = Item>, Item> {
iter: iter::Fuse<Iter>,
buffer: VecDeque<Item>,
count: usize,
}
impl<Iter: Iterator<Item = Item>, Item> Iterator for SkipLast<Iter, Item> {
type Item = Item;
fn next(&mut self) -> Option<Self::Item> {
if self.count == 0 {
return self.iter.next();
}
while self.buffer.len()!= self.count {
self.buffer.push_front(self.iter.next()?);
}
let next = self.iter.next()?;
let res = self.buffer.pop_back()?;
self.buffer.push_front(next);
Some(res)
}
}
#[cfg(test)]
mod skip_last_test {
use crate::apply::skip_last;
#[test]
fn skip_last_test() {
let a = [1, 2, 3, 4, 5, 6, 7];
assert_eq!(
skip_last(a.iter().copied(), 0)
.collect::<Vec<_>>()
.as_slice(),
&[1, 2, 3, 4, 5, 6, 7]
);
assert_eq!(
skip_last(a.iter().copied(), 5)
.collect::<Vec<_>>()
.as_slice(),
&[1, 2]
);
assert_eq!(
skip_last(a.iter().copied(), 7)
.collect::<Vec<_>>()
.as_slice(),
&[]
);
}
}
| {
match self {
ImageLine::Unpatched(inner) | ImageLine::Patched(inner) => inner,
}
} | identifier_body |
apply.rs | use crate::{
patch::{Hunk, Line, Patch},
utils::LineIter,
};
use std::collections::VecDeque;
use std::{fmt, iter};
/// An error returned when [`apply`]ing a `Patch` fails
///
/// [`apply`]: fn.apply.html
#[derive(Debug)]
pub struct ApplyError(usize);
impl fmt::Display for ApplyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "error applying hunk #{}", self.0)
}
}
impl std::error::Error for ApplyError {}
#[derive(Debug)]
enum ImageLine<'a, T:?Sized> {
Unpatched(&'a T),
Patched(&'a T),
}
impl<'a, T:?Sized> ImageLine<'a, T> {
fn inner(&self) -> &'a T {
match self {
ImageLine::Unpatched(inner) | ImageLine::Patched(inner) => inner,
}
}
fn into_inner(self) -> &'a T {
self.inner()
}
fn is_patched(&self) -> bool {
match self {
ImageLine::Unpatched(_) => false,
ImageLine::Patched(_) => true,
}
}
}
impl<T:?Sized> Copy for ImageLine<'_, T> {}
impl<T:?Sized> Clone for ImageLine<'_, T> {
fn clone(&self) -> Self {
*self
}
}
#[derive(Debug)]
pub struct ApplyOptions {
max_fuzzy: usize,
}
impl Default for ApplyOptions {
fn default() -> Self {
ApplyOptions::new()
}
}
impl ApplyOptions {
pub fn new() -> Self {
ApplyOptions { max_fuzzy: 0 }
}
pub fn with_max_fuzzy(mut self, max_fuzzy: usize) -> Self {
self.max_fuzzy = max_fuzzy;
self
}
}
/// Apply a `Patch` to a base image
///
/// ```
/// use diffy::{apply, Patch};
///
/// let s = "\
/// --- a/ideals
/// +++ b/ideals
/// @@ -1,4 +1,6 @@
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// +Second:
/// + I will protect those who cannot protect themselves.
/// ";
///
/// let patch = Patch::from_str(s).unwrap();
///
/// let base_image = "\
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// ";
///
/// let expected = "\
/// First:
/// Life before death,
/// strength before weakness,
/// journey before destination.
/// Second:
/// I will protect those who cannot protect themselves.
/// ";
///
/// assert_eq!(apply(base_image, &patch).unwrap(), expected);
/// ```
pub fn apply(base_image: &str, patch: &Patch<'_, str>) -> Result<String, ApplyError> {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
for (i, hunk) in patch.hunks().iter().enumerate() {
apply_hunk(&mut image, hunk, &ApplyOptions::new()).map_err(|_| ApplyError(i + 1))?;
}
Ok(image.into_iter().map(ImageLine::into_inner).collect()) | }
/// Apply a non-utf8 `Patch` to a base image
pub fn apply_bytes(base_image: &[u8], patch: &Patch<'_, [u8]>) -> Result<Vec<u8>, ApplyError> {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
for (i, hunk) in patch.hunks().iter().enumerate() {
apply_hunk(&mut image, hunk, &ApplyOptions::new()).map_err(|_| ApplyError(i + 1))?;
}
Ok(image
.into_iter()
.flat_map(ImageLine::into_inner)
.copied()
.collect())
}
/// Try applying all hunks a `Patch` to a base image
pub fn apply_all_bytes(
base_image: &[u8],
patch: &Patch<'_, [u8]>,
options: ApplyOptions,
) -> (Vec<u8>, Vec<usize>) {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
let mut failed_indices = Vec::new();
for (i, hunk) in patch.hunks().iter().enumerate() {
if let Some(_) = apply_hunk(&mut image, hunk, &options).err() {
failed_indices.push(i);
}
}
(
image
.into_iter()
.flat_map(ImageLine::into_inner)
.copied()
.collect(),
failed_indices,
)
}
/// Try applying all hunks a `Patch` to a base image
pub fn apply_all(
base_image: &str,
patch: &Patch<'_, str>,
options: ApplyOptions,
) -> (String, Vec<usize>) {
let mut image: Vec<_> = LineIter::new(base_image)
.map(ImageLine::Unpatched)
.collect();
let mut failed_indices = Vec::new();
for (i, hunk) in patch.hunks().iter().enumerate() {
if let Some(_) = apply_hunk(&mut image, hunk, &options).err() {
failed_indices.push(i);
}
}
(
image.into_iter().map(ImageLine::into_inner).collect(),
failed_indices,
)
}
fn apply_hunk<'a, T: PartialEq +?Sized>(
image: &mut Vec<ImageLine<'a, T>>,
hunk: &Hunk<'a, T>,
options: &ApplyOptions,
) -> Result<(), ()> {
// Find position
let max_fuzzy = pre_context_line_count(hunk.lines())
.min(post_context_line_count(hunk.lines()))
.min(options.max_fuzzy);
let (pos, fuzzy) = find_position(image, hunk, max_fuzzy).ok_or(())?;
let begin = pos + fuzzy;
let end = pos
+ pre_image_line_count(hunk.lines())
.checked_sub(fuzzy)
.unwrap_or(0);
// update image
image.splice(
begin..end,
skip_last(post_image(hunk.lines()).skip(fuzzy), fuzzy).map(ImageLine::Patched),
);
Ok(())
}
// Search in `image` for a palce to apply hunk.
// This follows the general algorithm (minus fuzzy-matching context lines) described in GNU patch's
// man page.
//
// It might be worth looking into other possible positions to apply the hunk to as described here:
// https://neil.fraser.name/writing/patch/
fn find_position<T: PartialEq +?Sized>(
image: &[ImageLine<T>],
hunk: &Hunk<'_, T>,
max_fuzzy: usize,
) -> Option<(usize, usize)> {
let pos = hunk.new_range().start().saturating_sub(1);
for fuzzy in 0..=max_fuzzy {
// Create an iterator that starts with 'pos' and then interleaves
// moving pos backward/foward by one.
let backward = (0..pos).rev();
let forward = pos + 1..image.len();
for pos in iter::once(pos).chain(interleave(backward, forward)) {
if match_fragment(image, hunk.lines(), pos, fuzzy) {
return Some((pos, fuzzy));
}
}
}
None
}
fn pre_context_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
lines
.iter()
.take_while(|x| matches!(x, Line::Context(_)))
.count()
}
fn post_context_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
lines
.iter()
.rev()
.take_while(|x| matches!(x, Line::Context(_)))
.count()
}
fn pre_image_line_count<T:?Sized>(lines: &[Line<'_, T>]) -> usize {
pre_image(lines).count()
}
fn post_image<'a, 'b, T:?Sized>(lines: &'b [Line<'a, T>]) -> impl Iterator<Item = &'a T> + 'b {
lines.iter().filter_map(|line| match line {
Line::Context(l) | Line::Insert(l) => Some(*l),
Line::Delete(_) => None,
})
}
fn pre_image<'a, 'b, T:?Sized>(lines: &'b [Line<'a, T>]) -> impl Iterator<Item = &'a T> + 'b {
lines.iter().filter_map(|line| match line {
Line::Context(l) | Line::Delete(l) => Some(*l),
Line::Insert(_) => None,
})
}
fn match_fragment<T: PartialEq +?Sized>(
image: &[ImageLine<T>],
lines: &[Line<'_, T>],
pos: usize,
fuzzy: usize,
) -> bool {
let len = pre_image_line_count(lines);
let begin = pos + fuzzy;
let end = pos + len.checked_sub(fuzzy).unwrap_or(0);
let image = if let Some(image) = image.get(begin..end) {
image
} else {
return false;
};
// If any of these lines have already been patched then we can't match at this position
if image.iter().any(ImageLine::is_patched) {
return false;
}
pre_image(lines).eq(image.iter().map(ImageLine::inner))
}
#[derive(Debug)]
struct Interleave<I, J> {
a: iter::Fuse<I>,
b: iter::Fuse<J>,
flag: bool,
}
fn interleave<I, J>(
i: I,
j: J,
) -> Interleave<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter>
where
I: IntoIterator,
J: IntoIterator<Item = I::Item>,
{
Interleave {
a: i.into_iter().fuse(),
b: j.into_iter().fuse(),
flag: false,
}
}
impl<I, J> Iterator for Interleave<I, J>
where
I: Iterator,
J: Iterator<Item = I::Item>,
{
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
self.flag =!self.flag;
if self.flag {
match self.a.next() {
None => self.b.next(),
item => item,
}
} else {
match self.b.next() {
None => self.a.next(),
item => item,
}
}
}
}
fn skip_last<I: Iterator>(iter: I, count: usize) -> SkipLast<I, I::Item> {
SkipLast {
iter: iter.fuse(),
buffer: VecDeque::with_capacity(count),
count,
}
}
#[derive(Debug)]
struct SkipLast<Iter: Iterator<Item = Item>, Item> {
iter: iter::Fuse<Iter>,
buffer: VecDeque<Item>,
count: usize,
}
impl<Iter: Iterator<Item = Item>, Item> Iterator for SkipLast<Iter, Item> {
type Item = Item;
fn next(&mut self) -> Option<Self::Item> {
if self.count == 0 {
return self.iter.next();
}
while self.buffer.len()!= self.count {
self.buffer.push_front(self.iter.next()?);
}
let next = self.iter.next()?;
let res = self.buffer.pop_back()?;
self.buffer.push_front(next);
Some(res)
}
}
#[cfg(test)]
mod skip_last_test {
use crate::apply::skip_last;
#[test]
fn skip_last_test() {
let a = [1, 2, 3, 4, 5, 6, 7];
assert_eq!(
skip_last(a.iter().copied(), 0)
.collect::<Vec<_>>()
.as_slice(),
&[1, 2, 3, 4, 5, 6, 7]
);
assert_eq!(
skip_last(a.iter().copied(), 5)
.collect::<Vec<_>>()
.as_slice(),
&[1, 2]
);
assert_eq!(
skip_last(a.iter().copied(), 7)
.collect::<Vec<_>>()
.as_slice(),
&[]
);
}
} | random_line_split |
|
memory.rs | //! Interface with Screeps' `Memory` global variable
//!
//! Screeps' memory lives in the javascript `Memory` global variable and is
//! encoded as a javascript object. This object's reference is tracked within
//! rust as a `MemoryReference`. The [`root`] function gives access to a
//! reference to the `Memory` global object.
//!
//! # Typing
//! Contrary to accessing the memory in javascript, rust's strong type system,
//! requires that read values be assigned a type. To facilitate this, the
//! `MemoryReference` provides methods to read a part of the memory as a
//! certain type. If the value read cannot be transformed to the requested
//! type, the method return `None`.
//!
//! # Accessing the memory
//! Memory can be accessed in two ways:
//! - via _keys_
//! - via _paths_ (methods prefixed with `path_`)
//!
//! In both cases, if the value requested is `undefined`, `null`, or even just
//! of the wrong type, the method returns `None`.
//!
//! ## Accessing memory with a _key_
//! Since a `MemoryReference` represents a javascript object, its children can
//! be accessed using the `object["key"]` javascript syntax using type methods.
//! ```no_run
//! let mem = screeps::memory::root();
//! let cpu_used_last_tick = mem.i32("cpu_used_last_tick").unwrap();
//! ```
//!
//! ## Accessing memory with a _path_
//! A quality of life improvement upon the key access is through full path. In
//! javascript, it is possible to query a value with a full path:
//! ```javascript
//! var creep_time = Memory.creeps.John.time;
//! ```
//!
//! To emulate this behavior in rust, you can write such a path to a string and
//! it will fetch the javascript object using
//! [lodash](https://lodash.com/docs/4.17.10#get) and convert the result
//! depending on the method used. For example,
//! ```no_run
//! let mem = screeps::memory::root();
//! let creep_time = mem.path_i32("creeps.John.time").unwrap();
//! ```
//!
//! # Other methods that provide `MemoryReference`s
//! In addition to accessing the memory from the root, it is possible to
//! access the memory via creeps, spawns, rooms and flags. Accessing the memory
//! from those objects will also result in a `MemoryReference` which instead
//! points at the root of this object's memory.
//!
//! [`root`]: crate::memory::root
use std::fmt;
use stdweb::{JsSerialize, Reference, Value};
use crate::{
traits::{TryFrom, TryInto},
ConversionError,
};
#[derive(Clone, Debug)]
pub struct UnexpectedTypeError;
impl fmt::Display for UnexpectedTypeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: include &'static str references to the type names in this error...
write!(f, "expected one memory type, found another")
}
}
// TODO: do we even need this over just a raw 'Reference'?
/// A [`Reference`] to a screeps memory object
///
/// [`Reference`]: stdweb::Reference
pub struct MemoryReference(Reference);
impl AsRef<Reference> for MemoryReference {
fn as_ref(&self) -> &Reference {
&self.0
}
}
impl Default for MemoryReference {
fn default() -> Self {
Self::new()
}
}
impl MemoryReference {
pub fn new() -> Self {
js_unwrap!({})
}
/// Creates a MemoryReference from some JavaScript reference.
///
/// Warning: `MemoryReference` is only designed to work with "plain"
/// JavaScript objects, and passing an array or a non-plain object
/// into this method probably won't be what you want. `MemoryReference`
/// also gives access to all properties, so if this is indeed a plain
/// object, all of its values should also be plain objects.
///
/// Passing a non-plain-object reference into this function won't
/// invoke undefined behavior in and of itself, but other functions
/// can rely on `MemoryReference` being "plain".
pub unsafe fn from_reference_unchecked(reference: Reference) -> Self {
MemoryReference(reference)
}
pub fn bool(&self, key: &str) -> bool {
js_unwrap!(Boolean(@{self.as_ref()}[@{key}]))
}
pub fn path_bool(&self, path: &str) -> bool {
js_unwrap!(Boolean(_.get(@{self.as_ref()}, @{path})))
}
pub fn f64(&self, key: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_f64(&self, path: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn i32(&self, key: &str) -> Result<Option<i32>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_i32(&self, path: &str) -> Result<Option<i32>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn string(&self, key: &str) -> Result<Option<String>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_string(&self, path: &str) -> Result<Option<String>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn dict(&self, key: &str) -> Result<Option<MemoryReference>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_dict(&self, path: &str) -> Result<Option<MemoryReference>, ConversionError> {
(js! { | return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
/// Get a dictionary value or create it if it does not exist.
///
/// If the value exists but is a different type, this will return `None`.
pub fn dict_or_create(&self, key: &str) -> Result<MemoryReference, UnexpectedTypeError> {
(js! {
var map = (@{self.as_ref()});
var key = (@{key});
var value = map[key];
if (value === null || value === undefined) {
map[key] = value = {};
}
if ((typeof value) == "object" &&!_.isArray(value)) {
return value;
} else {
return null;
}
})
.try_into()
.map_err(|_| UnexpectedTypeError)
.map(MemoryReference)
}
pub fn keys(&self) -> Vec<String> {
js_unwrap!(Object.keys(@{self.as_ref()}))
}
pub fn del(&self, key: &str) {
js! { @(no_return)
(@{self.as_ref()})[@{key}] = undefined;
}
}
pub fn path_del(&self, path: &str) {
js! {
_.set(@{self.as_ref()}, @{path}, undefined);
}
}
/// Gets a custom type. Will return `None` if `null` or `undefined`, and
/// `Err` if incorrect type.
///
/// # Example
///
/// ```no_run
/// use log::info;
/// use screeps::{prelude::*, Position};
///
/// let creep = screeps::game::creeps::get("mycreepname").unwrap();
/// let mem = creep.memory();
/// let pos = mem.get::<Position>("saved_pos").unwrap();
/// let pos = match pos {
/// Some(pos) => {
/// info!("found position: {}", pos);
/// pos
/// }
/// None => {
/// info!("no position. saving new one!");
/// let pos = creep.pos();
/// mem.set("saved_pos", pos);
/// pos
/// }
/// };
/// info!("final position: {}", pos);
/// creep.move_to(&pos);
/// ```
pub fn get<T>(&self, key: &str) -> Result<Option<T>, <T as TryFrom<Value>>::Error>
where
T: TryFrom<Value>,
{
let val = js! {
return (@{self.as_ref()})[@{key}];
};
if val == Value::Null || val == Value::Undefined {
Ok(None)
} else {
Some(val.try_into()).transpose()
}
}
/// Gets a custom type at a memory path. Will return `None` if `null` or
/// `undefined`, and `Err` if incorrect type.
///
/// Uses lodash in JavaScript to evaluate the path. See https://lodash.com/docs/#get.
pub fn get_path<T>(&self, path: &str) -> Result<Option<T>, <T as TryFrom<Value>>::Error>
where
T: TryFrom<Value>,
{
let val = js! {
return _.get(@{self.as_ref()}, @{path});
};
if val == Value::Null || val == Value::Undefined {
Ok(None)
} else {
Some(val.try_into()).transpose()
}
}
pub fn set<T>(&self, key: &str, value: T)
where
T: JsSerialize,
{
js! { @(no_return)
(@{self.as_ref()})[@{key}] = @{value};
}
}
pub fn path_set<T>(&self, path: &str, value: T)
where
T: JsSerialize,
{
js! { @(no_return)
_.set(@{self.as_ref()}, @{path}, @{value});
}
}
pub fn arr<T>(&self, key: &str) -> Result<Option<Vec<T>>, ConversionError>
where
T: TryFrom<Value, Error = ConversionError>,
{
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_arr<T>(&self, path: &str) -> Result<Option<Vec<T>>, ConversionError>
where
T: TryFrom<Value, Error = ConversionError>,
{
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
}
impl TryFrom<Value> for MemoryReference {
type Error = ConversionError;
fn try_from(v: Value) -> Result<Self, Self::Error> {
let r: Reference = v.try_into()?; // fail early.
Ok(MemoryReference(
(js! {
var v = (@{r});
if (_.isArray(v)) {
return null;
} else {
return v;
}
})
.try_into()?,
))
}
}
/// Get a reference to the `Memory` global object
pub fn root() -> MemoryReference {
js_unwrap!(Memory)
} | random_line_split |
|
memory.rs | //! Interface with Screeps' `Memory` global variable
//!
//! Screeps' memory lives in the javascript `Memory` global variable and is
//! encoded as a javascript object. This object's reference is tracked within
//! rust as a `MemoryReference`. The [`root`] function gives access to a
//! reference to the `Memory` global object.
//!
//! # Typing
//! Contrary to accessing the memory in javascript, rust's strong type system,
//! requires that read values be assigned a type. To facilitate this, the
//! `MemoryReference` provides methods to read a part of the memory as a
//! certain type. If the value read cannot be transformed to the requested
//! type, the method return `None`.
//!
//! # Accessing the memory
//! Memory can be accessed in two ways:
//! - via _keys_
//! - via _paths_ (methods prefixed with `path_`)
//!
//! In both cases, if the value requested is `undefined`, `null`, or even just
//! of the wrong type, the method returns `None`.
//!
//! ## Accessing memory with a _key_
//! Since a `MemoryReference` represents a javascript object, its children can
//! be accessed using the `object["key"]` javascript syntax using type methods.
//! ```no_run
//! let mem = screeps::memory::root();
//! let cpu_used_last_tick = mem.i32("cpu_used_last_tick").unwrap();
//! ```
//!
//! ## Accessing memory with a _path_
//! A quality of life improvement upon the key access is through full path. In
//! javascript, it is possible to query a value with a full path:
//! ```javascript
//! var creep_time = Memory.creeps.John.time;
//! ```
//!
//! To emulate this behavior in rust, you can write such a path to a string and
//! it will fetch the javascript object using
//! [lodash](https://lodash.com/docs/4.17.10#get) and convert the result
//! depending on the method used. For example,
//! ```no_run
//! let mem = screeps::memory::root();
//! let creep_time = mem.path_i32("creeps.John.time").unwrap();
//! ```
//!
//! # Other methods that provide `MemoryReference`s
//! In addition to accessing the memory from the root, it is possible to
//! access the memory via creeps, spawns, rooms and flags. Accessing the memory
//! from those objects will also result in a `MemoryReference` which instead
//! points at the root of this object's memory.
//!
//! [`root`]: crate::memory::root
use std::fmt;
use stdweb::{JsSerialize, Reference, Value};
use crate::{
traits::{TryFrom, TryInto},
ConversionError,
};
#[derive(Clone, Debug)]
pub struct UnexpectedTypeError;
impl fmt::Display for UnexpectedTypeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: include &'static str references to the type names in this error...
write!(f, "expected one memory type, found another")
}
}
// TODO: do we even need this over just a raw 'Reference'?
/// A [`Reference`] to a screeps memory object
///
/// [`Reference`]: stdweb::Reference
pub struct MemoryReference(Reference);
impl AsRef<Reference> for MemoryReference {
fn as_ref(&self) -> &Reference {
&self.0
}
}
impl Default for MemoryReference {
fn default() -> Self {
Self::new()
}
}
impl MemoryReference {
pub fn new() -> Self {
js_unwrap!({})
}
/// Creates a MemoryReference from some JavaScript reference.
///
/// Warning: `MemoryReference` is only designed to work with "plain"
/// JavaScript objects, and passing an array or a non-plain object
/// into this method probably won't be what you want. `MemoryReference`
/// also gives access to all properties, so if this is indeed a plain
/// object, all of its values should also be plain objects.
///
/// Passing a non-plain-object reference into this function won't
/// invoke undefined behavior in and of itself, but other functions
/// can rely on `MemoryReference` being "plain".
pub unsafe fn from_reference_unchecked(reference: Reference) -> Self {
MemoryReference(reference)
}
pub fn bool(&self, key: &str) -> bool {
js_unwrap!(Boolean(@{self.as_ref()}[@{key}]))
}
pub fn path_bool(&self, path: &str) -> bool {
js_unwrap!(Boolean(_.get(@{self.as_ref()}, @{path})))
}
pub fn f64(&self, key: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_f64(&self, path: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn i32(&self, key: &str) -> Result<Option<i32>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_i32(&self, path: &str) -> Result<Option<i32>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn string(&self, key: &str) -> Result<Option<String>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_string(&self, path: &str) -> Result<Option<String>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn dict(&self, key: &str) -> Result<Option<MemoryReference>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_dict(&self, path: &str) -> Result<Option<MemoryReference>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
/// Get a dictionary value or create it if it does not exist.
///
/// If the value exists but is a different type, this will return `None`.
pub fn dict_or_create(&self, key: &str) -> Result<MemoryReference, UnexpectedTypeError> {
(js! {
var map = (@{self.as_ref()});
var key = (@{key});
var value = map[key];
if (value === null || value === undefined) {
map[key] = value = {};
}
if ((typeof value) == "object" &&!_.isArray(value)) {
return value;
} else {
return null;
}
})
.try_into()
.map_err(|_| UnexpectedTypeError)
.map(MemoryReference)
}
pub fn keys(&self) -> Vec<String> {
js_unwrap!(Object.keys(@{self.as_ref()}))
}
pub fn del(&self, key: &str) {
js! { @(no_return)
(@{self.as_ref()})[@{key}] = undefined;
}
}
pub fn path_del(&self, path: &str) {
js! {
_.set(@{self.as_ref()}, @{path}, undefined);
}
}
/// Gets a custom type. Will return `None` if `null` or `undefined`, and
/// `Err` if incorrect type.
///
/// # Example
///
/// ```no_run
/// use log::info;
/// use screeps::{prelude::*, Position};
///
/// let creep = screeps::game::creeps::get("mycreepname").unwrap();
/// let mem = creep.memory();
/// let pos = mem.get::<Position>("saved_pos").unwrap();
/// let pos = match pos {
/// Some(pos) => {
/// info!("found position: {}", pos);
/// pos
/// }
/// None => {
/// info!("no position. saving new one!");
/// let pos = creep.pos();
/// mem.set("saved_pos", pos);
/// pos
/// }
/// };
/// info!("final position: {}", pos);
/// creep.move_to(&pos);
/// ```
pub fn get<T>(&self, key: &str) -> Result<Option<T>, <T as TryFrom<Value>>::Error>
where
T: TryFrom<Value>,
{
let val = js! {
return (@{self.as_ref()})[@{key}];
};
if val == Value::Null || val == Value::Undefined {
Ok(None)
} else {
Some(val.try_into()).transpose()
}
}
/// Gets a custom type at a memory path. Will return `None` if `null` or
/// `undefined`, and `Err` if incorrect type.
///
/// Uses lodash in JavaScript to evaluate the path. See https://lodash.com/docs/#get.
pub fn get_path<T>(&self, path: &str) -> Result<Option<T>, <T as TryFrom<Value>>::Error>
where
T: TryFrom<Value>,
{
let val = js! {
return _.get(@{self.as_ref()}, @{path});
};
if val == Value::Null || val == Value::Undefined | else {
Some(val.try_into()).transpose()
}
}
pub fn set<T>(&self, key: &str, value: T)
where
T: JsSerialize,
{
js! { @(no_return)
(@{self.as_ref()})[@{key}] = @{value};
}
}
pub fn path_set<T>(&self, path: &str, value: T)
where
T: JsSerialize,
{
js! { @(no_return)
_.set(@{self.as_ref()}, @{path}, @{value});
}
}
pub fn arr<T>(&self, key: &str) -> Result<Option<Vec<T>>, ConversionError>
where
T: TryFrom<Value, Error = ConversionError>,
{
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_arr<T>(&self, path: &str) -> Result<Option<Vec<T>>, ConversionError>
where
T: TryFrom<Value, Error = ConversionError>,
{
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
}
impl TryFrom<Value> for MemoryReference {
type Error = ConversionError;
fn try_from(v: Value) -> Result<Self, Self::Error> {
let r: Reference = v.try_into()?; // fail early.
Ok(MemoryReference(
(js! {
var v = (@{r});
if (_.isArray(v)) {
return null;
} else {
return v;
}
})
.try_into()?,
))
}
}
/// Get a reference to the `Memory` global object
pub fn root() -> MemoryReference {
js_unwrap!(Memory)
}
| {
Ok(None)
} | conditional_block |
memory.rs | //! Interface with Screeps' `Memory` global variable
//!
//! Screeps' memory lives in the javascript `Memory` global variable and is
//! encoded as a javascript object. This object's reference is tracked within
//! rust as a `MemoryReference`. The [`root`] function gives access to a
//! reference to the `Memory` global object.
//!
//! # Typing
//! Contrary to accessing the memory in javascript, rust's strong type system,
//! requires that read values be assigned a type. To facilitate this, the
//! `MemoryReference` provides methods to read a part of the memory as a
//! certain type. If the value read cannot be transformed to the requested
//! type, the method return `None`.
//!
//! # Accessing the memory
//! Memory can be accessed in two ways:
//! - via _keys_
//! - via _paths_ (methods prefixed with `path_`)
//!
//! In both cases, if the value requested is `undefined`, `null`, or even just
//! of the wrong type, the method returns `None`.
//!
//! ## Accessing memory with a _key_
//! Since a `MemoryReference` represents a javascript object, its children can
//! be accessed using the `object["key"]` javascript syntax using type methods.
//! ```no_run
//! let mem = screeps::memory::root();
//! let cpu_used_last_tick = mem.i32("cpu_used_last_tick").unwrap();
//! ```
//!
//! ## Accessing memory with a _path_
//! A quality of life improvement upon the key access is through full path. In
//! javascript, it is possible to query a value with a full path:
//! ```javascript
//! var creep_time = Memory.creeps.John.time;
//! ```
//!
//! To emulate this behavior in rust, you can write such a path to a string and
//! it will fetch the javascript object using
//! [lodash](https://lodash.com/docs/4.17.10#get) and convert the result
//! depending on the method used. For example,
//! ```no_run
//! let mem = screeps::memory::root();
//! let creep_time = mem.path_i32("creeps.John.time").unwrap();
//! ```
//!
//! # Other methods that provide `MemoryReference`s
//! In addition to accessing the memory from the root, it is possible to
//! access the memory via creeps, spawns, rooms and flags. Accessing the memory
//! from those objects will also result in a `MemoryReference` which instead
//! points at the root of this object's memory.
//!
//! [`root`]: crate::memory::root
use std::fmt;
use stdweb::{JsSerialize, Reference, Value};
use crate::{
traits::{TryFrom, TryInto},
ConversionError,
};
#[derive(Clone, Debug)]
pub struct UnexpectedTypeError;
impl fmt::Display for UnexpectedTypeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: include &'static str references to the type names in this error...
write!(f, "expected one memory type, found another")
}
}
// TODO: do we even need this over just a raw 'Reference'?
/// A [`Reference`] to a screeps memory object
///
/// [`Reference`]: stdweb::Reference
pub struct MemoryReference(Reference);
impl AsRef<Reference> for MemoryReference {
fn as_ref(&self) -> &Reference {
&self.0
}
}
impl Default for MemoryReference {
fn default() -> Self {
Self::new()
}
}
impl MemoryReference {
pub fn new() -> Self {
js_unwrap!({})
}
/// Creates a MemoryReference from some JavaScript reference.
///
/// Warning: `MemoryReference` is only designed to work with "plain"
/// JavaScript objects, and passing an array or a non-plain object
/// into this method probably won't be what you want. `MemoryReference`
/// also gives access to all properties, so if this is indeed a plain
/// object, all of its values should also be plain objects.
///
/// Passing a non-plain-object reference into this function won't
/// invoke undefined behavior in and of itself, but other functions
/// can rely on `MemoryReference` being "plain".
pub unsafe fn from_reference_unchecked(reference: Reference) -> Self {
MemoryReference(reference)
}
pub fn bool(&self, key: &str) -> bool {
js_unwrap!(Boolean(@{self.as_ref()}[@{key}]))
}
pub fn path_bool(&self, path: &str) -> bool {
js_unwrap!(Boolean(_.get(@{self.as_ref()}, @{path})))
}
pub fn | (&self, key: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_f64(&self, path: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn i32(&self, key: &str) -> Result<Option<i32>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_i32(&self, path: &str) -> Result<Option<i32>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn string(&self, key: &str) -> Result<Option<String>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_string(&self, path: &str) -> Result<Option<String>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn dict(&self, key: &str) -> Result<Option<MemoryReference>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_dict(&self, path: &str) -> Result<Option<MemoryReference>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
/// Get a dictionary value or create it if it does not exist.
///
/// If the value exists but is a different type, this will return `None`.
pub fn dict_or_create(&self, key: &str) -> Result<MemoryReference, UnexpectedTypeError> {
(js! {
var map = (@{self.as_ref()});
var key = (@{key});
var value = map[key];
if (value === null || value === undefined) {
map[key] = value = {};
}
if ((typeof value) == "object" &&!_.isArray(value)) {
return value;
} else {
return null;
}
})
.try_into()
.map_err(|_| UnexpectedTypeError)
.map(MemoryReference)
}
pub fn keys(&self) -> Vec<String> {
js_unwrap!(Object.keys(@{self.as_ref()}))
}
pub fn del(&self, key: &str) {
js! { @(no_return)
(@{self.as_ref()})[@{key}] = undefined;
}
}
pub fn path_del(&self, path: &str) {
js! {
_.set(@{self.as_ref()}, @{path}, undefined);
}
}
/// Gets a custom type. Will return `None` if `null` or `undefined`, and
/// `Err` if incorrect type.
///
/// # Example
///
/// ```no_run
/// use log::info;
/// use screeps::{prelude::*, Position};
///
/// let creep = screeps::game::creeps::get("mycreepname").unwrap();
/// let mem = creep.memory();
/// let pos = mem.get::<Position>("saved_pos").unwrap();
/// let pos = match pos {
/// Some(pos) => {
/// info!("found position: {}", pos);
/// pos
/// }
/// None => {
/// info!("no position. saving new one!");
/// let pos = creep.pos();
/// mem.set("saved_pos", pos);
/// pos
/// }
/// };
/// info!("final position: {}", pos);
/// creep.move_to(&pos);
/// ```
pub fn get<T>(&self, key: &str) -> Result<Option<T>, <T as TryFrom<Value>>::Error>
where
T: TryFrom<Value>,
{
let val = js! {
return (@{self.as_ref()})[@{key}];
};
if val == Value::Null || val == Value::Undefined {
Ok(None)
} else {
Some(val.try_into()).transpose()
}
}
/// Gets a custom type at a memory path. Will return `None` if `null` or
/// `undefined`, and `Err` if incorrect type.
///
/// Uses lodash in JavaScript to evaluate the path. See https://lodash.com/docs/#get.
pub fn get_path<T>(&self, path: &str) -> Result<Option<T>, <T as TryFrom<Value>>::Error>
where
T: TryFrom<Value>,
{
let val = js! {
return _.get(@{self.as_ref()}, @{path});
};
if val == Value::Null || val == Value::Undefined {
Ok(None)
} else {
Some(val.try_into()).transpose()
}
}
pub fn set<T>(&self, key: &str, value: T)
where
T: JsSerialize,
{
js! { @(no_return)
(@{self.as_ref()})[@{key}] = @{value};
}
}
pub fn path_set<T>(&self, path: &str, value: T)
where
T: JsSerialize,
{
js! { @(no_return)
_.set(@{self.as_ref()}, @{path}, @{value});
}
}
pub fn arr<T>(&self, key: &str) -> Result<Option<Vec<T>>, ConversionError>
where
T: TryFrom<Value, Error = ConversionError>,
{
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_arr<T>(&self, path: &str) -> Result<Option<Vec<T>>, ConversionError>
where
T: TryFrom<Value, Error = ConversionError>,
{
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
}
impl TryFrom<Value> for MemoryReference {
type Error = ConversionError;
fn try_from(v: Value) -> Result<Self, Self::Error> {
let r: Reference = v.try_into()?; // fail early.
Ok(MemoryReference(
(js! {
var v = (@{r});
if (_.isArray(v)) {
return null;
} else {
return v;
}
})
.try_into()?,
))
}
}
/// Get a reference to the `Memory` global object
pub fn root() -> MemoryReference {
js_unwrap!(Memory)
}
| f64 | identifier_name |
memory.rs | //! Interface with Screeps' `Memory` global variable
//!
//! Screeps' memory lives in the javascript `Memory` global variable and is
//! encoded as a javascript object. This object's reference is tracked within
//! rust as a `MemoryReference`. The [`root`] function gives access to a
//! reference to the `Memory` global object.
//!
//! # Typing
//! Contrary to accessing the memory in javascript, rust's strong type system,
//! requires that read values be assigned a type. To facilitate this, the
//! `MemoryReference` provides methods to read a part of the memory as a
//! certain type. If the value read cannot be transformed to the requested
//! type, the method return `None`.
//!
//! # Accessing the memory
//! Memory can be accessed in two ways:
//! - via _keys_
//! - via _paths_ (methods prefixed with `path_`)
//!
//! In both cases, if the value requested is `undefined`, `null`, or even just
//! of the wrong type, the method returns `None`.
//!
//! ## Accessing memory with a _key_
//! Since a `MemoryReference` represents a javascript object, its children can
//! be accessed using the `object["key"]` javascript syntax using type methods.
//! ```no_run
//! let mem = screeps::memory::root();
//! let cpu_used_last_tick = mem.i32("cpu_used_last_tick").unwrap();
//! ```
//!
//! ## Accessing memory with a _path_
//! A quality of life improvement upon the key access is through full path. In
//! javascript, it is possible to query a value with a full path:
//! ```javascript
//! var creep_time = Memory.creeps.John.time;
//! ```
//!
//! To emulate this behavior in rust, you can write such a path to a string and
//! it will fetch the javascript object using
//! [lodash](https://lodash.com/docs/4.17.10#get) and convert the result
//! depending on the method used. For example,
//! ```no_run
//! let mem = screeps::memory::root();
//! let creep_time = mem.path_i32("creeps.John.time").unwrap();
//! ```
//!
//! # Other methods that provide `MemoryReference`s
//! In addition to accessing the memory from the root, it is possible to
//! access the memory via creeps, spawns, rooms and flags. Accessing the memory
//! from those objects will also result in a `MemoryReference` which instead
//! points at the root of this object's memory.
//!
//! [`root`]: crate::memory::root
use std::fmt;
use stdweb::{JsSerialize, Reference, Value};
use crate::{
traits::{TryFrom, TryInto},
ConversionError,
};
#[derive(Clone, Debug)]
pub struct UnexpectedTypeError;
impl fmt::Display for UnexpectedTypeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: include &'static str references to the type names in this error...
write!(f, "expected one memory type, found another")
}
}
// TODO: do we even need this over just a raw 'Reference'?
/// A [`Reference`] to a screeps memory object
///
/// [`Reference`]: stdweb::Reference
pub struct MemoryReference(Reference);
impl AsRef<Reference> for MemoryReference {
fn as_ref(&self) -> &Reference {
&self.0
}
}
impl Default for MemoryReference {
fn default() -> Self {
Self::new()
}
}
impl MemoryReference {
pub fn new() -> Self {
js_unwrap!({})
}
/// Creates a MemoryReference from some JavaScript reference.
///
/// Warning: `MemoryReference` is only designed to work with "plain"
/// JavaScript objects, and passing an array or a non-plain object
/// into this method probably won't be what you want. `MemoryReference`
/// also gives access to all properties, so if this is indeed a plain
/// object, all of its values should also be plain objects.
///
/// Passing a non-plain-object reference into this function won't
/// invoke undefined behavior in and of itself, but other functions
/// can rely on `MemoryReference` being "plain".
pub unsafe fn from_reference_unchecked(reference: Reference) -> Self {
MemoryReference(reference)
}
pub fn bool(&self, key: &str) -> bool {
js_unwrap!(Boolean(@{self.as_ref()}[@{key}]))
}
pub fn path_bool(&self, path: &str) -> bool {
js_unwrap!(Boolean(_.get(@{self.as_ref()}, @{path})))
}
pub fn f64(&self, key: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_f64(&self, path: &str) -> Result<Option<f64>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn i32(&self, key: &str) -> Result<Option<i32>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_i32(&self, path: &str) -> Result<Option<i32>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn string(&self, key: &str) -> Result<Option<String>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_string(&self, path: &str) -> Result<Option<String>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
pub fn dict(&self, key: &str) -> Result<Option<MemoryReference>, ConversionError> {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
}
pub fn path_dict(&self, path: &str) -> Result<Option<MemoryReference>, ConversionError> {
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
/// Get a dictionary value or create it if it does not exist.
///
/// If the value exists but is a different type, this will return `None`.
pub fn dict_or_create(&self, key: &str) -> Result<MemoryReference, UnexpectedTypeError> {
(js! {
var map = (@{self.as_ref()});
var key = (@{key});
var value = map[key];
if (value === null || value === undefined) {
map[key] = value = {};
}
if ((typeof value) == "object" &&!_.isArray(value)) {
return value;
} else {
return null;
}
})
.try_into()
.map_err(|_| UnexpectedTypeError)
.map(MemoryReference)
}
pub fn keys(&self) -> Vec<String> {
js_unwrap!(Object.keys(@{self.as_ref()}))
}
pub fn del(&self, key: &str) {
js! { @(no_return)
(@{self.as_ref()})[@{key}] = undefined;
}
}
pub fn path_del(&self, path: &str) {
js! {
_.set(@{self.as_ref()}, @{path}, undefined);
}
}
/// Gets a custom type. Will return `None` if `null` or `undefined`, and
/// `Err` if incorrect type.
///
/// # Example
///
/// ```no_run
/// use log::info;
/// use screeps::{prelude::*, Position};
///
/// let creep = screeps::game::creeps::get("mycreepname").unwrap();
/// let mem = creep.memory();
/// let pos = mem.get::<Position>("saved_pos").unwrap();
/// let pos = match pos {
/// Some(pos) => {
/// info!("found position: {}", pos);
/// pos
/// }
/// None => {
/// info!("no position. saving new one!");
/// let pos = creep.pos();
/// mem.set("saved_pos", pos);
/// pos
/// }
/// };
/// info!("final position: {}", pos);
/// creep.move_to(&pos);
/// ```
pub fn get<T>(&self, key: &str) -> Result<Option<T>, <T as TryFrom<Value>>::Error>
where
T: TryFrom<Value>,
{
let val = js! {
return (@{self.as_ref()})[@{key}];
};
if val == Value::Null || val == Value::Undefined {
Ok(None)
} else {
Some(val.try_into()).transpose()
}
}
/// Gets a custom type at a memory path. Will return `None` if `null` or
/// `undefined`, and `Err` if incorrect type.
///
/// Uses lodash in JavaScript to evaluate the path. See https://lodash.com/docs/#get.
pub fn get_path<T>(&self, path: &str) -> Result<Option<T>, <T as TryFrom<Value>>::Error>
where
T: TryFrom<Value>,
{
let val = js! {
return _.get(@{self.as_ref()}, @{path});
};
if val == Value::Null || val == Value::Undefined {
Ok(None)
} else {
Some(val.try_into()).transpose()
}
}
pub fn set<T>(&self, key: &str, value: T)
where
T: JsSerialize,
{
js! { @(no_return)
(@{self.as_ref()})[@{key}] = @{value};
}
}
pub fn path_set<T>(&self, path: &str, value: T)
where
T: JsSerialize,
{
js! { @(no_return)
_.set(@{self.as_ref()}, @{path}, @{value});
}
}
pub fn arr<T>(&self, key: &str) -> Result<Option<Vec<T>>, ConversionError>
where
T: TryFrom<Value, Error = ConversionError>,
|
pub fn path_arr<T>(&self, path: &str) -> Result<Option<Vec<T>>, ConversionError>
where
T: TryFrom<Value, Error = ConversionError>,
{
(js! {
return _.get(@{self.as_ref()}, @{path});
})
.try_into()
}
}
impl TryFrom<Value> for MemoryReference {
type Error = ConversionError;
fn try_from(v: Value) -> Result<Self, Self::Error> {
let r: Reference = v.try_into()?; // fail early.
Ok(MemoryReference(
(js! {
var v = (@{r});
if (_.isArray(v)) {
return null;
} else {
return v;
}
})
.try_into()?,
))
}
}
/// Get a reference to the `Memory` global object
pub fn root() -> MemoryReference {
js_unwrap!(Memory)
}
| {
(js! {
return (@{self.as_ref()})[@{key}];
})
.try_into()
} | identifier_body |
rsa-fdh-vrf.rs | // This crate implements RSA-FDH-VRF based on section 4 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
// The ciphersuite is RSA-FDH-VRF-SHA256, suite string can be changed if other hash function is desired
// The step comments refer to the corresponding steps in the IETF pseudocode for comparison with hacspec
use hacspec_lib::*;
use hacspec_sha256::*;
use hacspec_rsa_pkcs1::*;
bytes!(IntByte, 1);
#[rustfmt::skip]
const ONE: IntByte = IntByte(secret_array!(U8, [0x01u8]));
#[rustfmt::skip]
const TWO: IntByte = IntByte(secret_array!(U8, [0x02u8]));
const SUITE_STRING: IntByte = ONE;
// Helper function used by prove and verify to compute mgf1 of alpha
// mgf_salt currently part of cipher suite, could be optional input
fn vrf_mgf1(n: RSAInt, alpha: &ByteSeq) -> ByteSeqResult {
let mgf_salt1 = i2osp(RSAInt::from_literal(BYTE_SIZE as u128), 4u32)?;
let mgf_salt2 = i2osp(n, BYTE_SIZE)?;
let mgf_salt = mgf_salt1.concat(&mgf_salt2);
let mgf_string = SUITE_STRING
.concat(&ONE)
.concat(&mgf_salt)
.concat(alpha);
let mgf = mgf1(&mgf_string, BYTE_SIZE as usize - 1usize)?;
ByteSeqResult::Ok(mgf)
}
// Based on section 4.1 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn prove(sk: SK, alpha: &ByteSeq) -> ByteSeqResult {
let (n, _d) = sk.clone();
// STEP 1 and 2
let em = vrf_mgf1(n, alpha)?;
// STEP 3
let m = os2ip(&em);
// STEP 4
let s = rsasp1(sk, m)?;
// STEP 5 and 6
i2osp(s, BYTE_SIZE) | // STEP 1 and 2
let hash_string = SUITE_STRING.concat(&TWO.concat(pi_string));
// STEP 3
ByteSeqResult::Ok(sha256(&hash_string).slice(0,32))
}
// Based on section 4.3 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn verify(pk: PK, alpha: &ByteSeq, pi_string: &ByteSeq) -> ByteSeqResult {
let (n, _e) = pk.clone();
// STEP 1
let s = os2ip(pi_string);
// STEP 2
let m = rsavp1(pk, s)?;
// STEP 3 and 4
let em_prime = vrf_mgf1(n, alpha)?;
// STEP 5
let m_prime = os2ip(&em_prime);
// STEP 6
if m == m_prime {
proof_to_hash(pi_string)
} else {
ByteSeqResult::Err(Error::VerificationFailed)
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_bigint::{BigInt,Sign};
use glass_pumpkin::prime;
use quickcheck::*;
// RSA key generation
// Taken from https://asecuritysite.com/rust/rsa01/
fn modinv(a0: BigInt, m0: BigInt) -> BigInt {
if m0 == one() { return one() }
let (mut a, mut m, mut x0, mut inv) =
(a0, m0.clone(), zero(), one());
while a > one() {
inv -= (&a / &m) * &x0;
a = &a % &m;
std::mem::swap(&mut a, &mut m);
std::mem::swap(&mut x0, &mut inv)
}
if inv < zero() { inv += m0 }
inv
}
fn rsa_key_gen() -> Keyp {
let p = BigInt::from_biguint(Sign::Plus,
prime::new((BIT_SIZE / 2) as usize).unwrap());
let q = BigInt::from_biguint(Sign::Plus,
prime::new((BIT_SIZE / 2) as usize).unwrap());
let n = RSAInt::from(p.clone()* q.clone());
let e = BigInt::parse_bytes(b"65537", 10).unwrap();
let totient = (p - BigInt::one()) * (q - BigInt::one());
let d = modinv(e.clone(), totient.clone());
Keyp { n, d: RSAInt::from(d), e: RSAInt::from(e) }
}
// quickcheck generation
#[derive(Clone, Copy, Debug)]
struct Keyp {n: RSAInt, d: RSAInt, e: RSAInt}
#[derive(Clone, Copy, Debug)]
struct Wrapper(RSAInt);
impl Arbitrary for Wrapper {
fn arbitrary(g: &mut Gen) -> Wrapper {
const NUM_BYTES: u32 = 127;
let mut a: [u8; NUM_BYTES as usize] = [0; NUM_BYTES as usize];
for i in 0..NUM_BYTES as usize {
a[i] = u8::arbitrary(g);
}
Wrapper(RSAInt::from_byte_seq_be(&Seq::<U8>::from_public_slice(&a)))
}
}
impl Arbitrary for Keyp {
fn arbitrary(_g: &mut Gen) -> Keyp {
rsa_key_gen()
}
}
// quickcheck tests
const NUM_TESTS: u64 = 5;
#[test]
fn test_rsafdhvrf() {
fn rsafdhvrf(kp: Keyp, alpha: Wrapper) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &alpha).unwrap();
let beta = proof_to_hash(&pi).unwrap();
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
beta_prime == beta
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(rsafdhvrf as fn(Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_rsafdhvrf() {
fn neg_rsafdhvrf(kp: Keyp, fake: Keyp, alpha: Wrapper) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &alpha).unwrap();
match verify((fake.n, fake.e), &alpha, &pi) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Error::VerificationFailed
| Error::MessageTooLarge),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_rsafdhvrf as fn(Keyp, Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_alpha_rsafdhvrf() {
fn neg_alpha_rsafdhvrf(
kp: Keyp, alpha: Wrapper, fake_alpha: Wrapper
) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let fake_alpha = i2osp(fake_alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &fake_alpha).unwrap();
match verify((kp.n, kp.e), &alpha, &pi) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Error::VerificationFailed
| Error::MessageTooLarge),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_alpha_rsafdhvrf as
fn(Keyp, Wrapper, Wrapper) -> bool);
}
// Test vector generation
// Strings should be given in hexadecimal
fn generate_test_vector(
alpha: &str, kp: Keyp
) -> Result<(String, String), Error> {
let alpha = ByteSeq::from_hex(&alpha);
let pi = prove((kp.n, kp.d), &alpha).unwrap();
let beta = proof_to_hash(&pi).unwrap();
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
let n = i2osp(kp.n, BYTE_SIZE)?;
let d = i2osp(kp.d, BYTE_SIZE)?;
let e = i2osp(kp.e, BYTE_SIZE)?;
println!("n:\n{}", ByteSeq::to_hex(&n));
println!("d:\n{}", ByteSeq::to_hex(&d));
println!("e:\n{}", ByteSeq::to_hex(&e));
println!("alpha:\n{}", ByteSeq::to_hex(&alpha));
println!("pi:\n{}", ByteSeq::to_hex(&pi));
println!("beta:\n{}", ByteSeq::to_hex(&beta));
Result::Ok((ByteSeq::to_hex(&pi), ByteSeq::to_hex(&beta)))
}
// Run with cargo test test_vector -- --ignored --nocapture in this crate
#[test]
#[ignore]
fn test_vector() {
// Pass alpha in hexadecimal
let kp = rsa_key_gen();
// let kp = get_test_key();
assert!(!generate_test_vector("af82", kp).is_err());
}
fn get_test_key() -> Keyp {
let n = RSAInt::from_hex("64f70acdc41c0ee7cb4961760368e34889c058ad3c7e578e8e72ed0d2fd1c7cfbb8beffd107204d544919db9d2470669c969e178d4deb8393daec4584ca9f162805c9ba46e617d89d4ab6480b0873b1cb92cf7232c88f013931ffe30f8ddf2cddbff4402bcb721985d2bb2eee5382dd09210b5d1da6b6b8207fe3e526de54efb55b56cd52d97cd77df6315569d5b59823c85ad99c57ad2959ec7d12cdf0c3e66cc57eaa1e644da9b0ca69b0df43945b0bd88ac66903ec98fe0e770b683ca7a332e69cba9229115a5295273aeeb4af2662063a312cbb4b871323f71888fd39557a5f4610ea7a590b021d43e5a89b69de68c728ce147f2743e0b97a5b3eb0d6ab1");
let d = RSAInt::from_hex("39134e9033a488e8900ad3859b37d804519ae2864c04400ade8c2965a2fabc31ba9bc8f70e2ce67e895ca8053bd1dad6427e106ff626518e4a4859c670d0411ca5e3b438a80d84a23e0f05a99a2158514c7d16d8537cb5fadad8e3215c0e5c0bf3a9c210aa0dfc77dd73ae9b4e090c1d33f52e538b5dde508ba43626f2e906546773ba7401aa6b68ab1151da528336ddafc9a6f2995d89ec282bc555fe41e776216576c0aafb66ef00b718e6c62afd51faf82e7b5a1d430591465b2188fa286ce778eb6a1b346b58331c7820b4142fb808e59ec910aa9b6d340dea673ae7be2d9e1fa91494e40372bcfb92da5fe236dc93b30b0a59b20af8edf3a10e3ea6dfe1");
let e = RSAInt::from_hex("010001");
Keyp {n, d, e}
}
// Note that the test vectors have been generated using this code
#[test]
fn test_empty() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("");
let pi = ByteSeq::from_hex("406581e350c601d6d7518ac928f6753929c56a7480a4a3d011ed65e5f61ca033accd45c03cac2dddcd61b909cedd0df517a1bba4705c9d04a2a8c7d735d24bc3e59b263cc8c18d5f6e2712747d809df7868ac720f90ffd3d7c7b78f3d75f14a9755ea8138804806f4739429d1a313b3abaaf89ce97fbdf10bc01d66723b0b38ad5dc51c87e5f852e2c8fc923cf0f9c86bb7bf8ae808532fcb8a981338d5b13278e66e19915e41c6fbd09f1fce3300da422fbf46f706d1c79f298c740926e14069f83dae52a25bad684e420ad5fc8af3b02e0cf3f79782fb6e7e65abe5e1f6b4fe41f20339b2986fe39f7ce4ceb9c2490d5229e9bfda93150d6800880c411daae");
let beta = ByteSeq::from_hex("d065ca3be8716236e99f64139adf481090f0a0c839f86ffda3c4fad948166af0");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
#[test]
fn test_72() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("72");
let pi = ByteSeq::from_hex("3d396dc417bee1975ff63c4e8b43b9417be03a91d5eb47309790d74100271342d6dc11511333ec4bc42aea3e02640dc870665044e85085c3dea43eedeb266d9b2de3824aca18b8de3e4d198bde808d80a2a10f0f4bd73fbc7cc36da44cb68af3161b2264e737dcd2d669252abb29f275c971ff6b8234876b7d1ff3d4d05197fe563d6ae92685dccbbbb689b4837da42fe47433019d9bfc50001b11708bf9f656532febf674119c0d67e27714195722fd977e0fc35d7325b5fb3ecb54df53986e01a809d0e5ec442fdacc3d271e7ab5480b8eb18f25cd3baf6a47abc6bf027e8dedef911f2bec367fa5d65e106f314b64cc1d9534d4f26fa034035a43852be66a");
let beta = ByteSeq::from_hex("a229210b84f0bb43b296075f226dee433cf2727cd6c2e4871afdeb77414f6a47");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
#[test]
fn test_af82() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("af82");
let pi = ByteSeq::from_hex("57b07056abc6851330b21ae890fd43ea53b4435319748cf8dba82148ee381c11d21a8660a8714aa59abaac2b7d0141ac4e85b1113b144328eb11461a7f26086896036fc49579a58a2516cecd274946f8dd82fef31652dfe2e2b495966cd6193a1bd197ef6e3472f30bfe14827dd968ea3bf8310dc002a765a0d54b12c3c9627309800b74701a3f7d07a02db0a6ca3a639e60726059727313818a6b671bebe18f078713ced33e50acbfd1e661ec89c5e82b8e1e07f6293f45474aa57d084da46a2437932491d92a87b3393bb0ec62254a3eca19e1004756867839671f84f7a2378097f334832f4aa0442fc5f8637fb2220bb3f2dca247927f0d49ae1c1b2e7455");
let beta = ByteSeq::from_hex("ebc5582b6aaf23c424ec1c74e1b8250327c957967fa37566284dac8400e62032");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
} | }
// Based on section 4.2 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn proof_to_hash(pi_string: &ByteSeq) -> ByteSeqResult { | random_line_split |
rsa-fdh-vrf.rs | // This crate implements RSA-FDH-VRF based on section 4 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
// The ciphersuite is RSA-FDH-VRF-SHA256, suite string can be changed if other hash function is desired
// The step comments refer to the corresponding steps in the IETF pseudocode for comparison with hacspec
use hacspec_lib::*;
use hacspec_sha256::*;
use hacspec_rsa_pkcs1::*;
bytes!(IntByte, 1);
#[rustfmt::skip]
const ONE: IntByte = IntByte(secret_array!(U8, [0x01u8]));
#[rustfmt::skip]
const TWO: IntByte = IntByte(secret_array!(U8, [0x02u8]));
const SUITE_STRING: IntByte = ONE;
// Helper function used by prove and verify to compute mgf1 of alpha
// mgf_salt currently part of cipher suite, could be optional input
fn vrf_mgf1(n: RSAInt, alpha: &ByteSeq) -> ByteSeqResult {
let mgf_salt1 = i2osp(RSAInt::from_literal(BYTE_SIZE as u128), 4u32)?;
let mgf_salt2 = i2osp(n, BYTE_SIZE)?;
let mgf_salt = mgf_salt1.concat(&mgf_salt2);
let mgf_string = SUITE_STRING
.concat(&ONE)
.concat(&mgf_salt)
.concat(alpha);
let mgf = mgf1(&mgf_string, BYTE_SIZE as usize - 1usize)?;
ByteSeqResult::Ok(mgf)
}
// Based on section 4.1 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn | (sk: SK, alpha: &ByteSeq) -> ByteSeqResult {
let (n, _d) = sk.clone();
// STEP 1 and 2
let em = vrf_mgf1(n, alpha)?;
// STEP 3
let m = os2ip(&em);
// STEP 4
let s = rsasp1(sk, m)?;
// STEP 5 and 6
i2osp(s, BYTE_SIZE)
}
// Based on section 4.2 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn proof_to_hash(pi_string: &ByteSeq) -> ByteSeqResult {
// STEP 1 and 2
let hash_string = SUITE_STRING.concat(&TWO.concat(pi_string));
// STEP 3
ByteSeqResult::Ok(sha256(&hash_string).slice(0,32))
}
// Based on section 4.3 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn verify(pk: PK, alpha: &ByteSeq, pi_string: &ByteSeq) -> ByteSeqResult {
let (n, _e) = pk.clone();
// STEP 1
let s = os2ip(pi_string);
// STEP 2
let m = rsavp1(pk, s)?;
// STEP 3 and 4
let em_prime = vrf_mgf1(n, alpha)?;
// STEP 5
let m_prime = os2ip(&em_prime);
// STEP 6
if m == m_prime {
proof_to_hash(pi_string)
} else {
ByteSeqResult::Err(Error::VerificationFailed)
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_bigint::{BigInt,Sign};
use glass_pumpkin::prime;
use quickcheck::*;
// RSA key generation
// Taken from https://asecuritysite.com/rust/rsa01/
fn modinv(a0: BigInt, m0: BigInt) -> BigInt {
if m0 == one() { return one() }
let (mut a, mut m, mut x0, mut inv) =
(a0, m0.clone(), zero(), one());
while a > one() {
inv -= (&a / &m) * &x0;
a = &a % &m;
std::mem::swap(&mut a, &mut m);
std::mem::swap(&mut x0, &mut inv)
}
if inv < zero() { inv += m0 }
inv
}
fn rsa_key_gen() -> Keyp {
let p = BigInt::from_biguint(Sign::Plus,
prime::new((BIT_SIZE / 2) as usize).unwrap());
let q = BigInt::from_biguint(Sign::Plus,
prime::new((BIT_SIZE / 2) as usize).unwrap());
let n = RSAInt::from(p.clone()* q.clone());
let e = BigInt::parse_bytes(b"65537", 10).unwrap();
let totient = (p - BigInt::one()) * (q - BigInt::one());
let d = modinv(e.clone(), totient.clone());
Keyp { n, d: RSAInt::from(d), e: RSAInt::from(e) }
}
// quickcheck generation
#[derive(Clone, Copy, Debug)]
struct Keyp {n: RSAInt, d: RSAInt, e: RSAInt}
#[derive(Clone, Copy, Debug)]
struct Wrapper(RSAInt);
impl Arbitrary for Wrapper {
fn arbitrary(g: &mut Gen) -> Wrapper {
const NUM_BYTES: u32 = 127;
let mut a: [u8; NUM_BYTES as usize] = [0; NUM_BYTES as usize];
for i in 0..NUM_BYTES as usize {
a[i] = u8::arbitrary(g);
}
Wrapper(RSAInt::from_byte_seq_be(&Seq::<U8>::from_public_slice(&a)))
}
}
impl Arbitrary for Keyp {
fn arbitrary(_g: &mut Gen) -> Keyp {
rsa_key_gen()
}
}
// quickcheck tests
const NUM_TESTS: u64 = 5;
#[test]
fn test_rsafdhvrf() {
fn rsafdhvrf(kp: Keyp, alpha: Wrapper) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &alpha).unwrap();
let beta = proof_to_hash(&pi).unwrap();
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
beta_prime == beta
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(rsafdhvrf as fn(Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_rsafdhvrf() {
fn neg_rsafdhvrf(kp: Keyp, fake: Keyp, alpha: Wrapper) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &alpha).unwrap();
match verify((fake.n, fake.e), &alpha, &pi) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Error::VerificationFailed
| Error::MessageTooLarge),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_rsafdhvrf as fn(Keyp, Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_alpha_rsafdhvrf() {
fn neg_alpha_rsafdhvrf(
kp: Keyp, alpha: Wrapper, fake_alpha: Wrapper
) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let fake_alpha = i2osp(fake_alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &fake_alpha).unwrap();
match verify((kp.n, kp.e), &alpha, &pi) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Error::VerificationFailed
| Error::MessageTooLarge),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_alpha_rsafdhvrf as
fn(Keyp, Wrapper, Wrapper) -> bool);
}
// Test vector generation
// Strings should be given in hexadecimal
fn generate_test_vector(
alpha: &str, kp: Keyp
) -> Result<(String, String), Error> {
let alpha = ByteSeq::from_hex(&alpha);
let pi = prove((kp.n, kp.d), &alpha).unwrap();
let beta = proof_to_hash(&pi).unwrap();
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
let n = i2osp(kp.n, BYTE_SIZE)?;
let d = i2osp(kp.d, BYTE_SIZE)?;
let e = i2osp(kp.e, BYTE_SIZE)?;
println!("n:\n{}", ByteSeq::to_hex(&n));
println!("d:\n{}", ByteSeq::to_hex(&d));
println!("e:\n{}", ByteSeq::to_hex(&e));
println!("alpha:\n{}", ByteSeq::to_hex(&alpha));
println!("pi:\n{}", ByteSeq::to_hex(&pi));
println!("beta:\n{}", ByteSeq::to_hex(&beta));
Result::Ok((ByteSeq::to_hex(&pi), ByteSeq::to_hex(&beta)))
}
// Run with cargo test test_vector -- --ignored --nocapture in this crate
#[test]
#[ignore]
fn test_vector() {
// Pass alpha in hexadecimal
let kp = rsa_key_gen();
// let kp = get_test_key();
assert!(!generate_test_vector("af82", kp).is_err());
}
fn get_test_key() -> Keyp {
let n = RSAInt::from_hex("64f70acdc41c0ee7cb4961760368e34889c058ad3c7e578e8e72ed0d2fd1c7cfbb8beffd107204d544919db9d2470669c969e178d4deb8393daec4584ca9f162805c9ba46e617d89d4ab6480b0873b1cb92cf7232c88f013931ffe30f8ddf2cddbff4402bcb721985d2bb2eee5382dd09210b5d1da6b6b8207fe3e526de54efb55b56cd52d97cd77df6315569d5b59823c85ad99c57ad2959ec7d12cdf0c3e66cc57eaa1e644da9b0ca69b0df43945b0bd88ac66903ec98fe0e770b683ca7a332e69cba9229115a5295273aeeb4af2662063a312cbb4b871323f71888fd39557a5f4610ea7a590b021d43e5a89b69de68c728ce147f2743e0b97a5b3eb0d6ab1");
let d = RSAInt::from_hex("39134e9033a488e8900ad3859b37d804519ae2864c04400ade8c2965a2fabc31ba9bc8f70e2ce67e895ca8053bd1dad6427e106ff626518e4a4859c670d0411ca5e3b438a80d84a23e0f05a99a2158514c7d16d8537cb5fadad8e3215c0e5c0bf3a9c210aa0dfc77dd73ae9b4e090c1d33f52e538b5dde508ba43626f2e906546773ba7401aa6b68ab1151da528336ddafc9a6f2995d89ec282bc555fe41e776216576c0aafb66ef00b718e6c62afd51faf82e7b5a1d430591465b2188fa286ce778eb6a1b346b58331c7820b4142fb808e59ec910aa9b6d340dea673ae7be2d9e1fa91494e40372bcfb92da5fe236dc93b30b0a59b20af8edf3a10e3ea6dfe1");
let e = RSAInt::from_hex("010001");
Keyp {n, d, e}
}
// Note that the test vectors have been generated using this code
#[test]
fn test_empty() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("");
let pi = ByteSeq::from_hex("406581e350c601d6d7518ac928f6753929c56a7480a4a3d011ed65e5f61ca033accd45c03cac2dddcd61b909cedd0df517a1bba4705c9d04a2a8c7d735d24bc3e59b263cc8c18d5f6e2712747d809df7868ac720f90ffd3d7c7b78f3d75f14a9755ea8138804806f4739429d1a313b3abaaf89ce97fbdf10bc01d66723b0b38ad5dc51c87e5f852e2c8fc923cf0f9c86bb7bf8ae808532fcb8a981338d5b13278e66e19915e41c6fbd09f1fce3300da422fbf46f706d1c79f298c740926e14069f83dae52a25bad684e420ad5fc8af3b02e0cf3f79782fb6e7e65abe5e1f6b4fe41f20339b2986fe39f7ce4ceb9c2490d5229e9bfda93150d6800880c411daae");
let beta = ByteSeq::from_hex("d065ca3be8716236e99f64139adf481090f0a0c839f86ffda3c4fad948166af0");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
#[test]
fn test_72() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("72");
let pi = ByteSeq::from_hex("3d396dc417bee1975ff63c4e8b43b9417be03a91d5eb47309790d74100271342d6dc11511333ec4bc42aea3e02640dc870665044e85085c3dea43eedeb266d9b2de3824aca18b8de3e4d198bde808d80a2a10f0f4bd73fbc7cc36da44cb68af3161b2264e737dcd2d669252abb29f275c971ff6b8234876b7d1ff3d4d05197fe563d6ae92685dccbbbb689b4837da42fe47433019d9bfc50001b11708bf9f656532febf674119c0d67e27714195722fd977e0fc35d7325b5fb3ecb54df53986e01a809d0e5ec442fdacc3d271e7ab5480b8eb18f25cd3baf6a47abc6bf027e8dedef911f2bec367fa5d65e106f314b64cc1d9534d4f26fa034035a43852be66a");
let beta = ByteSeq::from_hex("a229210b84f0bb43b296075f226dee433cf2727cd6c2e4871afdeb77414f6a47");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
#[test]
fn test_af82() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("af82");
let pi = ByteSeq::from_hex("57b07056abc6851330b21ae890fd43ea53b4435319748cf8dba82148ee381c11d21a8660a8714aa59abaac2b7d0141ac4e85b1113b144328eb11461a7f26086896036fc49579a58a2516cecd274946f8dd82fef31652dfe2e2b495966cd6193a1bd197ef6e3472f30bfe14827dd968ea3bf8310dc002a765a0d54b12c3c9627309800b74701a3f7d07a02db0a6ca3a639e60726059727313818a6b671bebe18f078713ced33e50acbfd1e661ec89c5e82b8e1e07f6293f45474aa57d084da46a2437932491d92a87b3393bb0ec62254a3eca19e1004756867839671f84f7a2378097f334832f4aa0442fc5f8637fb2220bb3f2dca247927f0d49ae1c1b2e7455");
let beta = ByteSeq::from_hex("ebc5582b6aaf23c424ec1c74e1b8250327c957967fa37566284dac8400e62032");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
}
| prove | identifier_name |
rsa-fdh-vrf.rs | // This crate implements RSA-FDH-VRF based on section 4 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
// The ciphersuite is RSA-FDH-VRF-SHA256, suite string can be changed if other hash function is desired
// The step comments refer to the corresponding steps in the IETF pseudocode for comparison with hacspec
use hacspec_lib::*;
use hacspec_sha256::*;
use hacspec_rsa_pkcs1::*;
bytes!(IntByte, 1);
#[rustfmt::skip]
const ONE: IntByte = IntByte(secret_array!(U8, [0x01u8]));
#[rustfmt::skip]
const TWO: IntByte = IntByte(secret_array!(U8, [0x02u8]));
const SUITE_STRING: IntByte = ONE;
// Helper function used by prove and verify to compute mgf1 of alpha
// mgf_salt currently part of cipher suite, could be optional input
fn vrf_mgf1(n: RSAInt, alpha: &ByteSeq) -> ByteSeqResult {
let mgf_salt1 = i2osp(RSAInt::from_literal(BYTE_SIZE as u128), 4u32)?;
let mgf_salt2 = i2osp(n, BYTE_SIZE)?;
let mgf_salt = mgf_salt1.concat(&mgf_salt2);
let mgf_string = SUITE_STRING
.concat(&ONE)
.concat(&mgf_salt)
.concat(alpha);
let mgf = mgf1(&mgf_string, BYTE_SIZE as usize - 1usize)?;
ByteSeqResult::Ok(mgf)
}
// Based on section 4.1 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn prove(sk: SK, alpha: &ByteSeq) -> ByteSeqResult {
let (n, _d) = sk.clone();
// STEP 1 and 2
let em = vrf_mgf1(n, alpha)?;
// STEP 3
let m = os2ip(&em);
// STEP 4
let s = rsasp1(sk, m)?;
// STEP 5 and 6
i2osp(s, BYTE_SIZE)
}
// Based on section 4.2 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn proof_to_hash(pi_string: &ByteSeq) -> ByteSeqResult |
// Based on section 4.3 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn verify(pk: PK, alpha: &ByteSeq, pi_string: &ByteSeq) -> ByteSeqResult {
let (n, _e) = pk.clone();
// STEP 1
let s = os2ip(pi_string);
// STEP 2
let m = rsavp1(pk, s)?;
// STEP 3 and 4
let em_prime = vrf_mgf1(n, alpha)?;
// STEP 5
let m_prime = os2ip(&em_prime);
// STEP 6
if m == m_prime {
proof_to_hash(pi_string)
} else {
ByteSeqResult::Err(Error::VerificationFailed)
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_bigint::{BigInt,Sign};
use glass_pumpkin::prime;
use quickcheck::*;
// RSA key generation
// Taken from https://asecuritysite.com/rust/rsa01/
fn modinv(a0: BigInt, m0: BigInt) -> BigInt {
if m0 == one() { return one() }
let (mut a, mut m, mut x0, mut inv) =
(a0, m0.clone(), zero(), one());
while a > one() {
inv -= (&a / &m) * &x0;
a = &a % &m;
std::mem::swap(&mut a, &mut m);
std::mem::swap(&mut x0, &mut inv)
}
if inv < zero() { inv += m0 }
inv
}
fn rsa_key_gen() -> Keyp {
let p = BigInt::from_biguint(Sign::Plus,
prime::new((BIT_SIZE / 2) as usize).unwrap());
let q = BigInt::from_biguint(Sign::Plus,
prime::new((BIT_SIZE / 2) as usize).unwrap());
let n = RSAInt::from(p.clone()* q.clone());
let e = BigInt::parse_bytes(b"65537", 10).unwrap();
let totient = (p - BigInt::one()) * (q - BigInt::one());
let d = modinv(e.clone(), totient.clone());
Keyp { n, d: RSAInt::from(d), e: RSAInt::from(e) }
}
// quickcheck generation
#[derive(Clone, Copy, Debug)]
struct Keyp {n: RSAInt, d: RSAInt, e: RSAInt}
#[derive(Clone, Copy, Debug)]
struct Wrapper(RSAInt);
impl Arbitrary for Wrapper {
fn arbitrary(g: &mut Gen) -> Wrapper {
const NUM_BYTES: u32 = 127;
let mut a: [u8; NUM_BYTES as usize] = [0; NUM_BYTES as usize];
for i in 0..NUM_BYTES as usize {
a[i] = u8::arbitrary(g);
}
Wrapper(RSAInt::from_byte_seq_be(&Seq::<U8>::from_public_slice(&a)))
}
}
impl Arbitrary for Keyp {
fn arbitrary(_g: &mut Gen) -> Keyp {
rsa_key_gen()
}
}
// quickcheck tests
const NUM_TESTS: u64 = 5;
#[test]
fn test_rsafdhvrf() {
fn rsafdhvrf(kp: Keyp, alpha: Wrapper) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &alpha).unwrap();
let beta = proof_to_hash(&pi).unwrap();
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
beta_prime == beta
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(rsafdhvrf as fn(Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_rsafdhvrf() {
fn neg_rsafdhvrf(kp: Keyp, fake: Keyp, alpha: Wrapper) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &alpha).unwrap();
match verify((fake.n, fake.e), &alpha, &pi) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Error::VerificationFailed
| Error::MessageTooLarge),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_rsafdhvrf as fn(Keyp, Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_alpha_rsafdhvrf() {
fn neg_alpha_rsafdhvrf(
kp: Keyp, alpha: Wrapper, fake_alpha: Wrapper
) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let fake_alpha = i2osp(fake_alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &fake_alpha).unwrap();
match verify((kp.n, kp.e), &alpha, &pi) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Error::VerificationFailed
| Error::MessageTooLarge),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_alpha_rsafdhvrf as
fn(Keyp, Wrapper, Wrapper) -> bool);
}
// Test vector generation
// Strings should be given in hexadecimal
fn generate_test_vector(
alpha: &str, kp: Keyp
) -> Result<(String, String), Error> {
let alpha = ByteSeq::from_hex(&alpha);
let pi = prove((kp.n, kp.d), &alpha).unwrap();
let beta = proof_to_hash(&pi).unwrap();
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
let n = i2osp(kp.n, BYTE_SIZE)?;
let d = i2osp(kp.d, BYTE_SIZE)?;
let e = i2osp(kp.e, BYTE_SIZE)?;
println!("n:\n{}", ByteSeq::to_hex(&n));
println!("d:\n{}", ByteSeq::to_hex(&d));
println!("e:\n{}", ByteSeq::to_hex(&e));
println!("alpha:\n{}", ByteSeq::to_hex(&alpha));
println!("pi:\n{}", ByteSeq::to_hex(&pi));
println!("beta:\n{}", ByteSeq::to_hex(&beta));
Result::Ok((ByteSeq::to_hex(&pi), ByteSeq::to_hex(&beta)))
}
// Run with cargo test test_vector -- --ignored --nocapture in this crate
#[test]
#[ignore]
fn test_vector() {
// Pass alpha in hexadecimal
let kp = rsa_key_gen();
// let kp = get_test_key();
assert!(!generate_test_vector("af82", kp).is_err());
}
fn get_test_key() -> Keyp {
let n = RSAInt::from_hex("64f70acdc41c0ee7cb4961760368e34889c058ad3c7e578e8e72ed0d2fd1c7cfbb8beffd107204d544919db9d2470669c969e178d4deb8393daec4584ca9f162805c9ba46e617d89d4ab6480b0873b1cb92cf7232c88f013931ffe30f8ddf2cddbff4402bcb721985d2bb2eee5382dd09210b5d1da6b6b8207fe3e526de54efb55b56cd52d97cd77df6315569d5b59823c85ad99c57ad2959ec7d12cdf0c3e66cc57eaa1e644da9b0ca69b0df43945b0bd88ac66903ec98fe0e770b683ca7a332e69cba9229115a5295273aeeb4af2662063a312cbb4b871323f71888fd39557a5f4610ea7a590b021d43e5a89b69de68c728ce147f2743e0b97a5b3eb0d6ab1");
let d = RSAInt::from_hex("39134e9033a488e8900ad3859b37d804519ae2864c04400ade8c2965a2fabc31ba9bc8f70e2ce67e895ca8053bd1dad6427e106ff626518e4a4859c670d0411ca5e3b438a80d84a23e0f05a99a2158514c7d16d8537cb5fadad8e3215c0e5c0bf3a9c210aa0dfc77dd73ae9b4e090c1d33f52e538b5dde508ba43626f2e906546773ba7401aa6b68ab1151da528336ddafc9a6f2995d89ec282bc555fe41e776216576c0aafb66ef00b718e6c62afd51faf82e7b5a1d430591465b2188fa286ce778eb6a1b346b58331c7820b4142fb808e59ec910aa9b6d340dea673ae7be2d9e1fa91494e40372bcfb92da5fe236dc93b30b0a59b20af8edf3a10e3ea6dfe1");
let e = RSAInt::from_hex("010001");
Keyp {n, d, e}
}
// Note that the test vectors have been generated using this code
#[test]
fn test_empty() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("");
let pi = ByteSeq::from_hex("406581e350c601d6d7518ac928f6753929c56a7480a4a3d011ed65e5f61ca033accd45c03cac2dddcd61b909cedd0df517a1bba4705c9d04a2a8c7d735d24bc3e59b263cc8c18d5f6e2712747d809df7868ac720f90ffd3d7c7b78f3d75f14a9755ea8138804806f4739429d1a313b3abaaf89ce97fbdf10bc01d66723b0b38ad5dc51c87e5f852e2c8fc923cf0f9c86bb7bf8ae808532fcb8a981338d5b13278e66e19915e41c6fbd09f1fce3300da422fbf46f706d1c79f298c740926e14069f83dae52a25bad684e420ad5fc8af3b02e0cf3f79782fb6e7e65abe5e1f6b4fe41f20339b2986fe39f7ce4ceb9c2490d5229e9bfda93150d6800880c411daae");
let beta = ByteSeq::from_hex("d065ca3be8716236e99f64139adf481090f0a0c839f86ffda3c4fad948166af0");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
#[test]
fn test_72() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("72");
let pi = ByteSeq::from_hex("3d396dc417bee1975ff63c4e8b43b9417be03a91d5eb47309790d74100271342d6dc11511333ec4bc42aea3e02640dc870665044e85085c3dea43eedeb266d9b2de3824aca18b8de3e4d198bde808d80a2a10f0f4bd73fbc7cc36da44cb68af3161b2264e737dcd2d669252abb29f275c971ff6b8234876b7d1ff3d4d05197fe563d6ae92685dccbbbb689b4837da42fe47433019d9bfc50001b11708bf9f656532febf674119c0d67e27714195722fd977e0fc35d7325b5fb3ecb54df53986e01a809d0e5ec442fdacc3d271e7ab5480b8eb18f25cd3baf6a47abc6bf027e8dedef911f2bec367fa5d65e106f314b64cc1d9534d4f26fa034035a43852be66a");
let beta = ByteSeq::from_hex("a229210b84f0bb43b296075f226dee433cf2727cd6c2e4871afdeb77414f6a47");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
#[test]
fn test_af82() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("af82");
let pi = ByteSeq::from_hex("57b07056abc6851330b21ae890fd43ea53b4435319748cf8dba82148ee381c11d21a8660a8714aa59abaac2b7d0141ac4e85b1113b144328eb11461a7f26086896036fc49579a58a2516cecd274946f8dd82fef31652dfe2e2b495966cd6193a1bd197ef6e3472f30bfe14827dd968ea3bf8310dc002a765a0d54b12c3c9627309800b74701a3f7d07a02db0a6ca3a639e60726059727313818a6b671bebe18f078713ced33e50acbfd1e661ec89c5e82b8e1e07f6293f45474aa57d084da46a2437932491d92a87b3393bb0ec62254a3eca19e1004756867839671f84f7a2378097f334832f4aa0442fc5f8637fb2220bb3f2dca247927f0d49ae1c1b2e7455");
let beta = ByteSeq::from_hex("ebc5582b6aaf23c424ec1c74e1b8250327c957967fa37566284dac8400e62032");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
}
| {
// STEP 1 and 2
let hash_string = SUITE_STRING.concat(&TWO.concat(pi_string));
// STEP 3
ByteSeqResult::Ok(sha256(&hash_string).slice(0,32))
} | identifier_body |
rsa-fdh-vrf.rs | // This crate implements RSA-FDH-VRF based on section 4 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
// The ciphersuite is RSA-FDH-VRF-SHA256, suite string can be changed if other hash function is desired
// The step comments refer to the corresponding steps in the IETF pseudocode for comparison with hacspec
use hacspec_lib::*;
use hacspec_sha256::*;
use hacspec_rsa_pkcs1::*;
bytes!(IntByte, 1);
#[rustfmt::skip]
const ONE: IntByte = IntByte(secret_array!(U8, [0x01u8]));
#[rustfmt::skip]
const TWO: IntByte = IntByte(secret_array!(U8, [0x02u8]));
const SUITE_STRING: IntByte = ONE;
// Helper function used by prove and verify to compute mgf1 of alpha
// mgf_salt currently part of cipher suite, could be optional input
fn vrf_mgf1(n: RSAInt, alpha: &ByteSeq) -> ByteSeqResult {
let mgf_salt1 = i2osp(RSAInt::from_literal(BYTE_SIZE as u128), 4u32)?;
let mgf_salt2 = i2osp(n, BYTE_SIZE)?;
let mgf_salt = mgf_salt1.concat(&mgf_salt2);
let mgf_string = SUITE_STRING
.concat(&ONE)
.concat(&mgf_salt)
.concat(alpha);
let mgf = mgf1(&mgf_string, BYTE_SIZE as usize - 1usize)?;
ByteSeqResult::Ok(mgf)
}
// Based on section 4.1 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn prove(sk: SK, alpha: &ByteSeq) -> ByteSeqResult {
let (n, _d) = sk.clone();
// STEP 1 and 2
let em = vrf_mgf1(n, alpha)?;
// STEP 3
let m = os2ip(&em);
// STEP 4
let s = rsasp1(sk, m)?;
// STEP 5 and 6
i2osp(s, BYTE_SIZE)
}
// Based on section 4.2 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn proof_to_hash(pi_string: &ByteSeq) -> ByteSeqResult {
// STEP 1 and 2
let hash_string = SUITE_STRING.concat(&TWO.concat(pi_string));
// STEP 3
ByteSeqResult::Ok(sha256(&hash_string).slice(0,32))
}
// Based on section 4.3 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/
pub fn verify(pk: PK, alpha: &ByteSeq, pi_string: &ByteSeq) -> ByteSeqResult {
let (n, _e) = pk.clone();
// STEP 1
let s = os2ip(pi_string);
// STEP 2
let m = rsavp1(pk, s)?;
// STEP 3 and 4
let em_prime = vrf_mgf1(n, alpha)?;
// STEP 5
let m_prime = os2ip(&em_prime);
// STEP 6
if m == m_prime | else {
ByteSeqResult::Err(Error::VerificationFailed)
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_bigint::{BigInt,Sign};
use glass_pumpkin::prime;
use quickcheck::*;
// RSA key generation
// Taken from https://asecuritysite.com/rust/rsa01/
fn modinv(a0: BigInt, m0: BigInt) -> BigInt {
if m0 == one() { return one() }
let (mut a, mut m, mut x0, mut inv) =
(a0, m0.clone(), zero(), one());
while a > one() {
inv -= (&a / &m) * &x0;
a = &a % &m;
std::mem::swap(&mut a, &mut m);
std::mem::swap(&mut x0, &mut inv)
}
if inv < zero() { inv += m0 }
inv
}
fn rsa_key_gen() -> Keyp {
let p = BigInt::from_biguint(Sign::Plus,
prime::new((BIT_SIZE / 2) as usize).unwrap());
let q = BigInt::from_biguint(Sign::Plus,
prime::new((BIT_SIZE / 2) as usize).unwrap());
let n = RSAInt::from(p.clone()* q.clone());
let e = BigInt::parse_bytes(b"65537", 10).unwrap();
let totient = (p - BigInt::one()) * (q - BigInt::one());
let d = modinv(e.clone(), totient.clone());
Keyp { n, d: RSAInt::from(d), e: RSAInt::from(e) }
}
// quickcheck generation
#[derive(Clone, Copy, Debug)]
struct Keyp {n: RSAInt, d: RSAInt, e: RSAInt}
#[derive(Clone, Copy, Debug)]
struct Wrapper(RSAInt);
impl Arbitrary for Wrapper {
fn arbitrary(g: &mut Gen) -> Wrapper {
const NUM_BYTES: u32 = 127;
let mut a: [u8; NUM_BYTES as usize] = [0; NUM_BYTES as usize];
for i in 0..NUM_BYTES as usize {
a[i] = u8::arbitrary(g);
}
Wrapper(RSAInt::from_byte_seq_be(&Seq::<U8>::from_public_slice(&a)))
}
}
impl Arbitrary for Keyp {
fn arbitrary(_g: &mut Gen) -> Keyp {
rsa_key_gen()
}
}
// quickcheck tests
const NUM_TESTS: u64 = 5;
#[test]
fn test_rsafdhvrf() {
fn rsafdhvrf(kp: Keyp, alpha: Wrapper) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &alpha).unwrap();
let beta = proof_to_hash(&pi).unwrap();
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
beta_prime == beta
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(rsafdhvrf as fn(Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_rsafdhvrf() {
fn neg_rsafdhvrf(kp: Keyp, fake: Keyp, alpha: Wrapper) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &alpha).unwrap();
match verify((fake.n, fake.e), &alpha, &pi) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Error::VerificationFailed
| Error::MessageTooLarge),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_rsafdhvrf as fn(Keyp, Keyp, Wrapper) -> bool);
}
#[test]
fn test_neg_alpha_rsafdhvrf() {
fn neg_alpha_rsafdhvrf(
kp: Keyp, alpha: Wrapper, fake_alpha: Wrapper
) -> bool {
let alpha = i2osp(alpha.0, BYTE_SIZE).unwrap();
let fake_alpha = i2osp(fake_alpha.0, BYTE_SIZE).unwrap();
let pi = prove((kp.n, kp.d), &fake_alpha).unwrap();
match verify((kp.n, kp.e), &alpha, &pi) {
Ok(_beta_prime) => false,
Err(e) => matches!(e, Error::VerificationFailed
| Error::MessageTooLarge),
}
}
QuickCheck::new().tests(NUM_TESTS)
.quickcheck(neg_alpha_rsafdhvrf as
fn(Keyp, Wrapper, Wrapper) -> bool);
}
// Test vector generation
// Strings should be given in hexadecimal
fn generate_test_vector(
alpha: &str, kp: Keyp
) -> Result<(String, String), Error> {
let alpha = ByteSeq::from_hex(&alpha);
let pi = prove((kp.n, kp.d), &alpha).unwrap();
let beta = proof_to_hash(&pi).unwrap();
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
let n = i2osp(kp.n, BYTE_SIZE)?;
let d = i2osp(kp.d, BYTE_SIZE)?;
let e = i2osp(kp.e, BYTE_SIZE)?;
println!("n:\n{}", ByteSeq::to_hex(&n));
println!("d:\n{}", ByteSeq::to_hex(&d));
println!("e:\n{}", ByteSeq::to_hex(&e));
println!("alpha:\n{}", ByteSeq::to_hex(&alpha));
println!("pi:\n{}", ByteSeq::to_hex(&pi));
println!("beta:\n{}", ByteSeq::to_hex(&beta));
Result::Ok((ByteSeq::to_hex(&pi), ByteSeq::to_hex(&beta)))
}
// Run with cargo test test_vector -- --ignored --nocapture in this crate
#[test]
#[ignore]
fn test_vector() {
// Pass alpha in hexadecimal
let kp = rsa_key_gen();
// let kp = get_test_key();
assert!(!generate_test_vector("af82", kp).is_err());
}
fn get_test_key() -> Keyp {
let n = RSAInt::from_hex("64f70acdc41c0ee7cb4961760368e34889c058ad3c7e578e8e72ed0d2fd1c7cfbb8beffd107204d544919db9d2470669c969e178d4deb8393daec4584ca9f162805c9ba46e617d89d4ab6480b0873b1cb92cf7232c88f013931ffe30f8ddf2cddbff4402bcb721985d2bb2eee5382dd09210b5d1da6b6b8207fe3e526de54efb55b56cd52d97cd77df6315569d5b59823c85ad99c57ad2959ec7d12cdf0c3e66cc57eaa1e644da9b0ca69b0df43945b0bd88ac66903ec98fe0e770b683ca7a332e69cba9229115a5295273aeeb4af2662063a312cbb4b871323f71888fd39557a5f4610ea7a590b021d43e5a89b69de68c728ce147f2743e0b97a5b3eb0d6ab1");
let d = RSAInt::from_hex("39134e9033a488e8900ad3859b37d804519ae2864c04400ade8c2965a2fabc31ba9bc8f70e2ce67e895ca8053bd1dad6427e106ff626518e4a4859c670d0411ca5e3b438a80d84a23e0f05a99a2158514c7d16d8537cb5fadad8e3215c0e5c0bf3a9c210aa0dfc77dd73ae9b4e090c1d33f52e538b5dde508ba43626f2e906546773ba7401aa6b68ab1151da528336ddafc9a6f2995d89ec282bc555fe41e776216576c0aafb66ef00b718e6c62afd51faf82e7b5a1d430591465b2188fa286ce778eb6a1b346b58331c7820b4142fb808e59ec910aa9b6d340dea673ae7be2d9e1fa91494e40372bcfb92da5fe236dc93b30b0a59b20af8edf3a10e3ea6dfe1");
let e = RSAInt::from_hex("010001");
Keyp {n, d, e}
}
// Note that the test vectors have been generated using this code
#[test]
fn test_empty() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("");
let pi = ByteSeq::from_hex("406581e350c601d6d7518ac928f6753929c56a7480a4a3d011ed65e5f61ca033accd45c03cac2dddcd61b909cedd0df517a1bba4705c9d04a2a8c7d735d24bc3e59b263cc8c18d5f6e2712747d809df7868ac720f90ffd3d7c7b78f3d75f14a9755ea8138804806f4739429d1a313b3abaaf89ce97fbdf10bc01d66723b0b38ad5dc51c87e5f852e2c8fc923cf0f9c86bb7bf8ae808532fcb8a981338d5b13278e66e19915e41c6fbd09f1fce3300da422fbf46f706d1c79f298c740926e14069f83dae52a25bad684e420ad5fc8af3b02e0cf3f79782fb6e7e65abe5e1f6b4fe41f20339b2986fe39f7ce4ceb9c2490d5229e9bfda93150d6800880c411daae");
let beta = ByteSeq::from_hex("d065ca3be8716236e99f64139adf481090f0a0c839f86ffda3c4fad948166af0");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
#[test]
fn test_72() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("72");
let pi = ByteSeq::from_hex("3d396dc417bee1975ff63c4e8b43b9417be03a91d5eb47309790d74100271342d6dc11511333ec4bc42aea3e02640dc870665044e85085c3dea43eedeb266d9b2de3824aca18b8de3e4d198bde808d80a2a10f0f4bd73fbc7cc36da44cb68af3161b2264e737dcd2d669252abb29f275c971ff6b8234876b7d1ff3d4d05197fe563d6ae92685dccbbbb689b4837da42fe47433019d9bfc50001b11708bf9f656532febf674119c0d67e27714195722fd977e0fc35d7325b5fb3ecb54df53986e01a809d0e5ec442fdacc3d271e7ab5480b8eb18f25cd3baf6a47abc6bf027e8dedef911f2bec367fa5d65e106f314b64cc1d9534d4f26fa034035a43852be66a");
let beta = ByteSeq::from_hex("a229210b84f0bb43b296075f226dee433cf2727cd6c2e4871afdeb77414f6a47");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
#[test]
fn test_af82() {
let kp = get_test_key();
let alpha = ByteSeq::from_hex("af82");
let pi = ByteSeq::from_hex("57b07056abc6851330b21ae890fd43ea53b4435319748cf8dba82148ee381c11d21a8660a8714aa59abaac2b7d0141ac4e85b1113b144328eb11461a7f26086896036fc49579a58a2516cecd274946f8dd82fef31652dfe2e2b495966cd6193a1bd197ef6e3472f30bfe14827dd968ea3bf8310dc002a765a0d54b12c3c9627309800b74701a3f7d07a02db0a6ca3a639e60726059727313818a6b671bebe18f078713ced33e50acbfd1e661ec89c5e82b8e1e07f6293f45474aa57d084da46a2437932491d92a87b3393bb0ec62254a3eca19e1004756867839671f84f7a2378097f334832f4aa0442fc5f8637fb2220bb3f2dca247927f0d49ae1c1b2e7455");
let beta = ByteSeq::from_hex("ebc5582b6aaf23c424ec1c74e1b8250327c957967fa37566284dac8400e62032");
let pi_prime = prove((kp.n, kp.d), &alpha).unwrap();
assert_eq!(pi_prime, pi);
let beta_prime = proof_to_hash(&pi).unwrap();
assert_eq!(beta_prime, beta);
let beta_prime = verify((kp.n, kp.e), &alpha, &pi).unwrap();
assert_eq!(beta_prime, beta);
}
}
| {
proof_to_hash(pi_string)
} | conditional_block |
game.rs | #[cfg(feature = "hot-reload")]
use crate::assets::HotReloader;
use crate::config::AudioConfig;
use crate::core::audio::AudioSystem;
use crate::core::camera::{Camera, ProjectionMatrix};
use crate::core::input::{Input, InputAction};
use crate::core::random::{RandomGenerator, Seed};
use crate::core::scene::{Scene, SceneStack};
use crate::core::transform::update_transforms;
use crate::core::window::WindowDim;
use crate::event::GameEvent;
use crate::gameplay::collision::CollisionWorld;
use crate::gameplay::delete::GarbageCollector;
use crate::render::path::debug::DebugQueue;
use crate::render::ui::gui::GuiContext;
use crate::render::Renderer;
use crate::resources::Resources;
use crate::{HEIGHT, WIDTH};
use glfw::{Context, Key, MouseButton, WindowEvent};
use log::info;
use luminance_glfw::GlfwSurface;
use shrev::{EventChannel, ReaderId};
use std::any::Any;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::thread;
use std::time::{Duration, Instant};
/// GameBuilder is used to create a new game. Game struct has a lot of members that do not need to be
/// exposed so gamebuilder provides a simpler way to get started.
pub struct GameBuilder<'a, A>
where
A: InputAction,
{
surface: &'a mut GlfwSurface,
scene: Option<Box<dyn Scene<WindowEvent>>>,
resources: Resources,
phantom: PhantomData<A>,
seed: Option<Seed>,
input_config: Option<(HashMap<Key, A>, HashMap<MouseButton, A>)>,
gui_context: GuiContext,
audio_config: AudioConfig,
}
impl<'a, A> GameBuilder<'a, A>
where
A: InputAction +'static,
{
pub fn new(surface: &'a mut GlfwSurface) -> Self {
// resources will need at least an event channel and an input
let mut resources = Resources::default();
let chan: EventChannel<GameEvent> = EventChannel::new();
resources.insert(chan);
// and some asset manager;
crate::assets::create_asset_managers(surface, &mut resources);
// the proj matrix.
resources.insert(ProjectionMatrix::new(WIDTH as f32, HEIGHT as f32));
resources.insert(WindowDim::new(WIDTH, HEIGHT));
resources.insert(CollisionWorld::default());
resources.insert(DebugQueue::default());
Self {
gui_context: GuiContext::new(WindowDim::new(WIDTH, HEIGHT)),
surface,
scene: None,
resources,
input_config: None,
phantom: PhantomData::default(),
seed: None,
audio_config: AudioConfig::default(),
}
}
/// Set up the first scene.
pub fn for_scene(mut self, scene: Box<dyn Scene<WindowEvent>>) -> Self {
self.scene = Some(scene);
self
}
pub fn with_input_config(
mut self,
key_map: HashMap<Key, A>,
btn_map: HashMap<MouseButton, A>,
) -> Self {
self.input_config = Some((key_map, btn_map));
self
}
/// Specific config for audio
pub fn with_audio_config(mut self, audio_config: AudioConfig) -> Self {
self.audio_config = audio_config;
self
}
/// Add custom resources.
pub fn with_resource<T: Any>(mut self, r: T) -> Self {
self.resources.insert(r);
self
}
pub fn with_seed(mut self, seed: Seed) -> Self {
self.seed = Some(seed);
self
}
pub fn | (mut self) -> Game<'a, A> {
let renderer = Renderer::new(self.surface, &self.gui_context);
// Need some input :D
let input: Input<A> = {
let (key_mapping, btn_mapping) = self
.input_config
.unwrap_or((A::get_default_key_mapping(), A::get_default_mouse_mapping()));
Input::new(key_mapping, btn_mapping)
};
self.resources.insert(input);
let mut world = hecs::World::new();
// if a seed is provided, let's add it to the resources.
if let Some(seed) = self.seed {
self.resources.insert(RandomGenerator::new(seed));
} else {
self.resources.insert(RandomGenerator::from_entropy());
}
let scene_stack = {
let mut scenes = SceneStack::default();
if let Some(scene) = self.scene {
scenes.push(scene, &mut world, &mut self.resources);
}
scenes
};
let rdr_id = {
let mut chan = self
.resources
.fetch_mut::<EventChannel<GameEvent>>()
.unwrap();
chan.register_reader()
};
let garbage_collector = GarbageCollector::new(&mut self.resources);
// we need a camera :)
world.spawn((Camera::new(),));
info!("Finished building game");
// audio system.
let audio_system = AudioSystem::new(&self.resources, self.audio_config)
.expect("Cannot create audio system");
Game {
surface: self.surface,
renderer,
scene_stack,
world,
audio_system,
resources: self.resources,
rdr_id,
garbage_collector,
phantom: self.phantom,
gui_context: self.gui_context,
#[cfg(feature = "hot-reload")]
hot_reloader: HotReloader::new(),
}
}
}
/// Struct that holds the game state and systems.
///
/// # Lifetime requirement:
/// The opengl context is held in GlfwSurface. This is a mutable reference here as we do not want the
/// context to be dropped at the same time as the systems. If it is dropped before, then releasing GPU
/// resources will throw a segfault.
///
/// # Generic parameters:
/// - A: Action that is derived from the inputs. (e.g. Move Left)
///
pub struct Game<'a, A> {
/// for drawing stuff
surface: &'a mut GlfwSurface,
renderer: Renderer<GlfwSurface>,
/// All the scenes. Current scene will be used in the main loop.
scene_stack: SceneStack<WindowEvent>,
/// Play music and sound effects
audio_system: AudioSystem,
/// Resources (assets, inputs...)
resources: Resources,
/// Current entities.
world: hecs::World,
/// Read events from the systems
rdr_id: ReaderId<GameEvent>,
/// Clean up the dead entities.
garbage_collector: GarbageCollector,
gui_context: GuiContext,
phantom: PhantomData<A>,
#[cfg(feature = "hot-reload")]
hot_reloader: HotReloader<GlfwSurface>,
}
impl<'a, A> Game<'a, A>
where
A: InputAction +'static,
{
/// Run the game. This is the main loop.
pub fn run(&mut self) {
let mut current_time = Instant::now();
let dt = Duration::from_millis(16);
let mut back_buffer = self.surface.back_buffer().unwrap();
'app: loop {
// 1. Poll the events and update the Input resource
// ------------------------------------------------
let mut resize = false;
self.surface.window.glfw.poll_events();
{
let mut input = self.resources.fetch_mut::<Input<A>>().unwrap();
input.prepare();
self.gui_context.reset_inputs();
for (_, event) in self.surface.events_rx.try_iter() {
match event {
WindowEvent::Close => break 'app,
WindowEvent::FramebufferSize(_, _) => resize = true,
ev => {
self.gui_context.process_event(ev.clone());
if let Some(scene) = self.scene_stack.current_mut() {
scene.process_input(&mut self.world, ev.clone(), &self.resources);
}
input.process_event(ev)
}
}
}
}
// 2. Update the scene.
// ------------------------------------------------
let scene_result = if let Some(scene) = self.scene_stack.current_mut() {
let scene_res = scene.update(dt, &mut self.world, &self.resources);
{
let chan = self.resources.fetch::<EventChannel<GameEvent>>().unwrap();
for ev in chan.read(&mut self.rdr_id) {
scene.process_event(&mut self.world, ev.clone(), &self.resources);
}
}
let maybe_gui =
scene.prepare_gui(dt, &mut self.world, &self.resources, &mut self.gui_context);
self.renderer.prepare_ui(
self.surface,
maybe_gui,
&self.resources,
&mut *self.gui_context.fonts.borrow_mut(),
);
Some(scene_res)
} else {
None
};
// Update children transforms:
// -----------------------------
update_transforms(&mut self.world);
// 3. Clean up dead entities.
// ------------------------------------------------
self.garbage_collector
.collect(&mut self.world, &self.resources);
// 4. Render to screen
// ------------------------------------------------
log::debug!("RENDER");
self.renderer
.update(self.surface, &self.world, dt, &self.resources);
if resize {
back_buffer = self.surface.back_buffer().unwrap();
let new_size = back_buffer.size();
let mut proj = self.resources.fetch_mut::<ProjectionMatrix>().unwrap();
proj.resize(new_size[0] as f32, new_size[1] as f32);
let mut dim = self.resources.fetch_mut::<WindowDim>().unwrap();
dim.resize(new_size[0], new_size[1]);
self.gui_context.window_dim = *dim;
}
let render =
self.renderer
.render(self.surface, &mut back_buffer, &self.world, &self.resources);
if render.is_ok() {
self.surface.window.swap_buffers();
} else {
break 'app;
}
// Play music :)
self.audio_system.process(&self.resources);
// Update collision world for collision queries.
{
let mut collisions = self.resources.fetch_mut::<CollisionWorld>().unwrap();
collisions.synchronize(&self.world);
}
// Either clean up or load new resources.
crate::assets::update_asset_managers(self.surface, &self.resources);
#[cfg(feature = "hot-reload")]
self.hot_reloader.update(&self.resources);
// Now, if need to switch scenes, do it.
if let Some(res) = scene_result {
self.scene_stack
.apply_result(res, &mut self.world, &mut self.resources);
}
let now = Instant::now();
let frame_duration = now - current_time;
if frame_duration < dt {
thread::sleep(dt - frame_duration);
}
current_time = now;
}
info!("Bye bye.");
}
}
| build | identifier_name |
game.rs | #[cfg(feature = "hot-reload")]
use crate::assets::HotReloader;
use crate::config::AudioConfig;
use crate::core::audio::AudioSystem;
use crate::core::camera::{Camera, ProjectionMatrix};
use crate::core::input::{Input, InputAction};
use crate::core::random::{RandomGenerator, Seed};
use crate::core::scene::{Scene, SceneStack};
use crate::core::transform::update_transforms;
use crate::core::window::WindowDim;
use crate::event::GameEvent;
use crate::gameplay::collision::CollisionWorld;
use crate::gameplay::delete::GarbageCollector;
use crate::render::path::debug::DebugQueue;
use crate::render::ui::gui::GuiContext;
use crate::render::Renderer;
use crate::resources::Resources;
use crate::{HEIGHT, WIDTH};
use glfw::{Context, Key, MouseButton, WindowEvent};
use log::info;
use luminance_glfw::GlfwSurface;
use shrev::{EventChannel, ReaderId};
use std::any::Any;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::thread;
use std::time::{Duration, Instant};
/// GameBuilder is used to create a new game. Game struct has a lot of members that do not need to be
/// exposed so gamebuilder provides a simpler way to get started.
pub struct GameBuilder<'a, A>
where
A: InputAction,
{
surface: &'a mut GlfwSurface,
scene: Option<Box<dyn Scene<WindowEvent>>>,
resources: Resources,
phantom: PhantomData<A>,
seed: Option<Seed>,
input_config: Option<(HashMap<Key, A>, HashMap<MouseButton, A>)>,
gui_context: GuiContext,
audio_config: AudioConfig,
}
impl<'a, A> GameBuilder<'a, A>
where
A: InputAction +'static,
{
pub fn new(surface: &'a mut GlfwSurface) -> Self {
// resources will need at least an event channel and an input
let mut resources = Resources::default();
let chan: EventChannel<GameEvent> = EventChannel::new();
resources.insert(chan);
// and some asset manager;
crate::assets::create_asset_managers(surface, &mut resources);
// the proj matrix.
resources.insert(ProjectionMatrix::new(WIDTH as f32, HEIGHT as f32));
resources.insert(WindowDim::new(WIDTH, HEIGHT));
resources.insert(CollisionWorld::default());
resources.insert(DebugQueue::default());
Self {
gui_context: GuiContext::new(WindowDim::new(WIDTH, HEIGHT)),
surface,
scene: None,
resources,
input_config: None,
phantom: PhantomData::default(),
seed: None,
audio_config: AudioConfig::default(),
}
}
/// Set up the first scene.
pub fn for_scene(mut self, scene: Box<dyn Scene<WindowEvent>>) -> Self {
self.scene = Some(scene);
self
}
pub fn with_input_config(
mut self,
key_map: HashMap<Key, A>,
btn_map: HashMap<MouseButton, A>,
) -> Self {
self.input_config = Some((key_map, btn_map));
self
}
/// Specific config for audio
pub fn with_audio_config(mut self, audio_config: AudioConfig) -> Self {
self.audio_config = audio_config;
self
}
/// Add custom resources.
pub fn with_resource<T: Any>(mut self, r: T) -> Self {
self.resources.insert(r);
self
}
pub fn with_seed(mut self, seed: Seed) -> Self {
self.seed = Some(seed);
self
}
pub fn build(mut self) -> Game<'a, A> {
let renderer = Renderer::new(self.surface, &self.gui_context);
// Need some input :D
let input: Input<A> = {
let (key_mapping, btn_mapping) = self
.input_config
.unwrap_or((A::get_default_key_mapping(), A::get_default_mouse_mapping()));
Input::new(key_mapping, btn_mapping)
};
self.resources.insert(input);
let mut world = hecs::World::new();
// if a seed is provided, let's add it to the resources.
if let Some(seed) = self.seed {
self.resources.insert(RandomGenerator::new(seed));
} else {
self.resources.insert(RandomGenerator::from_entropy());
}
let scene_stack = {
let mut scenes = SceneStack::default();
if let Some(scene) = self.scene {
scenes.push(scene, &mut world, &mut self.resources);
}
scenes
};
let rdr_id = {
let mut chan = self
.resources
.fetch_mut::<EventChannel<GameEvent>>()
.unwrap();
chan.register_reader()
};
let garbage_collector = GarbageCollector::new(&mut self.resources);
// we need a camera :)
world.spawn((Camera::new(),));
info!("Finished building game");
// audio system.
let audio_system = AudioSystem::new(&self.resources, self.audio_config)
.expect("Cannot create audio system");
Game {
surface: self.surface,
renderer,
scene_stack,
world,
audio_system,
resources: self.resources,
rdr_id,
garbage_collector,
phantom: self.phantom,
gui_context: self.gui_context,
#[cfg(feature = "hot-reload")]
hot_reloader: HotReloader::new(),
}
}
}
/// Struct that holds the game state and systems.
///
/// # Lifetime requirement:
/// The opengl context is held in GlfwSurface. This is a mutable reference here as we do not want the
/// context to be dropped at the same time as the systems. If it is dropped before, then releasing GPU
/// resources will throw a segfault.
///
/// # Generic parameters:
/// - A: Action that is derived from the inputs. (e.g. Move Left)
///
pub struct Game<'a, A> {
/// for drawing stuff
surface: &'a mut GlfwSurface,
renderer: Renderer<GlfwSurface>,
/// All the scenes. Current scene will be used in the main loop.
scene_stack: SceneStack<WindowEvent>,
/// Play music and sound effects
audio_system: AudioSystem,
/// Resources (assets, inputs...)
resources: Resources,
/// Current entities.
world: hecs::World,
/// Read events from the systems
rdr_id: ReaderId<GameEvent>,
/// Clean up the dead entities.
garbage_collector: GarbageCollector,
gui_context: GuiContext,
phantom: PhantomData<A>,
#[cfg(feature = "hot-reload")]
hot_reloader: HotReloader<GlfwSurface>,
}
impl<'a, A> Game<'a, A>
where
A: InputAction +'static,
{
/// Run the game. This is the main loop.
pub fn run(&mut self) {
let mut current_time = Instant::now();
let dt = Duration::from_millis(16);
let mut back_buffer = self.surface.back_buffer().unwrap();
'app: loop {
// 1. Poll the events and update the Input resource
// ------------------------------------------------
let mut resize = false;
self.surface.window.glfw.poll_events();
{
let mut input = self.resources.fetch_mut::<Input<A>>().unwrap();
input.prepare();
self.gui_context.reset_inputs();
for (_, event) in self.surface.events_rx.try_iter() {
match event {
WindowEvent::Close => break 'app,
WindowEvent::FramebufferSize(_, _) => resize = true,
ev => {
self.gui_context.process_event(ev.clone());
if let Some(scene) = self.scene_stack.current_mut() {
scene.process_input(&mut self.world, ev.clone(), &self.resources);
}
input.process_event(ev)
}
}
}
}
// 2. Update the scene.
// ------------------------------------------------ | let scene_result = if let Some(scene) = self.scene_stack.current_mut() {
let scene_res = scene.update(dt, &mut self.world, &self.resources);
{
let chan = self.resources.fetch::<EventChannel<GameEvent>>().unwrap();
for ev in chan.read(&mut self.rdr_id) {
scene.process_event(&mut self.world, ev.clone(), &self.resources);
}
}
let maybe_gui =
scene.prepare_gui(dt, &mut self.world, &self.resources, &mut self.gui_context);
self.renderer.prepare_ui(
self.surface,
maybe_gui,
&self.resources,
&mut *self.gui_context.fonts.borrow_mut(),
);
Some(scene_res)
} else {
None
};
// Update children transforms:
// -----------------------------
update_transforms(&mut self.world);
// 3. Clean up dead entities.
// ------------------------------------------------
self.garbage_collector
.collect(&mut self.world, &self.resources);
// 4. Render to screen
// ------------------------------------------------
log::debug!("RENDER");
self.renderer
.update(self.surface, &self.world, dt, &self.resources);
if resize {
back_buffer = self.surface.back_buffer().unwrap();
let new_size = back_buffer.size();
let mut proj = self.resources.fetch_mut::<ProjectionMatrix>().unwrap();
proj.resize(new_size[0] as f32, new_size[1] as f32);
let mut dim = self.resources.fetch_mut::<WindowDim>().unwrap();
dim.resize(new_size[0], new_size[1]);
self.gui_context.window_dim = *dim;
}
let render =
self.renderer
.render(self.surface, &mut back_buffer, &self.world, &self.resources);
if render.is_ok() {
self.surface.window.swap_buffers();
} else {
break 'app;
}
// Play music :)
self.audio_system.process(&self.resources);
// Update collision world for collision queries.
{
let mut collisions = self.resources.fetch_mut::<CollisionWorld>().unwrap();
collisions.synchronize(&self.world);
}
// Either clean up or load new resources.
crate::assets::update_asset_managers(self.surface, &self.resources);
#[cfg(feature = "hot-reload")]
self.hot_reloader.update(&self.resources);
// Now, if need to switch scenes, do it.
if let Some(res) = scene_result {
self.scene_stack
.apply_result(res, &mut self.world, &mut self.resources);
}
let now = Instant::now();
let frame_duration = now - current_time;
if frame_duration < dt {
thread::sleep(dt - frame_duration);
}
current_time = now;
}
info!("Bye bye.");
}
} | random_line_split |
|
game.rs | #[cfg(feature = "hot-reload")]
use crate::assets::HotReloader;
use crate::config::AudioConfig;
use crate::core::audio::AudioSystem;
use crate::core::camera::{Camera, ProjectionMatrix};
use crate::core::input::{Input, InputAction};
use crate::core::random::{RandomGenerator, Seed};
use crate::core::scene::{Scene, SceneStack};
use crate::core::transform::update_transforms;
use crate::core::window::WindowDim;
use crate::event::GameEvent;
use crate::gameplay::collision::CollisionWorld;
use crate::gameplay::delete::GarbageCollector;
use crate::render::path::debug::DebugQueue;
use crate::render::ui::gui::GuiContext;
use crate::render::Renderer;
use crate::resources::Resources;
use crate::{HEIGHT, WIDTH};
use glfw::{Context, Key, MouseButton, WindowEvent};
use log::info;
use luminance_glfw::GlfwSurface;
use shrev::{EventChannel, ReaderId};
use std::any::Any;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::thread;
use std::time::{Duration, Instant};
/// GameBuilder is used to create a new game. Game struct has a lot of members that do not need to be
/// exposed so gamebuilder provides a simpler way to get started.
pub struct GameBuilder<'a, A>
where
A: InputAction,
{
surface: &'a mut GlfwSurface,
scene: Option<Box<dyn Scene<WindowEvent>>>,
resources: Resources,
phantom: PhantomData<A>,
seed: Option<Seed>,
input_config: Option<(HashMap<Key, A>, HashMap<MouseButton, A>)>,
gui_context: GuiContext,
audio_config: AudioConfig,
}
impl<'a, A> GameBuilder<'a, A>
where
A: InputAction +'static,
{
pub fn new(surface: &'a mut GlfwSurface) -> Self {
// resources will need at least an event channel and an input
let mut resources = Resources::default();
let chan: EventChannel<GameEvent> = EventChannel::new();
resources.insert(chan);
// and some asset manager;
crate::assets::create_asset_managers(surface, &mut resources);
// the proj matrix.
resources.insert(ProjectionMatrix::new(WIDTH as f32, HEIGHT as f32));
resources.insert(WindowDim::new(WIDTH, HEIGHT));
resources.insert(CollisionWorld::default());
resources.insert(DebugQueue::default());
Self {
gui_context: GuiContext::new(WindowDim::new(WIDTH, HEIGHT)),
surface,
scene: None,
resources,
input_config: None,
phantom: PhantomData::default(),
seed: None,
audio_config: AudioConfig::default(),
}
}
/// Set up the first scene.
pub fn for_scene(mut self, scene: Box<dyn Scene<WindowEvent>>) -> Self {
self.scene = Some(scene);
self
}
pub fn with_input_config(
mut self,
key_map: HashMap<Key, A>,
btn_map: HashMap<MouseButton, A>,
) -> Self {
self.input_config = Some((key_map, btn_map));
self
}
/// Specific config for audio
pub fn with_audio_config(mut self, audio_config: AudioConfig) -> Self {
self.audio_config = audio_config;
self
}
/// Add custom resources.
pub fn with_resource<T: Any>(mut self, r: T) -> Self {
self.resources.insert(r);
self
}
pub fn with_seed(mut self, seed: Seed) -> Self |
pub fn build(mut self) -> Game<'a, A> {
let renderer = Renderer::new(self.surface, &self.gui_context);
// Need some input :D
let input: Input<A> = {
let (key_mapping, btn_mapping) = self
.input_config
.unwrap_or((A::get_default_key_mapping(), A::get_default_mouse_mapping()));
Input::new(key_mapping, btn_mapping)
};
self.resources.insert(input);
let mut world = hecs::World::new();
// if a seed is provided, let's add it to the resources.
if let Some(seed) = self.seed {
self.resources.insert(RandomGenerator::new(seed));
} else {
self.resources.insert(RandomGenerator::from_entropy());
}
let scene_stack = {
let mut scenes = SceneStack::default();
if let Some(scene) = self.scene {
scenes.push(scene, &mut world, &mut self.resources);
}
scenes
};
let rdr_id = {
let mut chan = self
.resources
.fetch_mut::<EventChannel<GameEvent>>()
.unwrap();
chan.register_reader()
};
let garbage_collector = GarbageCollector::new(&mut self.resources);
// we need a camera :)
world.spawn((Camera::new(),));
info!("Finished building game");
// audio system.
let audio_system = AudioSystem::new(&self.resources, self.audio_config)
.expect("Cannot create audio system");
Game {
surface: self.surface,
renderer,
scene_stack,
world,
audio_system,
resources: self.resources,
rdr_id,
garbage_collector,
phantom: self.phantom,
gui_context: self.gui_context,
#[cfg(feature = "hot-reload")]
hot_reloader: HotReloader::new(),
}
}
}
/// Struct that holds the game state and systems.
///
/// # Lifetime requirement:
/// The opengl context is held in GlfwSurface. This is a mutable reference here as we do not want the
/// context to be dropped at the same time as the systems. If it is dropped before, then releasing GPU
/// resources will throw a segfault.
///
/// # Generic parameters:
/// - A: Action that is derived from the inputs. (e.g. Move Left)
///
pub struct Game<'a, A> {
/// for drawing stuff
surface: &'a mut GlfwSurface,
renderer: Renderer<GlfwSurface>,
/// All the scenes. Current scene will be used in the main loop.
scene_stack: SceneStack<WindowEvent>,
/// Play music and sound effects
audio_system: AudioSystem,
/// Resources (assets, inputs...)
resources: Resources,
/// Current entities.
world: hecs::World,
/// Read events from the systems
rdr_id: ReaderId<GameEvent>,
/// Clean up the dead entities.
garbage_collector: GarbageCollector,
gui_context: GuiContext,
phantom: PhantomData<A>,
#[cfg(feature = "hot-reload")]
hot_reloader: HotReloader<GlfwSurface>,
}
impl<'a, A> Game<'a, A>
where
A: InputAction +'static,
{
/// Run the game. This is the main loop.
pub fn run(&mut self) {
let mut current_time = Instant::now();
let dt = Duration::from_millis(16);
let mut back_buffer = self.surface.back_buffer().unwrap();
'app: loop {
// 1. Poll the events and update the Input resource
// ------------------------------------------------
let mut resize = false;
self.surface.window.glfw.poll_events();
{
let mut input = self.resources.fetch_mut::<Input<A>>().unwrap();
input.prepare();
self.gui_context.reset_inputs();
for (_, event) in self.surface.events_rx.try_iter() {
match event {
WindowEvent::Close => break 'app,
WindowEvent::FramebufferSize(_, _) => resize = true,
ev => {
self.gui_context.process_event(ev.clone());
if let Some(scene) = self.scene_stack.current_mut() {
scene.process_input(&mut self.world, ev.clone(), &self.resources);
}
input.process_event(ev)
}
}
}
}
// 2. Update the scene.
// ------------------------------------------------
let scene_result = if let Some(scene) = self.scene_stack.current_mut() {
let scene_res = scene.update(dt, &mut self.world, &self.resources);
{
let chan = self.resources.fetch::<EventChannel<GameEvent>>().unwrap();
for ev in chan.read(&mut self.rdr_id) {
scene.process_event(&mut self.world, ev.clone(), &self.resources);
}
}
let maybe_gui =
scene.prepare_gui(dt, &mut self.world, &self.resources, &mut self.gui_context);
self.renderer.prepare_ui(
self.surface,
maybe_gui,
&self.resources,
&mut *self.gui_context.fonts.borrow_mut(),
);
Some(scene_res)
} else {
None
};
// Update children transforms:
// -----------------------------
update_transforms(&mut self.world);
// 3. Clean up dead entities.
// ------------------------------------------------
self.garbage_collector
.collect(&mut self.world, &self.resources);
// 4. Render to screen
// ------------------------------------------------
log::debug!("RENDER");
self.renderer
.update(self.surface, &self.world, dt, &self.resources);
if resize {
back_buffer = self.surface.back_buffer().unwrap();
let new_size = back_buffer.size();
let mut proj = self.resources.fetch_mut::<ProjectionMatrix>().unwrap();
proj.resize(new_size[0] as f32, new_size[1] as f32);
let mut dim = self.resources.fetch_mut::<WindowDim>().unwrap();
dim.resize(new_size[0], new_size[1]);
self.gui_context.window_dim = *dim;
}
let render =
self.renderer
.render(self.surface, &mut back_buffer, &self.world, &self.resources);
if render.is_ok() {
self.surface.window.swap_buffers();
} else {
break 'app;
}
// Play music :)
self.audio_system.process(&self.resources);
// Update collision world for collision queries.
{
let mut collisions = self.resources.fetch_mut::<CollisionWorld>().unwrap();
collisions.synchronize(&self.world);
}
// Either clean up or load new resources.
crate::assets::update_asset_managers(self.surface, &self.resources);
#[cfg(feature = "hot-reload")]
self.hot_reloader.update(&self.resources);
// Now, if need to switch scenes, do it.
if let Some(res) = scene_result {
self.scene_stack
.apply_result(res, &mut self.world, &mut self.resources);
}
let now = Instant::now();
let frame_duration = now - current_time;
if frame_duration < dt {
thread::sleep(dt - frame_duration);
}
current_time = now;
}
info!("Bye bye.");
}
}
| {
self.seed = Some(seed);
self
} | identifier_body |
mod.rs | //! Utilities for handling shell surfaces with the `wl_shell` protocol
//!
//! This module provides automatic handling of shell surfaces objects, by being registered
//! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`,
//! thus this module is provided as a compatibility layer with older clients. As a consequence,
//! you can as a compositor-writer decide to only support its functionality in a best-effort
//! maneer: as this global is part of the core protocol, you are still required to provide
//! some support for it.
//!
//! ## Why use this implementation
//!
//! This implementation can track for you the various shell surfaces defined by the
//! clients by handling the `wl_shell` protocol.
//!
//! It allows you to easily access a list of all shell surfaces defined by your clients
//! access their associated metadata and underlying `wl_surface`s.
//!
//! This handler only handles the protocol exchanges with the client to present you the
//! information in a coherent and relatively easy to use manner. All the actual drawing
//! and positioning logic of windows is out of its scope.
//!
//! ## How to use it
//!
//! ### Initialization
//!
//! To initialize this handler, simple use the [`wl_shell_init`](::wayland::shell::legacy::wl_shell_init)
//! function provided in this module. You will need to provide it the [`CompositorToken`](::wayland::compositor::CompositorToken)
//! you retrieved from an instantiation of the compositor handler provided by smithay.
//!
//! ```no_run
//! # extern crate wayland_server;
//! # #[macro_use] extern crate smithay;
//! # extern crate wayland_protocols;
//! #
//! use smithay::wayland::compositor::roles::*;
//! use smithay::wayland::compositor::CompositorToken;
//! use smithay::wayland::shell::legacy::{wl_shell_init, ShellSurfaceRole, ShellRequest};
//! # use wayland_server::protocol::{wl_seat, wl_output};
//!
//! // define the roles type. You need to integrate the XdgSurface role:
//! define_roles!(MyRoles =>
//! [ShellSurface, ShellSurfaceRole]
//! );
//!
//! # fn main() {
//! # let mut event_loop = wayland_server::calloop::EventLoop::<()>::new().unwrap();
//! # let mut display = wayland_server::Display::new(event_loop.handle());
//! # let (compositor_token, _, _) = smithay::wayland::compositor::compositor_init::<MyRoles, _, _>(
//! # &mut display,
//! # |_, _, _| {},
//! # None
//! # );
//! let (shell_state, _) = wl_shell_init(
//! &mut display,
//! // token from the compositor implementation
//! compositor_token,
//! // your implementation
//! |event: ShellRequest<_>| { /*... */ },
//! None // put a logger if you want
//! );
//!
//! // You're now ready to go!
//! # }
//! ```
use std::{
cell::RefCell,
rc::Rc,
sync::{Arc, Mutex},
};
use crate::wayland::compositor::{roles::Role, CompositorToken};
use wayland_server::{
protocol::{wl_output, wl_seat, wl_shell, wl_shell_surface, wl_surface},
Display, Global,
};
mod wl_handlers;
/// Metadata associated with the `wl_surface` role
pub struct ShellSurfaceRole {
/// Title of the surface
pub title: String,
/// Class of the surface
pub class: String,
pending_ping: u32,
}
/// A handle to a shell surface
pub struct ShellSurface<R> {
wl_surface: wl_surface::WlSurface,
shell_surface: wl_shell_surface::WlShellSurface,
token: CompositorToken<R>,
}
impl<R> ShellSurface<R>
where
R: Role<ShellSurfaceRole> +'static,
{
/// Is the shell surface referred by this handle still alive?
pub fn alive(&self) -> bool {
self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive()
}
/// Do this handle and the other one actually refer to the same shell surface?
pub fn equals(&self, other: &Self) -> bool {
self.shell_surface.as_ref().equals(&other.shell_surface.as_ref())
}
/// Access the underlying `wl_surface` of this toplevel surface
///
/// Returns `None` if the toplevel surface actually no longer exists.
pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> |
/// Send a ping request to this shell surface
///
/// You'll receive the reply as a [`ShellRequest::Pong`] request
///
/// A typical use is to start a timer at the same time you send this ping
/// request, and cancel it when you receive the pong. If the timer runs
/// down to 0 before a pong is received, mark the client as unresponsive.
///
/// Fails if this shell client already has a pending ping or is already dead.
pub fn send_ping(&self, serial: u32) -> Result<(), ()> {
if!self.alive() {
return Err(());
}
let ret = self.token.with_role_data(&self.wl_surface, |data| {
if data.pending_ping == 0 {
data.pending_ping = serial;
true
} else {
false
}
});
if let Ok(true) = ret {
self.shell_surface.ping(serial);
Ok(())
} else {
Err(())
}
}
/// Send a configure event to this toplevel surface to suggest it a new configuration
pub fn send_configure(&self, size: (u32, u32), edges: wl_shell_surface::Resize) {
self.shell_surface.configure(edges, size.0 as i32, size.1 as i32)
}
/// Signal a popup surface that it has lost focus
pub fn send_popup_done(&self) {
self.shell_surface.popup_done()
}
}
/// Possible kinds of shell surface of the `wl_shell` protocol
pub enum ShellSurfaceKind {
/// Toplevel, a regular window displayed somewhere in the compositor space
Toplevel,
/// Transient, this surface has a parent surface
///
/// These are sub-windows of an application (for example a configuration window),
/// and as such should only be visible in their parent window is, and on top of it.
Transient {
/// The surface considered as parent
parent: wl_surface::WlSurface,
/// Location relative to the parent
location: (i32, i32),
/// Wether this window should be marked as inactive
inactive: bool,
},
/// Fullscreen surface, covering an entire output
Fullscreen {
/// Method used for fullscreen
method: wl_shell_surface::FullscreenMethod,
/// Framerate (relevant only for driver fullscreen)
framerate: u32,
/// Requested output if any
output: Option<wl_output::WlOutput>,
},
/// A popup surface
///
/// Short-lived surface, typically referred as "tooltips" in many
/// contexts.
Popup {
/// The parent surface of this popup
parent: wl_surface::WlSurface,
/// The serial of the input event triggering the creation of this
/// popup
serial: u32,
/// Wether this popup should be marked as inactive
inactive: bool,
/// Location of the popup relative to its parent
location: (i32, i32),
/// Seat associated this the input that triggered the creation of the
/// popup. Used to define when the "popup done" event is sent.
seat: wl_seat::WlSeat,
},
/// A maximized surface
///
/// Like a toplevel surface, but as big as possible on a single output
/// while keeping any relevant desktop-environment interface visible.
Maximized {
/// Requested output for maximization
output: Option<wl_output::WlOutput>,
},
}
/// A request triggered by a `wl_shell_surface`
pub enum ShellRequest<R> {
/// A new shell surface was created
///
/// by default it has no kind and this should not be displayed
NewShellSurface {
/// The created surface
surface: ShellSurface<R>,
},
/// A pong event
///
/// The surface responded to its pending ping. If you receive this
/// event, smithay has already checked that the responded serial was valid.
Pong {
/// The surface that sent the pong
surface: ShellSurface<R>,
},
/// Start of an interactive move
///
/// The surface requests that an interactive move is started on it
Move {
/// The surface requesting the move
surface: ShellSurface<R>,
/// Serial of the implicit grab that initiated the move
serial: u32,
/// Seat associated with the move
seat: wl_seat::WlSeat,
},
/// Start of an interactive resize
///
/// The surface requests that an interactive resize is started on it
Resize {
/// The surface requesting the resize
surface: ShellSurface<R>,
/// Serial of the implicit grab that initiated the resize
serial: u32,
/// Seat associated with the resize
seat: wl_seat::WlSeat,
/// Direction of the resize
edges: wl_shell_surface::Resize,
},
/// The surface changed its kind
SetKind {
/// The surface
surface: ShellSurface<R>,
/// Its new kind
kind: ShellSurfaceKind,
},
}
/// Shell global state
///
/// This state allows you to retrieve a list of surfaces
/// currently known to the shell global.
pub struct ShellState<R> {
known_surfaces: Vec<ShellSurface<R>>,
}
impl<R> ShellState<R>
where
R: Role<ShellSurfaceRole> +'static,
{
/// Cleans the internal surface storage by removing all dead surfaces
pub(crate) fn cleanup_surfaces(&mut self) {
self.known_surfaces.retain(|s| s.alive());
}
/// Access all the shell surfaces known by this handler
pub fn surfaces(&self) -> &[ShellSurface<R>] {
&self.known_surfaces[..]
}
}
/// Create a new `wl_shell` global
pub fn wl_shell_init<R, L, Impl>(
display: &mut Display,
ctoken: CompositorToken<R>,
implementation: Impl,
logger: L,
) -> (Arc<Mutex<ShellState<R>>>, Global<wl_shell::WlShell>)
where
R: Role<ShellSurfaceRole> +'static,
L: Into<Option<::slog::Logger>>,
Impl: FnMut(ShellRequest<R>) +'static,
{
let _log = crate::slog_or_stdlog(logger);
let implementation = Rc::new(RefCell::new(implementation));
let state = Arc::new(Mutex::new(ShellState {
known_surfaces: Vec::new(),
}));
let state2 = state.clone();
let global = display.create_global(1, move |shell, _version| {
self::wl_handlers::implement_shell(shell, ctoken, implementation.clone(), state2.clone());
});
(state, global)
}
| {
if self.alive() {
Some(&self.wl_surface)
} else {
None
}
} | identifier_body |
mod.rs | //! Utilities for handling shell surfaces with the `wl_shell` protocol
//!
//! This module provides automatic handling of shell surfaces objects, by being registered
//! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`,
//! thus this module is provided as a compatibility layer with older clients. As a consequence,
//! you can as a compositor-writer decide to only support its functionality in a best-effort
//! maneer: as this global is part of the core protocol, you are still required to provide
//! some support for it.
//!
//! ## Why use this implementation
//!
//! This implementation can track for you the various shell surfaces defined by the
//! clients by handling the `wl_shell` protocol.
//!
//! It allows you to easily access a list of all shell surfaces defined by your clients
//! access their associated metadata and underlying `wl_surface`s.
//!
//! This handler only handles the protocol exchanges with the client to present you the
//! information in a coherent and relatively easy to use manner. All the actual drawing
//! and positioning logic of windows is out of its scope.
//!
//! ## How to use it
//!
//! ### Initialization
//!
//! To initialize this handler, simple use the [`wl_shell_init`](::wayland::shell::legacy::wl_shell_init)
//! function provided in this module. You will need to provide it the [`CompositorToken`](::wayland::compositor::CompositorToken)
//! you retrieved from an instantiation of the compositor handler provided by smithay.
//!
//! ```no_run
//! # extern crate wayland_server;
//! # #[macro_use] extern crate smithay;
//! # extern crate wayland_protocols;
//! #
//! use smithay::wayland::compositor::roles::*;
//! use smithay::wayland::compositor::CompositorToken;
//! use smithay::wayland::shell::legacy::{wl_shell_init, ShellSurfaceRole, ShellRequest};
//! # use wayland_server::protocol::{wl_seat, wl_output};
//!
//! // define the roles type. You need to integrate the XdgSurface role:
//! define_roles!(MyRoles =>
//! [ShellSurface, ShellSurfaceRole]
//! );
//!
//! # fn main() {
//! # let mut event_loop = wayland_server::calloop::EventLoop::<()>::new().unwrap();
//! # let mut display = wayland_server::Display::new(event_loop.handle());
//! # let (compositor_token, _, _) = smithay::wayland::compositor::compositor_init::<MyRoles, _, _>(
//! # &mut display,
//! # |_, _, _| {},
//! # None
//! # );
//! let (shell_state, _) = wl_shell_init(
//! &mut display,
//! // token from the compositor implementation
//! compositor_token,
//! // your implementation
//! |event: ShellRequest<_>| { /*... */ },
//! None // put a logger if you want
//! );
//!
//! // You're now ready to go!
//! # }
//! ```
use std::{
cell::RefCell,
rc::Rc,
sync::{Arc, Mutex},
};
use crate::wayland::compositor::{roles::Role, CompositorToken};
use wayland_server::{
protocol::{wl_output, wl_seat, wl_shell, wl_shell_surface, wl_surface},
Display, Global,
};
mod wl_handlers;
/// Metadata associated with the `wl_surface` role
pub struct ShellSurfaceRole {
/// Title of the surface
pub title: String,
/// Class of the surface
pub class: String,
pending_ping: u32,
}
/// A handle to a shell surface
pub struct | <R> {
wl_surface: wl_surface::WlSurface,
shell_surface: wl_shell_surface::WlShellSurface,
token: CompositorToken<R>,
}
impl<R> ShellSurface<R>
where
R: Role<ShellSurfaceRole> +'static,
{
/// Is the shell surface referred by this handle still alive?
pub fn alive(&self) -> bool {
self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive()
}
/// Do this handle and the other one actually refer to the same shell surface?
pub fn equals(&self, other: &Self) -> bool {
self.shell_surface.as_ref().equals(&other.shell_surface.as_ref())
}
/// Access the underlying `wl_surface` of this toplevel surface
///
/// Returns `None` if the toplevel surface actually no longer exists.
pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> {
if self.alive() {
Some(&self.wl_surface)
} else {
None
}
}
/// Send a ping request to this shell surface
///
/// You'll receive the reply as a [`ShellRequest::Pong`] request
///
/// A typical use is to start a timer at the same time you send this ping
/// request, and cancel it when you receive the pong. If the timer runs
/// down to 0 before a pong is received, mark the client as unresponsive.
///
/// Fails if this shell client already has a pending ping or is already dead.
pub fn send_ping(&self, serial: u32) -> Result<(), ()> {
if!self.alive() {
return Err(());
}
let ret = self.token.with_role_data(&self.wl_surface, |data| {
if data.pending_ping == 0 {
data.pending_ping = serial;
true
} else {
false
}
});
if let Ok(true) = ret {
self.shell_surface.ping(serial);
Ok(())
} else {
Err(())
}
}
/// Send a configure event to this toplevel surface to suggest it a new configuration
pub fn send_configure(&self, size: (u32, u32), edges: wl_shell_surface::Resize) {
self.shell_surface.configure(edges, size.0 as i32, size.1 as i32)
}
/// Signal a popup surface that it has lost focus
pub fn send_popup_done(&self) {
self.shell_surface.popup_done()
}
}
/// Possible kinds of shell surface of the `wl_shell` protocol
pub enum ShellSurfaceKind {
/// Toplevel, a regular window displayed somewhere in the compositor space
Toplevel,
/// Transient, this surface has a parent surface
///
/// These are sub-windows of an application (for example a configuration window),
/// and as such should only be visible in their parent window is, and on top of it.
Transient {
/// The surface considered as parent
parent: wl_surface::WlSurface,
/// Location relative to the parent
location: (i32, i32),
/// Wether this window should be marked as inactive
inactive: bool,
},
/// Fullscreen surface, covering an entire output
Fullscreen {
/// Method used for fullscreen
method: wl_shell_surface::FullscreenMethod,
/// Framerate (relevant only for driver fullscreen)
framerate: u32,
/// Requested output if any
output: Option<wl_output::WlOutput>,
},
/// A popup surface
///
/// Short-lived surface, typically referred as "tooltips" in many
/// contexts.
Popup {
/// The parent surface of this popup
parent: wl_surface::WlSurface,
/// The serial of the input event triggering the creation of this
/// popup
serial: u32,
/// Wether this popup should be marked as inactive
inactive: bool,
/// Location of the popup relative to its parent
location: (i32, i32),
/// Seat associated this the input that triggered the creation of the
/// popup. Used to define when the "popup done" event is sent.
seat: wl_seat::WlSeat,
},
/// A maximized surface
///
/// Like a toplevel surface, but as big as possible on a single output
/// while keeping any relevant desktop-environment interface visible.
Maximized {
/// Requested output for maximization
output: Option<wl_output::WlOutput>,
},
}
/// A request triggered by a `wl_shell_surface`
pub enum ShellRequest<R> {
/// A new shell surface was created
///
/// by default it has no kind and this should not be displayed
NewShellSurface {
/// The created surface
surface: ShellSurface<R>,
},
/// A pong event
///
/// The surface responded to its pending ping. If you receive this
/// event, smithay has already checked that the responded serial was valid.
Pong {
/// The surface that sent the pong
surface: ShellSurface<R>,
},
/// Start of an interactive move
///
/// The surface requests that an interactive move is started on it
Move {
/// The surface requesting the move
surface: ShellSurface<R>,
/// Serial of the implicit grab that initiated the move
serial: u32,
/// Seat associated with the move
seat: wl_seat::WlSeat,
},
/// Start of an interactive resize
///
/// The surface requests that an interactive resize is started on it
Resize {
/// The surface requesting the resize
surface: ShellSurface<R>,
/// Serial of the implicit grab that initiated the resize
serial: u32,
/// Seat associated with the resize
seat: wl_seat::WlSeat,
/// Direction of the resize
edges: wl_shell_surface::Resize,
},
/// The surface changed its kind
SetKind {
/// The surface
surface: ShellSurface<R>,
/// Its new kind
kind: ShellSurfaceKind,
},
}
/// Shell global state
///
/// This state allows you to retrieve a list of surfaces
/// currently known to the shell global.
pub struct ShellState<R> {
known_surfaces: Vec<ShellSurface<R>>,
}
impl<R> ShellState<R>
where
R: Role<ShellSurfaceRole> +'static,
{
/// Cleans the internal surface storage by removing all dead surfaces
pub(crate) fn cleanup_surfaces(&mut self) {
self.known_surfaces.retain(|s| s.alive());
}
/// Access all the shell surfaces known by this handler
pub fn surfaces(&self) -> &[ShellSurface<R>] {
&self.known_surfaces[..]
}
}
/// Create a new `wl_shell` global
pub fn wl_shell_init<R, L, Impl>(
display: &mut Display,
ctoken: CompositorToken<R>,
implementation: Impl,
logger: L,
) -> (Arc<Mutex<ShellState<R>>>, Global<wl_shell::WlShell>)
where
R: Role<ShellSurfaceRole> +'static,
L: Into<Option<::slog::Logger>>,
Impl: FnMut(ShellRequest<R>) +'static,
{
let _log = crate::slog_or_stdlog(logger);
let implementation = Rc::new(RefCell::new(implementation));
let state = Arc::new(Mutex::new(ShellState {
known_surfaces: Vec::new(),
}));
let state2 = state.clone();
let global = display.create_global(1, move |shell, _version| {
self::wl_handlers::implement_shell(shell, ctoken, implementation.clone(), state2.clone());
});
(state, global)
}
| ShellSurface | identifier_name |
mod.rs | //! Utilities for handling shell surfaces with the `wl_shell` protocol
//!
//! This module provides automatic handling of shell surfaces objects, by being registered
//! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`,
//! thus this module is provided as a compatibility layer with older clients. As a consequence,
//! you can as a compositor-writer decide to only support its functionality in a best-effort
//! maneer: as this global is part of the core protocol, you are still required to provide
//! some support for it.
//!
//! ## Why use this implementation
//!
//! This implementation can track for you the various shell surfaces defined by the
//! clients by handling the `wl_shell` protocol.
//!
//! It allows you to easily access a list of all shell surfaces defined by your clients
//! access their associated metadata and underlying `wl_surface`s.
//!
//! This handler only handles the protocol exchanges with the client to present you the
//! information in a coherent and relatively easy to use manner. All the actual drawing
//! and positioning logic of windows is out of its scope.
//!
//! ## How to use it
//!
//! ### Initialization
//!
//! To initialize this handler, simple use the [`wl_shell_init`](::wayland::shell::legacy::wl_shell_init)
//! function provided in this module. You will need to provide it the [`CompositorToken`](::wayland::compositor::CompositorToken)
//! you retrieved from an instantiation of the compositor handler provided by smithay.
//!
//! ```no_run
//! # extern crate wayland_server;
//! # #[macro_use] extern crate smithay;
//! # extern crate wayland_protocols;
//! #
//! use smithay::wayland::compositor::roles::*;
//! use smithay::wayland::compositor::CompositorToken;
//! use smithay::wayland::shell::legacy::{wl_shell_init, ShellSurfaceRole, ShellRequest};
//! # use wayland_server::protocol::{wl_seat, wl_output};
//!
//! // define the roles type. You need to integrate the XdgSurface role:
//! define_roles!(MyRoles =>
//! [ShellSurface, ShellSurfaceRole]
//! );
//!
//! # fn main() {
//! # let mut event_loop = wayland_server::calloop::EventLoop::<()>::new().unwrap();
//! # let mut display = wayland_server::Display::new(event_loop.handle());
//! # let (compositor_token, _, _) = smithay::wayland::compositor::compositor_init::<MyRoles, _, _>(
//! # &mut display,
//! # |_, _, _| {},
//! # None
//! # );
//! let (shell_state, _) = wl_shell_init(
//! &mut display,
//! // token from the compositor implementation
//! compositor_token,
//! // your implementation
//! |event: ShellRequest<_>| { /*... */ },
//! None // put a logger if you want
//! );
//!
//! // You're now ready to go!
//! # }
//! ```
use std::{
cell::RefCell,
rc::Rc,
sync::{Arc, Mutex},
};
use crate::wayland::compositor::{roles::Role, CompositorToken};
use wayland_server::{
protocol::{wl_output, wl_seat, wl_shell, wl_shell_surface, wl_surface},
Display, Global,
};
mod wl_handlers;
/// Metadata associated with the `wl_surface` role
pub struct ShellSurfaceRole {
/// Title of the surface
pub title: String,
/// Class of the surface
pub class: String,
pending_ping: u32,
}
/// A handle to a shell surface
pub struct ShellSurface<R> {
wl_surface: wl_surface::WlSurface,
shell_surface: wl_shell_surface::WlShellSurface,
token: CompositorToken<R>,
}
impl<R> ShellSurface<R>
where
R: Role<ShellSurfaceRole> +'static,
{
/// Is the shell surface referred by this handle still alive?
pub fn alive(&self) -> bool {
self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive()
}
/// Do this handle and the other one actually refer to the same shell surface?
pub fn equals(&self, other: &Self) -> bool {
self.shell_surface.as_ref().equals(&other.shell_surface.as_ref())
}
/// Access the underlying `wl_surface` of this toplevel surface
///
/// Returns `None` if the toplevel surface actually no longer exists.
pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> {
if self.alive() {
Some(&self.wl_surface)
} else {
None
}
}
/// Send a ping request to this shell surface
///
/// You'll receive the reply as a [`ShellRequest::Pong`] request
///
/// A typical use is to start a timer at the same time you send this ping
/// request, and cancel it when you receive the pong. If the timer runs
/// down to 0 before a pong is received, mark the client as unresponsive.
///
/// Fails if this shell client already has a pending ping or is already dead.
pub fn send_ping(&self, serial: u32) -> Result<(), ()> {
if!self.alive() {
return Err(());
}
let ret = self.token.with_role_data(&self.wl_surface, |data| {
if data.pending_ping == 0 {
data.pending_ping = serial;
true
} else {
false
}
});
if let Ok(true) = ret | else {
Err(())
}
}
/// Send a configure event to this toplevel surface to suggest it a new configuration
pub fn send_configure(&self, size: (u32, u32), edges: wl_shell_surface::Resize) {
self.shell_surface.configure(edges, size.0 as i32, size.1 as i32)
}
/// Signal a popup surface that it has lost focus
pub fn send_popup_done(&self) {
self.shell_surface.popup_done()
}
}
/// Possible kinds of shell surface of the `wl_shell` protocol
pub enum ShellSurfaceKind {
/// Toplevel, a regular window displayed somewhere in the compositor space
Toplevel,
/// Transient, this surface has a parent surface
///
/// These are sub-windows of an application (for example a configuration window),
/// and as such should only be visible in their parent window is, and on top of it.
Transient {
/// The surface considered as parent
parent: wl_surface::WlSurface,
/// Location relative to the parent
location: (i32, i32),
/// Wether this window should be marked as inactive
inactive: bool,
},
/// Fullscreen surface, covering an entire output
Fullscreen {
/// Method used for fullscreen
method: wl_shell_surface::FullscreenMethod,
/// Framerate (relevant only for driver fullscreen)
framerate: u32,
/// Requested output if any
output: Option<wl_output::WlOutput>,
},
/// A popup surface
///
/// Short-lived surface, typically referred as "tooltips" in many
/// contexts.
Popup {
/// The parent surface of this popup
parent: wl_surface::WlSurface,
/// The serial of the input event triggering the creation of this
/// popup
serial: u32,
/// Wether this popup should be marked as inactive
inactive: bool,
/// Location of the popup relative to its parent
location: (i32, i32),
/// Seat associated this the input that triggered the creation of the
/// popup. Used to define when the "popup done" event is sent.
seat: wl_seat::WlSeat,
},
/// A maximized surface
///
/// Like a toplevel surface, but as big as possible on a single output
/// while keeping any relevant desktop-environment interface visible.
Maximized {
/// Requested output for maximization
output: Option<wl_output::WlOutput>,
},
}
/// A request triggered by a `wl_shell_surface`
pub enum ShellRequest<R> {
/// A new shell surface was created
///
/// by default it has no kind and this should not be displayed
NewShellSurface {
/// The created surface
surface: ShellSurface<R>,
},
/// A pong event
///
/// The surface responded to its pending ping. If you receive this
/// event, smithay has already checked that the responded serial was valid.
Pong {
/// The surface that sent the pong
surface: ShellSurface<R>,
},
/// Start of an interactive move
///
/// The surface requests that an interactive move is started on it
Move {
/// The surface requesting the move
surface: ShellSurface<R>,
/// Serial of the implicit grab that initiated the move
serial: u32,
/// Seat associated with the move
seat: wl_seat::WlSeat,
},
/// Start of an interactive resize
///
/// The surface requests that an interactive resize is started on it
Resize {
/// The surface requesting the resize
surface: ShellSurface<R>,
/// Serial of the implicit grab that initiated the resize
serial: u32,
/// Seat associated with the resize
seat: wl_seat::WlSeat,
/// Direction of the resize
edges: wl_shell_surface::Resize,
},
/// The surface changed its kind
SetKind {
/// The surface
surface: ShellSurface<R>,
/// Its new kind
kind: ShellSurfaceKind,
},
}
/// Shell global state
///
/// This state allows you to retrieve a list of surfaces
/// currently known to the shell global.
pub struct ShellState<R> {
known_surfaces: Vec<ShellSurface<R>>,
}
impl<R> ShellState<R>
where
R: Role<ShellSurfaceRole> +'static,
{
/// Cleans the internal surface storage by removing all dead surfaces
pub(crate) fn cleanup_surfaces(&mut self) {
self.known_surfaces.retain(|s| s.alive());
}
/// Access all the shell surfaces known by this handler
pub fn surfaces(&self) -> &[ShellSurface<R>] {
&self.known_surfaces[..]
}
}
/// Create a new `wl_shell` global
pub fn wl_shell_init<R, L, Impl>(
display: &mut Display,
ctoken: CompositorToken<R>,
implementation: Impl,
logger: L,
) -> (Arc<Mutex<ShellState<R>>>, Global<wl_shell::WlShell>)
where
R: Role<ShellSurfaceRole> +'static,
L: Into<Option<::slog::Logger>>,
Impl: FnMut(ShellRequest<R>) +'static,
{
let _log = crate::slog_or_stdlog(logger);
let implementation = Rc::new(RefCell::new(implementation));
let state = Arc::new(Mutex::new(ShellState {
known_surfaces: Vec::new(),
}));
let state2 = state.clone();
let global = display.create_global(1, move |shell, _version| {
self::wl_handlers::implement_shell(shell, ctoken, implementation.clone(), state2.clone());
});
(state, global)
}
| {
self.shell_surface.ping(serial);
Ok(())
} | conditional_block |
mod.rs | //! Utilities for handling shell surfaces with the `wl_shell` protocol
//!
//! This module provides automatic handling of shell surfaces objects, by being registered
//! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`,
//! thus this module is provided as a compatibility layer with older clients. As a consequence,
//! you can as a compositor-writer decide to only support its functionality in a best-effort
//! maneer: as this global is part of the core protocol, you are still required to provide
//! some support for it.
//!
//! ## Why use this implementation
//!
//! This implementation can track for you the various shell surfaces defined by the
//! clients by handling the `wl_shell` protocol.
//!
//! It allows you to easily access a list of all shell surfaces defined by your clients
//! access their associated metadata and underlying `wl_surface`s.
//!
//! This handler only handles the protocol exchanges with the client to present you the
//! information in a coherent and relatively easy to use manner. All the actual drawing
//! and positioning logic of windows is out of its scope.
//!
//! ## How to use it
//!
//! ### Initialization
//!
//! To initialize this handler, simple use the [`wl_shell_init`](::wayland::shell::legacy::wl_shell_init)
//! function provided in this module. You will need to provide it the [`CompositorToken`](::wayland::compositor::CompositorToken)
//! you retrieved from an instantiation of the compositor handler provided by smithay.
//!
//! ```no_run
//! # extern crate wayland_server;
//! # #[macro_use] extern crate smithay;
//! # extern crate wayland_protocols;
//! #
//! use smithay::wayland::compositor::roles::*;
//! use smithay::wayland::compositor::CompositorToken;
//! use smithay::wayland::shell::legacy::{wl_shell_init, ShellSurfaceRole, ShellRequest};
//! # use wayland_server::protocol::{wl_seat, wl_output};
//!
//! // define the roles type. You need to integrate the XdgSurface role:
//! define_roles!(MyRoles =>
//! [ShellSurface, ShellSurfaceRole]
//! );
//!
//! # fn main() {
//! # let mut event_loop = wayland_server::calloop::EventLoop::<()>::new().unwrap();
//! # let mut display = wayland_server::Display::new(event_loop.handle());
//! # let (compositor_token, _, _) = smithay::wayland::compositor::compositor_init::<MyRoles, _, _>(
//! # &mut display,
//! # |_, _, _| {},
//! # None
//! # );
//! let (shell_state, _) = wl_shell_init(
//! &mut display,
//! // token from the compositor implementation
//! compositor_token,
//! // your implementation
//! |event: ShellRequest<_>| { /*... */ },
//! None // put a logger if you want
//! );
//!
//! // You're now ready to go!
//! # }
//! ```
use std::{
cell::RefCell,
rc::Rc,
sync::{Arc, Mutex},
};
use crate::wayland::compositor::{roles::Role, CompositorToken};
use wayland_server::{
protocol::{wl_output, wl_seat, wl_shell, wl_shell_surface, wl_surface},
Display, Global,
};
mod wl_handlers;
/// Metadata associated with the `wl_surface` role
pub struct ShellSurfaceRole {
/// Title of the surface
pub title: String,
/// Class of the surface
pub class: String,
pending_ping: u32,
}
/// A handle to a shell surface
pub struct ShellSurface<R> {
wl_surface: wl_surface::WlSurface,
shell_surface: wl_shell_surface::WlShellSurface,
token: CompositorToken<R>,
}
impl<R> ShellSurface<R>
where
R: Role<ShellSurfaceRole> +'static,
{
/// Is the shell surface referred by this handle still alive?
pub fn alive(&self) -> bool {
self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive()
}
/// Do this handle and the other one actually refer to the same shell surface?
pub fn equals(&self, other: &Self) -> bool {
self.shell_surface.as_ref().equals(&other.shell_surface.as_ref())
}
/// Access the underlying `wl_surface` of this toplevel surface
///
/// Returns `None` if the toplevel surface actually no longer exists.
pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> {
if self.alive() {
Some(&self.wl_surface)
} else {
None
} | ///
/// You'll receive the reply as a [`ShellRequest::Pong`] request
///
/// A typical use is to start a timer at the same time you send this ping
/// request, and cancel it when you receive the pong. If the timer runs
/// down to 0 before a pong is received, mark the client as unresponsive.
///
/// Fails if this shell client already has a pending ping or is already dead.
pub fn send_ping(&self, serial: u32) -> Result<(), ()> {
if!self.alive() {
return Err(());
}
let ret = self.token.with_role_data(&self.wl_surface, |data| {
if data.pending_ping == 0 {
data.pending_ping = serial;
true
} else {
false
}
});
if let Ok(true) = ret {
self.shell_surface.ping(serial);
Ok(())
} else {
Err(())
}
}
/// Send a configure event to this toplevel surface to suggest it a new configuration
pub fn send_configure(&self, size: (u32, u32), edges: wl_shell_surface::Resize) {
self.shell_surface.configure(edges, size.0 as i32, size.1 as i32)
}
/// Signal a popup surface that it has lost focus
pub fn send_popup_done(&self) {
self.shell_surface.popup_done()
}
}
/// Possible kinds of shell surface of the `wl_shell` protocol
pub enum ShellSurfaceKind {
/// Toplevel, a regular window displayed somewhere in the compositor space
Toplevel,
/// Transient, this surface has a parent surface
///
/// These are sub-windows of an application (for example a configuration window),
/// and as such should only be visible in their parent window is, and on top of it.
Transient {
/// The surface considered as parent
parent: wl_surface::WlSurface,
/// Location relative to the parent
location: (i32, i32),
/// Wether this window should be marked as inactive
inactive: bool,
},
/// Fullscreen surface, covering an entire output
Fullscreen {
/// Method used for fullscreen
method: wl_shell_surface::FullscreenMethod,
/// Framerate (relevant only for driver fullscreen)
framerate: u32,
/// Requested output if any
output: Option<wl_output::WlOutput>,
},
/// A popup surface
///
/// Short-lived surface, typically referred as "tooltips" in many
/// contexts.
Popup {
/// The parent surface of this popup
parent: wl_surface::WlSurface,
/// The serial of the input event triggering the creation of this
/// popup
serial: u32,
/// Wether this popup should be marked as inactive
inactive: bool,
/// Location of the popup relative to its parent
location: (i32, i32),
/// Seat associated this the input that triggered the creation of the
/// popup. Used to define when the "popup done" event is sent.
seat: wl_seat::WlSeat,
},
/// A maximized surface
///
/// Like a toplevel surface, but as big as possible on a single output
/// while keeping any relevant desktop-environment interface visible.
Maximized {
/// Requested output for maximization
output: Option<wl_output::WlOutput>,
},
}
/// A request triggered by a `wl_shell_surface`
pub enum ShellRequest<R> {
/// A new shell surface was created
///
/// by default it has no kind and this should not be displayed
NewShellSurface {
/// The created surface
surface: ShellSurface<R>,
},
/// A pong event
///
/// The surface responded to its pending ping. If you receive this
/// event, smithay has already checked that the responded serial was valid.
Pong {
/// The surface that sent the pong
surface: ShellSurface<R>,
},
/// Start of an interactive move
///
/// The surface requests that an interactive move is started on it
Move {
/// The surface requesting the move
surface: ShellSurface<R>,
/// Serial of the implicit grab that initiated the move
serial: u32,
/// Seat associated with the move
seat: wl_seat::WlSeat,
},
/// Start of an interactive resize
///
/// The surface requests that an interactive resize is started on it
Resize {
/// The surface requesting the resize
surface: ShellSurface<R>,
/// Serial of the implicit grab that initiated the resize
serial: u32,
/// Seat associated with the resize
seat: wl_seat::WlSeat,
/// Direction of the resize
edges: wl_shell_surface::Resize,
},
/// The surface changed its kind
SetKind {
/// The surface
surface: ShellSurface<R>,
/// Its new kind
kind: ShellSurfaceKind,
},
}
/// Shell global state
///
/// This state allows you to retrieve a list of surfaces
/// currently known to the shell global.
pub struct ShellState<R> {
known_surfaces: Vec<ShellSurface<R>>,
}
impl<R> ShellState<R>
where
R: Role<ShellSurfaceRole> +'static,
{
/// Cleans the internal surface storage by removing all dead surfaces
pub(crate) fn cleanup_surfaces(&mut self) {
self.known_surfaces.retain(|s| s.alive());
}
/// Access all the shell surfaces known by this handler
pub fn surfaces(&self) -> &[ShellSurface<R>] {
&self.known_surfaces[..]
}
}
/// Create a new `wl_shell` global
pub fn wl_shell_init<R, L, Impl>(
display: &mut Display,
ctoken: CompositorToken<R>,
implementation: Impl,
logger: L,
) -> (Arc<Mutex<ShellState<R>>>, Global<wl_shell::WlShell>)
where
R: Role<ShellSurfaceRole> +'static,
L: Into<Option<::slog::Logger>>,
Impl: FnMut(ShellRequest<R>) +'static,
{
let _log = crate::slog_or_stdlog(logger);
let implementation = Rc::new(RefCell::new(implementation));
let state = Arc::new(Mutex::new(ShellState {
known_surfaces: Vec::new(),
}));
let state2 = state.clone();
let global = display.create_global(1, move |shell, _version| {
self::wl_handlers::implement_shell(shell, ctoken, implementation.clone(), state2.clone());
});
(state, global)
} | }
/// Send a ping request to this shell surface | random_line_split |
edid.rs | // Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Implementation of the EDID specification provided by software.
//! EDID spec: <https://glenwing.github.io/docs/VESA-EEDID-A2.pdf>
use std::fmt;
use std::fmt::Debug;
use super::protocol::GpuResponse::*;
use super::protocol::VirtioGpuResult;
const EDID_DATA_LENGTH: usize = 128;
const DEFAULT_HORIZONTAL_BLANKING: u16 = 560;
const DEFAULT_VERTICAL_BLANKING: u16 = 50;
const DEFAULT_HORIZONTAL_FRONT_PORCH: u16 = 64;
const DEFAULT_VERTICAL_FRONT_PORCH: u16 = 1;
const DEFAULT_HORIZONTAL_SYNC_PULSE: u16 = 192;
const DEFAULT_VERTICAL_SYNC_PULSE: u16 = 3;
/// This class is used to create the Extended Display Identification Data (EDID), which will be
/// exposed to the guest system.
///
/// We ignore most of the spec, the point here being for us to provide enough for graphics to work
/// and to allow us to configure the resolution and refresh rate (via the preferred timing mode
/// pixel clock).
///
/// The EDID spec defines a number of methods to provide mode information, but in priority order the
/// "detailed" timing information is first, so we provide a single block of detailed timing
/// information and no other form of timing information.
#[repr(C)]
pub struct EdidBytes {
bytes: [u8; EDID_DATA_LENGTH],
}
impl EdidBytes {
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
}
impl Debug for EdidBytes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.bytes[..].fmt(f)
}
}
impl PartialEq for EdidBytes {
fn eq(&self, other: &EdidBytes) -> bool {
self.bytes[..] == other.bytes[..]
}
}
#[derive(Copy, Clone)]
pub struct Resolution {
width: u32,
height: u32,
}
impl Resolution {
fn new(width: u32, height: u32) -> Resolution {
Resolution { width, height }
}
fn get_aspect_ratio(&self) -> (u32, u32) {
let divisor = gcd(self.width, self.height);
(self.width / divisor, self.height / divisor)
}
}
fn gcd(x: u32, y: u32) -> u32 {
match y {
0 => x,
_ => gcd(y, x % y),
}
}
#[derive(Copy, Clone)]
pub struct DisplayInfo {
resolution: Resolution,
refresh_rate: u32,
horizontal_blanking: u16,
vertical_blanking: u16,
horizontal_front: u16,
vertical_front: u16,
horizontal_sync: u16,
vertical_sync: u16,
}
impl DisplayInfo {
/// Only width, height and refresh rate are required for the graphics stack to work, so instead
/// of pulling actual numbers from the system, we just use some typical values to populate other
/// fields for now.
pub fn new(width: u32, height: u32, refresh_rate: u32) -> Self {
Self {
resolution: Resolution::new(width, height),
refresh_rate,
horizontal_blanking: DEFAULT_HORIZONTAL_BLANKING,
vertical_blanking: DEFAULT_VERTICAL_BLANKING,
horizontal_front: DEFAULT_HORIZONTAL_FRONT_PORCH,
vertical_front: DEFAULT_VERTICAL_FRONT_PORCH,
horizontal_sync: DEFAULT_HORIZONTAL_SYNC_PULSE,
vertical_sync: DEFAULT_VERTICAL_SYNC_PULSE,
}
}
pub fn width(&self) -> u32 {
self.resolution.width
}
pub fn height(&self) -> u32 {
self.resolution.height
}
}
impl EdidBytes {
/// Creates a virtual EDID block.
pub fn new(info: &DisplayInfo) -> VirtioGpuResult {
let mut edid: [u8; EDID_DATA_LENGTH] = [0; EDID_DATA_LENGTH];
populate_header(&mut edid);
populate_edid_version(&mut edid);
populate_standard_timings(&mut edid)?;
// 4 available descriptor blocks
let block0 = &mut edid[54..72];
populate_detailed_timing(block0, info);
let block1 = &mut edid[72..90];
populate_display_name(block1);
calculate_checksum(&mut edid);
Ok(OkEdid(Self { bytes: edid }))
}
}
fn populate_display_name(edid_block: &mut [u8]) {
// Display Product Name String Descriptor Tag
edid_block[0..5].clone_from_slice(&[0x00, 0x00, 0x00, 0xFC, 0x00]);
edid_block[5..].clone_from_slice("CrosvmDisplay".as_bytes());
}
fn populate_detailed_timing(edid_block: &mut [u8], info: &DisplayInfo) {
assert_eq!(edid_block.len(), 18);
// Detailed timings
//
// 18 Byte Descriptors - 72 Bytes
// The 72 bytes in this section are divided into four data fields. Each of the four data fields
// are 18 bytes in length. These 18 byte data fields shall contain either detailed timing data
// as described in Section 3.10.2 or other types of data as described in Section 3.10.3. The
// addresses and the contents of the four 18 byte descriptors are shown in Table 3.20.
//
// We leave the bottom 6 bytes of this block purposefully empty.
let horizontal_blanking_lsb: u8 = (info.horizontal_blanking & 0xFF) as u8;
let horizontal_blanking_msb: u8 = ((info.horizontal_blanking >> 8) & 0x0F) as u8;
let vertical_blanking_lsb: u8 = (info.vertical_blanking & 0xFF) as u8;
let vertical_blanking_msb: u8 = ((info.vertical_blanking >> 8) & 0x0F) as u8;
// The pixel clock is what controls the refresh timing information.
//
// The formula for getting refresh rate out of this value is:
// refresh_rate = clk * 10000 / (htotal * vtotal)
// Solving for clk:
// clk = (refresh_rate * htotal * votal) / 10000
//
// where:
// clk - The setting here
// vtotal - Total lines
// htotal - Total pixels per line
//
// Value here is pixel clock + 10,000, in 10khz steps.
//
// Pseudocode of kernel logic for vrefresh:
// vtotal := mode->vtotal;
// calc_val := (clock * 1000) / htotal
// refresh := (calc_val + vtotal / 2) / vtotal
// if flags & INTERLACE: refresh *= 2
// if flags & DBLSCAN: refresh /= 2
// if vscan > 1: refresh /= vscan
//
let htotal = info.width() + (info.horizontal_blanking as u32);
let vtotal = info.height() + (info.vertical_blanking as u32);
let mut clock: u16 = ((info.refresh_rate * htotal * vtotal) / 10000) as u16;
// Round to nearest 10khz.
clock = ((clock + 5) / 10) * 10;
edid_block[0..2].copy_from_slice(&clock.to_le_bytes());
let width_lsb: u8 = (info.width() & 0xFF) as u8;
let width_msb: u8 = ((info.width() >> 8) & 0x0F) as u8;
// Horizointal Addressable Video in pixels.
edid_block[2] = width_lsb;
// Horizontal blanking in pixels.
edid_block[3] = horizontal_blanking_lsb;
// Upper bits of the two above vals.
edid_block[4] = horizontal_blanking_msb | (width_msb << 4) as u8;
let vertical_active: u32 = info.height();
let vertical_active_lsb: u8 = (vertical_active & 0xFF) as u8;
let vertical_active_msb: u8 = ((vertical_active >> 8) & 0x0F) as u8;
// Vertical addressable video in *lines*
edid_block[5] = vertical_active_lsb;
// Vertical blanking in lines
edid_block[6] = vertical_blanking_lsb;
// Sigbits of the above.
edid_block[7] = vertical_blanking_msb | (vertical_active_msb << 4);
let horizontal_front_lsb: u8 = (info.horizontal_front & 0xFF) as u8; // least sig 8 bits
let horizontal_front_msb: u8 = ((info.horizontal_front >> 8) & 0x03) as u8; // most sig 2 bits
let horizontal_sync_lsb: u8 = (info.horizontal_sync & 0xFF) as u8; // least sig 8 bits
let horizontal_sync_msb: u8 = ((info.horizontal_sync >> 8) & 0x03) as u8; // most sig 2 bits
let vertical_front_lsb: u8 = (info.vertical_front & 0x0F) as u8; // least sig 4 bits
let vertical_front_msb: u8 = ((info.vertical_front >> 8) & 0x0F) as u8; // most sig 2 bits
let vertical_sync_lsb: u8 = (info.vertical_sync & 0xFF) as u8; // least sig 4 bits
let vertical_sync_msb: u8 = ((info.vertical_sync >> 8) & 0x0F) as u8; // most sig 2 bits
// Horizontal front porch in pixels.
edid_block[8] = horizontal_front_lsb;
// Horizontal sync pulse width in pixels.
edid_block[9] = horizontal_sync_lsb;
// LSB of vertical front porch and sync pulse
edid_block[10] = vertical_sync_lsb | (vertical_front_lsb << 4);
// Upper 2 bits of these values.
edid_block[11] = vertical_sync_msb
| (vertical_front_msb << 2)
| (horizontal_sync_msb << 4)
| (horizontal_front_msb << 6);
}
// The EDID header. This is defined by the EDID spec.
fn populate_header(edid: &mut [u8]) {
edid[0] = 0x00;
edid[1] = 0xFF;
edid[2] = 0xFF;
edid[3] = 0xFF;
edid[4] = 0xFF;
edid[5] = 0xFF;
edid[6] = 0xFF;
edid[7] = 0x00;
let manufacturer_name: [char; 3] = ['G', 'G', 'L'];
// 00001 -> A, 00010 -> B, etc
let manufacturer_id: u16 = manufacturer_name
.iter()
.map(|c| (*c as u8 - b'A' + 1) & 0x1F)
.fold(0u16, |res, lsb| (res << 5) | (lsb as u16));
edid[8..10].copy_from_slice(&manufacturer_id.to_be_bytes());
let manufacture_product_id: u16 = 1;
edid[10..12].copy_from_slice(&manufacture_product_id.to_le_bytes());
let serial_id: u32 = 1;
edid[12..16].copy_from_slice(&serial_id.to_le_bytes());
let manufacture_week: u8 = 8;
edid[16] = manufacture_week;
let manufacture_year: u32 = 2022;
edid[17] = (manufacture_year - 1990u32) as u8;
}
// The standard timings are 8 timing modes with a lower priority (and different data format)
// than the 4 detailed timing modes.
fn populate_standard_timings(edid: &mut [u8]) -> VirtioGpuResult {
let resolutions = [
Resolution::new(1440, 900),
Resolution::new(1600, 900),
Resolution::new(800, 600),
Resolution::new(1680, 1050),
Resolution::new(1856, 1392),
Resolution::new(1280, 1024),
Resolution::new(1400, 1050),
Resolution::new(1920, 1200),
];
// Index 0 is horizontal pixels / 8 - 31
// Index 1 is a combination of the refresh_rate - 60 (so we are setting to 0, for now) and two
// bits for the aspect ratio.
for (index, r) in resolutions.iter().enumerate() {
edid[0x26 + (index * 2)] = (r.width / 8 - 31) as u8;
let ar_bits = match r.get_aspect_ratio() {
(8, 5) => 0x0,
(4, 3) => 0x1,
(5, 4) => 0x2,
(16, 9) => 0x3,
(x, y) => return Err(ErrEdid(format!("Unsupported aspect ratio: {} {}", x, y))),
};
edid[0x27 + (index * 2)] = ar_bits;
}
Ok(OkNoData)
}
// Per the EDID spec, needs to be 1 and 4.
fn populate_edid_version(edid: &mut [u8]) |
fn calculate_checksum(edid: &mut [u8]) {
let mut checksum: u8 = 0;
for byte in edid.iter().take(EDID_DATA_LENGTH - 1) {
checksum = checksum.wrapping_add(*byte);
}
if checksum!= 0 {
checksum = 255 - checksum + 1;
}
edid[127] = checksum;
}
| {
edid[18] = 1;
edid[19] = 4;
} | identifier_body |
edid.rs | // Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Implementation of the EDID specification provided by software.
//! EDID spec: <https://glenwing.github.io/docs/VESA-EEDID-A2.pdf>
use std::fmt;
use std::fmt::Debug;
use super::protocol::GpuResponse::*;
use super::protocol::VirtioGpuResult;
const EDID_DATA_LENGTH: usize = 128;
const DEFAULT_HORIZONTAL_BLANKING: u16 = 560;
const DEFAULT_VERTICAL_BLANKING: u16 = 50;
const DEFAULT_HORIZONTAL_FRONT_PORCH: u16 = 64;
const DEFAULT_VERTICAL_FRONT_PORCH: u16 = 1;
const DEFAULT_HORIZONTAL_SYNC_PULSE: u16 = 192;
const DEFAULT_VERTICAL_SYNC_PULSE: u16 = 3;
/// This class is used to create the Extended Display Identification Data (EDID), which will be
/// exposed to the guest system.
///
/// We ignore most of the spec, the point here being for us to provide enough for graphics to work
/// and to allow us to configure the resolution and refresh rate (via the preferred timing mode
/// pixel clock).
///
/// The EDID spec defines a number of methods to provide mode information, but in priority order the
/// "detailed" timing information is first, so we provide a single block of detailed timing
/// information and no other form of timing information.
#[repr(C)]
pub struct EdidBytes {
bytes: [u8; EDID_DATA_LENGTH],
}
impl EdidBytes {
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
}
impl Debug for EdidBytes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.bytes[..].fmt(f)
}
}
impl PartialEq for EdidBytes {
fn eq(&self, other: &EdidBytes) -> bool {
self.bytes[..] == other.bytes[..]
}
}
#[derive(Copy, Clone)]
pub struct Resolution {
width: u32,
height: u32,
}
impl Resolution {
fn | (width: u32, height: u32) -> Resolution {
Resolution { width, height }
}
fn get_aspect_ratio(&self) -> (u32, u32) {
let divisor = gcd(self.width, self.height);
(self.width / divisor, self.height / divisor)
}
}
fn gcd(x: u32, y: u32) -> u32 {
match y {
0 => x,
_ => gcd(y, x % y),
}
}
#[derive(Copy, Clone)]
pub struct DisplayInfo {
resolution: Resolution,
refresh_rate: u32,
horizontal_blanking: u16,
vertical_blanking: u16,
horizontal_front: u16,
vertical_front: u16,
horizontal_sync: u16,
vertical_sync: u16,
}
impl DisplayInfo {
/// Only width, height and refresh rate are required for the graphics stack to work, so instead
/// of pulling actual numbers from the system, we just use some typical values to populate other
/// fields for now.
pub fn new(width: u32, height: u32, refresh_rate: u32) -> Self {
Self {
resolution: Resolution::new(width, height),
refresh_rate,
horizontal_blanking: DEFAULT_HORIZONTAL_BLANKING,
vertical_blanking: DEFAULT_VERTICAL_BLANKING,
horizontal_front: DEFAULT_HORIZONTAL_FRONT_PORCH,
vertical_front: DEFAULT_VERTICAL_FRONT_PORCH,
horizontal_sync: DEFAULT_HORIZONTAL_SYNC_PULSE,
vertical_sync: DEFAULT_VERTICAL_SYNC_PULSE,
}
}
pub fn width(&self) -> u32 {
self.resolution.width
}
pub fn height(&self) -> u32 {
self.resolution.height
}
}
impl EdidBytes {
/// Creates a virtual EDID block.
pub fn new(info: &DisplayInfo) -> VirtioGpuResult {
let mut edid: [u8; EDID_DATA_LENGTH] = [0; EDID_DATA_LENGTH];
populate_header(&mut edid);
populate_edid_version(&mut edid);
populate_standard_timings(&mut edid)?;
// 4 available descriptor blocks
let block0 = &mut edid[54..72];
populate_detailed_timing(block0, info);
let block1 = &mut edid[72..90];
populate_display_name(block1);
calculate_checksum(&mut edid);
Ok(OkEdid(Self { bytes: edid }))
}
}
fn populate_display_name(edid_block: &mut [u8]) {
// Display Product Name String Descriptor Tag
edid_block[0..5].clone_from_slice(&[0x00, 0x00, 0x00, 0xFC, 0x00]);
edid_block[5..].clone_from_slice("CrosvmDisplay".as_bytes());
}
fn populate_detailed_timing(edid_block: &mut [u8], info: &DisplayInfo) {
assert_eq!(edid_block.len(), 18);
// Detailed timings
//
// 18 Byte Descriptors - 72 Bytes
// The 72 bytes in this section are divided into four data fields. Each of the four data fields
// are 18 bytes in length. These 18 byte data fields shall contain either detailed timing data
// as described in Section 3.10.2 or other types of data as described in Section 3.10.3. The
// addresses and the contents of the four 18 byte descriptors are shown in Table 3.20.
//
// We leave the bottom 6 bytes of this block purposefully empty.
let horizontal_blanking_lsb: u8 = (info.horizontal_blanking & 0xFF) as u8;
let horizontal_blanking_msb: u8 = ((info.horizontal_blanking >> 8) & 0x0F) as u8;
let vertical_blanking_lsb: u8 = (info.vertical_blanking & 0xFF) as u8;
let vertical_blanking_msb: u8 = ((info.vertical_blanking >> 8) & 0x0F) as u8;
// The pixel clock is what controls the refresh timing information.
//
// The formula for getting refresh rate out of this value is:
// refresh_rate = clk * 10000 / (htotal * vtotal)
// Solving for clk:
// clk = (refresh_rate * htotal * votal) / 10000
//
// where:
// clk - The setting here
// vtotal - Total lines
// htotal - Total pixels per line
//
// Value here is pixel clock + 10,000, in 10khz steps.
//
// Pseudocode of kernel logic for vrefresh:
// vtotal := mode->vtotal;
// calc_val := (clock * 1000) / htotal
// refresh := (calc_val + vtotal / 2) / vtotal
// if flags & INTERLACE: refresh *= 2
// if flags & DBLSCAN: refresh /= 2
// if vscan > 1: refresh /= vscan
//
let htotal = info.width() + (info.horizontal_blanking as u32);
let vtotal = info.height() + (info.vertical_blanking as u32);
let mut clock: u16 = ((info.refresh_rate * htotal * vtotal) / 10000) as u16;
// Round to nearest 10khz.
clock = ((clock + 5) / 10) * 10;
edid_block[0..2].copy_from_slice(&clock.to_le_bytes());
let width_lsb: u8 = (info.width() & 0xFF) as u8;
let width_msb: u8 = ((info.width() >> 8) & 0x0F) as u8;
// Horizointal Addressable Video in pixels.
edid_block[2] = width_lsb;
// Horizontal blanking in pixels.
edid_block[3] = horizontal_blanking_lsb;
// Upper bits of the two above vals.
edid_block[4] = horizontal_blanking_msb | (width_msb << 4) as u8;
let vertical_active: u32 = info.height();
let vertical_active_lsb: u8 = (vertical_active & 0xFF) as u8;
let vertical_active_msb: u8 = ((vertical_active >> 8) & 0x0F) as u8;
// Vertical addressable video in *lines*
edid_block[5] = vertical_active_lsb;
// Vertical blanking in lines
edid_block[6] = vertical_blanking_lsb;
// Sigbits of the above.
edid_block[7] = vertical_blanking_msb | (vertical_active_msb << 4);
let horizontal_front_lsb: u8 = (info.horizontal_front & 0xFF) as u8; // least sig 8 bits
let horizontal_front_msb: u8 = ((info.horizontal_front >> 8) & 0x03) as u8; // most sig 2 bits
let horizontal_sync_lsb: u8 = (info.horizontal_sync & 0xFF) as u8; // least sig 8 bits
let horizontal_sync_msb: u8 = ((info.horizontal_sync >> 8) & 0x03) as u8; // most sig 2 bits
let vertical_front_lsb: u8 = (info.vertical_front & 0x0F) as u8; // least sig 4 bits
let vertical_front_msb: u8 = ((info.vertical_front >> 8) & 0x0F) as u8; // most sig 2 bits
let vertical_sync_lsb: u8 = (info.vertical_sync & 0xFF) as u8; // least sig 4 bits
let vertical_sync_msb: u8 = ((info.vertical_sync >> 8) & 0x0F) as u8; // most sig 2 bits
// Horizontal front porch in pixels.
edid_block[8] = horizontal_front_lsb;
// Horizontal sync pulse width in pixels.
edid_block[9] = horizontal_sync_lsb;
// LSB of vertical front porch and sync pulse
edid_block[10] = vertical_sync_lsb | (vertical_front_lsb << 4);
// Upper 2 bits of these values.
edid_block[11] = vertical_sync_msb
| (vertical_front_msb << 2)
| (horizontal_sync_msb << 4)
| (horizontal_front_msb << 6);
}
// The EDID header. This is defined by the EDID spec.
fn populate_header(edid: &mut [u8]) {
edid[0] = 0x00;
edid[1] = 0xFF;
edid[2] = 0xFF;
edid[3] = 0xFF;
edid[4] = 0xFF;
edid[5] = 0xFF;
edid[6] = 0xFF;
edid[7] = 0x00;
let manufacturer_name: [char; 3] = ['G', 'G', 'L'];
// 00001 -> A, 00010 -> B, etc
let manufacturer_id: u16 = manufacturer_name
.iter()
.map(|c| (*c as u8 - b'A' + 1) & 0x1F)
.fold(0u16, |res, lsb| (res << 5) | (lsb as u16));
edid[8..10].copy_from_slice(&manufacturer_id.to_be_bytes());
let manufacture_product_id: u16 = 1;
edid[10..12].copy_from_slice(&manufacture_product_id.to_le_bytes());
let serial_id: u32 = 1;
edid[12..16].copy_from_slice(&serial_id.to_le_bytes());
let manufacture_week: u8 = 8;
edid[16] = manufacture_week;
let manufacture_year: u32 = 2022;
edid[17] = (manufacture_year - 1990u32) as u8;
}
// The standard timings are 8 timing modes with a lower priority (and different data format)
// than the 4 detailed timing modes.
fn populate_standard_timings(edid: &mut [u8]) -> VirtioGpuResult {
let resolutions = [
Resolution::new(1440, 900),
Resolution::new(1600, 900),
Resolution::new(800, 600),
Resolution::new(1680, 1050),
Resolution::new(1856, 1392),
Resolution::new(1280, 1024),
Resolution::new(1400, 1050),
Resolution::new(1920, 1200),
];
// Index 0 is horizontal pixels / 8 - 31
// Index 1 is a combination of the refresh_rate - 60 (so we are setting to 0, for now) and two
// bits for the aspect ratio.
for (index, r) in resolutions.iter().enumerate() {
edid[0x26 + (index * 2)] = (r.width / 8 - 31) as u8;
let ar_bits = match r.get_aspect_ratio() {
(8, 5) => 0x0,
(4, 3) => 0x1,
(5, 4) => 0x2,
(16, 9) => 0x3,
(x, y) => return Err(ErrEdid(format!("Unsupported aspect ratio: {} {}", x, y))),
};
edid[0x27 + (index * 2)] = ar_bits;
}
Ok(OkNoData)
}
// Per the EDID spec, needs to be 1 and 4.
fn populate_edid_version(edid: &mut [u8]) {
edid[18] = 1;
edid[19] = 4;
}
fn calculate_checksum(edid: &mut [u8]) {
let mut checksum: u8 = 0;
for byte in edid.iter().take(EDID_DATA_LENGTH - 1) {
checksum = checksum.wrapping_add(*byte);
}
if checksum!= 0 {
checksum = 255 - checksum + 1;
}
edid[127] = checksum;
}
| new | identifier_name |
edid.rs | // Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Implementation of the EDID specification provided by software.
//! EDID spec: <https://glenwing.github.io/docs/VESA-EEDID-A2.pdf>
use std::fmt;
use std::fmt::Debug;
use super::protocol::GpuResponse::*;
use super::protocol::VirtioGpuResult;
const EDID_DATA_LENGTH: usize = 128;
const DEFAULT_HORIZONTAL_BLANKING: u16 = 560;
const DEFAULT_VERTICAL_BLANKING: u16 = 50;
const DEFAULT_HORIZONTAL_FRONT_PORCH: u16 = 64;
const DEFAULT_VERTICAL_FRONT_PORCH: u16 = 1;
const DEFAULT_HORIZONTAL_SYNC_PULSE: u16 = 192;
const DEFAULT_VERTICAL_SYNC_PULSE: u16 = 3;
/// This class is used to create the Extended Display Identification Data (EDID), which will be
/// exposed to the guest system.
///
/// We ignore most of the spec, the point here being for us to provide enough for graphics to work
/// and to allow us to configure the resolution and refresh rate (via the preferred timing mode
/// pixel clock).
///
/// The EDID spec defines a number of methods to provide mode information, but in priority order the
/// "detailed" timing information is first, so we provide a single block of detailed timing
/// information and no other form of timing information.
#[repr(C)]
pub struct EdidBytes {
bytes: [u8; EDID_DATA_LENGTH],
}
impl EdidBytes {
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
}
impl Debug for EdidBytes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.bytes[..].fmt(f)
}
}
impl PartialEq for EdidBytes {
fn eq(&self, other: &EdidBytes) -> bool {
self.bytes[..] == other.bytes[..]
}
}
#[derive(Copy, Clone)]
pub struct Resolution {
width: u32,
height: u32,
}
impl Resolution {
fn new(width: u32, height: u32) -> Resolution {
Resolution { width, height }
}
fn get_aspect_ratio(&self) -> (u32, u32) {
let divisor = gcd(self.width, self.height);
(self.width / divisor, self.height / divisor)
}
}
fn gcd(x: u32, y: u32) -> u32 {
match y {
0 => x,
_ => gcd(y, x % y),
}
}
#[derive(Copy, Clone)]
pub struct DisplayInfo {
resolution: Resolution,
refresh_rate: u32,
horizontal_blanking: u16,
vertical_blanking: u16,
horizontal_front: u16,
vertical_front: u16,
horizontal_sync: u16,
vertical_sync: u16,
}
impl DisplayInfo {
/// Only width, height and refresh rate are required for the graphics stack to work, so instead
/// of pulling actual numbers from the system, we just use some typical values to populate other
/// fields for now.
pub fn new(width: u32, height: u32, refresh_rate: u32) -> Self {
Self {
resolution: Resolution::new(width, height),
refresh_rate,
horizontal_blanking: DEFAULT_HORIZONTAL_BLANKING,
vertical_blanking: DEFAULT_VERTICAL_BLANKING,
horizontal_front: DEFAULT_HORIZONTAL_FRONT_PORCH,
vertical_front: DEFAULT_VERTICAL_FRONT_PORCH,
horizontal_sync: DEFAULT_HORIZONTAL_SYNC_PULSE,
vertical_sync: DEFAULT_VERTICAL_SYNC_PULSE,
}
}
pub fn width(&self) -> u32 {
self.resolution.width
}
pub fn height(&self) -> u32 {
self.resolution.height
}
}
impl EdidBytes {
/// Creates a virtual EDID block.
pub fn new(info: &DisplayInfo) -> VirtioGpuResult {
let mut edid: [u8; EDID_DATA_LENGTH] = [0; EDID_DATA_LENGTH];
populate_header(&mut edid);
populate_edid_version(&mut edid);
populate_standard_timings(&mut edid)?;
// 4 available descriptor blocks
let block0 = &mut edid[54..72];
populate_detailed_timing(block0, info);
let block1 = &mut edid[72..90];
populate_display_name(block1);
| }
}
fn populate_display_name(edid_block: &mut [u8]) {
// Display Product Name String Descriptor Tag
edid_block[0..5].clone_from_slice(&[0x00, 0x00, 0x00, 0xFC, 0x00]);
edid_block[5..].clone_from_slice("CrosvmDisplay".as_bytes());
}
fn populate_detailed_timing(edid_block: &mut [u8], info: &DisplayInfo) {
assert_eq!(edid_block.len(), 18);
// Detailed timings
//
// 18 Byte Descriptors - 72 Bytes
// The 72 bytes in this section are divided into four data fields. Each of the four data fields
// are 18 bytes in length. These 18 byte data fields shall contain either detailed timing data
// as described in Section 3.10.2 or other types of data as described in Section 3.10.3. The
// addresses and the contents of the four 18 byte descriptors are shown in Table 3.20.
//
// We leave the bottom 6 bytes of this block purposefully empty.
let horizontal_blanking_lsb: u8 = (info.horizontal_blanking & 0xFF) as u8;
let horizontal_blanking_msb: u8 = ((info.horizontal_blanking >> 8) & 0x0F) as u8;
let vertical_blanking_lsb: u8 = (info.vertical_blanking & 0xFF) as u8;
let vertical_blanking_msb: u8 = ((info.vertical_blanking >> 8) & 0x0F) as u8;
// The pixel clock is what controls the refresh timing information.
//
// The formula for getting refresh rate out of this value is:
// refresh_rate = clk * 10000 / (htotal * vtotal)
// Solving for clk:
// clk = (refresh_rate * htotal * votal) / 10000
//
// where:
// clk - The setting here
// vtotal - Total lines
// htotal - Total pixels per line
//
// Value here is pixel clock + 10,000, in 10khz steps.
//
// Pseudocode of kernel logic for vrefresh:
// vtotal := mode->vtotal;
// calc_val := (clock * 1000) / htotal
// refresh := (calc_val + vtotal / 2) / vtotal
// if flags & INTERLACE: refresh *= 2
// if flags & DBLSCAN: refresh /= 2
// if vscan > 1: refresh /= vscan
//
let htotal = info.width() + (info.horizontal_blanking as u32);
let vtotal = info.height() + (info.vertical_blanking as u32);
let mut clock: u16 = ((info.refresh_rate * htotal * vtotal) / 10000) as u16;
// Round to nearest 10khz.
clock = ((clock + 5) / 10) * 10;
edid_block[0..2].copy_from_slice(&clock.to_le_bytes());
let width_lsb: u8 = (info.width() & 0xFF) as u8;
let width_msb: u8 = ((info.width() >> 8) & 0x0F) as u8;
// Horizointal Addressable Video in pixels.
edid_block[2] = width_lsb;
// Horizontal blanking in pixels.
edid_block[3] = horizontal_blanking_lsb;
// Upper bits of the two above vals.
edid_block[4] = horizontal_blanking_msb | (width_msb << 4) as u8;
let vertical_active: u32 = info.height();
let vertical_active_lsb: u8 = (vertical_active & 0xFF) as u8;
let vertical_active_msb: u8 = ((vertical_active >> 8) & 0x0F) as u8;
// Vertical addressable video in *lines*
edid_block[5] = vertical_active_lsb;
// Vertical blanking in lines
edid_block[6] = vertical_blanking_lsb;
// Sigbits of the above.
edid_block[7] = vertical_blanking_msb | (vertical_active_msb << 4);
let horizontal_front_lsb: u8 = (info.horizontal_front & 0xFF) as u8; // least sig 8 bits
let horizontal_front_msb: u8 = ((info.horizontal_front >> 8) & 0x03) as u8; // most sig 2 bits
let horizontal_sync_lsb: u8 = (info.horizontal_sync & 0xFF) as u8; // least sig 8 bits
let horizontal_sync_msb: u8 = ((info.horizontal_sync >> 8) & 0x03) as u8; // most sig 2 bits
let vertical_front_lsb: u8 = (info.vertical_front & 0x0F) as u8; // least sig 4 bits
let vertical_front_msb: u8 = ((info.vertical_front >> 8) & 0x0F) as u8; // most sig 2 bits
let vertical_sync_lsb: u8 = (info.vertical_sync & 0xFF) as u8; // least sig 4 bits
let vertical_sync_msb: u8 = ((info.vertical_sync >> 8) & 0x0F) as u8; // most sig 2 bits
// Horizontal front porch in pixels.
edid_block[8] = horizontal_front_lsb;
// Horizontal sync pulse width in pixels.
edid_block[9] = horizontal_sync_lsb;
// LSB of vertical front porch and sync pulse
edid_block[10] = vertical_sync_lsb | (vertical_front_lsb << 4);
// Upper 2 bits of these values.
edid_block[11] = vertical_sync_msb
| (vertical_front_msb << 2)
| (horizontal_sync_msb << 4)
| (horizontal_front_msb << 6);
}
// The EDID header. This is defined by the EDID spec.
fn populate_header(edid: &mut [u8]) {
edid[0] = 0x00;
edid[1] = 0xFF;
edid[2] = 0xFF;
edid[3] = 0xFF;
edid[4] = 0xFF;
edid[5] = 0xFF;
edid[6] = 0xFF;
edid[7] = 0x00;
let manufacturer_name: [char; 3] = ['G', 'G', 'L'];
// 00001 -> A, 00010 -> B, etc
let manufacturer_id: u16 = manufacturer_name
.iter()
.map(|c| (*c as u8 - b'A' + 1) & 0x1F)
.fold(0u16, |res, lsb| (res << 5) | (lsb as u16));
edid[8..10].copy_from_slice(&manufacturer_id.to_be_bytes());
let manufacture_product_id: u16 = 1;
edid[10..12].copy_from_slice(&manufacture_product_id.to_le_bytes());
let serial_id: u32 = 1;
edid[12..16].copy_from_slice(&serial_id.to_le_bytes());
let manufacture_week: u8 = 8;
edid[16] = manufacture_week;
let manufacture_year: u32 = 2022;
edid[17] = (manufacture_year - 1990u32) as u8;
}
// The standard timings are 8 timing modes with a lower priority (and different data format)
// than the 4 detailed timing modes.
fn populate_standard_timings(edid: &mut [u8]) -> VirtioGpuResult {
let resolutions = [
Resolution::new(1440, 900),
Resolution::new(1600, 900),
Resolution::new(800, 600),
Resolution::new(1680, 1050),
Resolution::new(1856, 1392),
Resolution::new(1280, 1024),
Resolution::new(1400, 1050),
Resolution::new(1920, 1200),
];
// Index 0 is horizontal pixels / 8 - 31
// Index 1 is a combination of the refresh_rate - 60 (so we are setting to 0, for now) and two
// bits for the aspect ratio.
for (index, r) in resolutions.iter().enumerate() {
edid[0x26 + (index * 2)] = (r.width / 8 - 31) as u8;
let ar_bits = match r.get_aspect_ratio() {
(8, 5) => 0x0,
(4, 3) => 0x1,
(5, 4) => 0x2,
(16, 9) => 0x3,
(x, y) => return Err(ErrEdid(format!("Unsupported aspect ratio: {} {}", x, y))),
};
edid[0x27 + (index * 2)] = ar_bits;
}
Ok(OkNoData)
}
// Per the EDID spec, needs to be 1 and 4.
fn populate_edid_version(edid: &mut [u8]) {
edid[18] = 1;
edid[19] = 4;
}
fn calculate_checksum(edid: &mut [u8]) {
let mut checksum: u8 = 0;
for byte in edid.iter().take(EDID_DATA_LENGTH - 1) {
checksum = checksum.wrapping_add(*byte);
}
if checksum!= 0 {
checksum = 255 - checksum + 1;
}
edid[127] = checksum;
} | calculate_checksum(&mut edid);
Ok(OkEdid(Self { bytes: edid })) | random_line_split |
edid.rs | // Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Implementation of the EDID specification provided by software.
//! EDID spec: <https://glenwing.github.io/docs/VESA-EEDID-A2.pdf>
use std::fmt;
use std::fmt::Debug;
use super::protocol::GpuResponse::*;
use super::protocol::VirtioGpuResult;
const EDID_DATA_LENGTH: usize = 128;
const DEFAULT_HORIZONTAL_BLANKING: u16 = 560;
const DEFAULT_VERTICAL_BLANKING: u16 = 50;
const DEFAULT_HORIZONTAL_FRONT_PORCH: u16 = 64;
const DEFAULT_VERTICAL_FRONT_PORCH: u16 = 1;
const DEFAULT_HORIZONTAL_SYNC_PULSE: u16 = 192;
const DEFAULT_VERTICAL_SYNC_PULSE: u16 = 3;
/// This class is used to create the Extended Display Identification Data (EDID), which will be
/// exposed to the guest system.
///
/// We ignore most of the spec, the point here being for us to provide enough for graphics to work
/// and to allow us to configure the resolution and refresh rate (via the preferred timing mode
/// pixel clock).
///
/// The EDID spec defines a number of methods to provide mode information, but in priority order the
/// "detailed" timing information is first, so we provide a single block of detailed timing
/// information and no other form of timing information.
#[repr(C)]
pub struct EdidBytes {
bytes: [u8; EDID_DATA_LENGTH],
}
impl EdidBytes {
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
}
impl Debug for EdidBytes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.bytes[..].fmt(f)
}
}
impl PartialEq for EdidBytes {
fn eq(&self, other: &EdidBytes) -> bool {
self.bytes[..] == other.bytes[..]
}
}
#[derive(Copy, Clone)]
pub struct Resolution {
width: u32,
height: u32,
}
impl Resolution {
fn new(width: u32, height: u32) -> Resolution {
Resolution { width, height }
}
fn get_aspect_ratio(&self) -> (u32, u32) {
let divisor = gcd(self.width, self.height);
(self.width / divisor, self.height / divisor)
}
}
fn gcd(x: u32, y: u32) -> u32 {
match y {
0 => x,
_ => gcd(y, x % y),
}
}
#[derive(Copy, Clone)]
pub struct DisplayInfo {
resolution: Resolution,
refresh_rate: u32,
horizontal_blanking: u16,
vertical_blanking: u16,
horizontal_front: u16,
vertical_front: u16,
horizontal_sync: u16,
vertical_sync: u16,
}
impl DisplayInfo {
/// Only width, height and refresh rate are required for the graphics stack to work, so instead
/// of pulling actual numbers from the system, we just use some typical values to populate other
/// fields for now.
pub fn new(width: u32, height: u32, refresh_rate: u32) -> Self {
Self {
resolution: Resolution::new(width, height),
refresh_rate,
horizontal_blanking: DEFAULT_HORIZONTAL_BLANKING,
vertical_blanking: DEFAULT_VERTICAL_BLANKING,
horizontal_front: DEFAULT_HORIZONTAL_FRONT_PORCH,
vertical_front: DEFAULT_VERTICAL_FRONT_PORCH,
horizontal_sync: DEFAULT_HORIZONTAL_SYNC_PULSE,
vertical_sync: DEFAULT_VERTICAL_SYNC_PULSE,
}
}
pub fn width(&self) -> u32 {
self.resolution.width
}
pub fn height(&self) -> u32 {
self.resolution.height
}
}
impl EdidBytes {
/// Creates a virtual EDID block.
pub fn new(info: &DisplayInfo) -> VirtioGpuResult {
let mut edid: [u8; EDID_DATA_LENGTH] = [0; EDID_DATA_LENGTH];
populate_header(&mut edid);
populate_edid_version(&mut edid);
populate_standard_timings(&mut edid)?;
// 4 available descriptor blocks
let block0 = &mut edid[54..72];
populate_detailed_timing(block0, info);
let block1 = &mut edid[72..90];
populate_display_name(block1);
calculate_checksum(&mut edid);
Ok(OkEdid(Self { bytes: edid }))
}
}
fn populate_display_name(edid_block: &mut [u8]) {
// Display Product Name String Descriptor Tag
edid_block[0..5].clone_from_slice(&[0x00, 0x00, 0x00, 0xFC, 0x00]);
edid_block[5..].clone_from_slice("CrosvmDisplay".as_bytes());
}
fn populate_detailed_timing(edid_block: &mut [u8], info: &DisplayInfo) {
assert_eq!(edid_block.len(), 18);
// Detailed timings
//
// 18 Byte Descriptors - 72 Bytes
// The 72 bytes in this section are divided into four data fields. Each of the four data fields
// are 18 bytes in length. These 18 byte data fields shall contain either detailed timing data
// as described in Section 3.10.2 or other types of data as described in Section 3.10.3. The
// addresses and the contents of the four 18 byte descriptors are shown in Table 3.20.
//
// We leave the bottom 6 bytes of this block purposefully empty.
let horizontal_blanking_lsb: u8 = (info.horizontal_blanking & 0xFF) as u8;
let horizontal_blanking_msb: u8 = ((info.horizontal_blanking >> 8) & 0x0F) as u8;
let vertical_blanking_lsb: u8 = (info.vertical_blanking & 0xFF) as u8;
let vertical_blanking_msb: u8 = ((info.vertical_blanking >> 8) & 0x0F) as u8;
// The pixel clock is what controls the refresh timing information.
//
// The formula for getting refresh rate out of this value is:
// refresh_rate = clk * 10000 / (htotal * vtotal)
// Solving for clk:
// clk = (refresh_rate * htotal * votal) / 10000
//
// where:
// clk - The setting here
// vtotal - Total lines
// htotal - Total pixels per line
//
// Value here is pixel clock + 10,000, in 10khz steps.
//
// Pseudocode of kernel logic for vrefresh:
// vtotal := mode->vtotal;
// calc_val := (clock * 1000) / htotal
// refresh := (calc_val + vtotal / 2) / vtotal
// if flags & INTERLACE: refresh *= 2
// if flags & DBLSCAN: refresh /= 2
// if vscan > 1: refresh /= vscan
//
let htotal = info.width() + (info.horizontal_blanking as u32);
let vtotal = info.height() + (info.vertical_blanking as u32);
let mut clock: u16 = ((info.refresh_rate * htotal * vtotal) / 10000) as u16;
// Round to nearest 10khz.
clock = ((clock + 5) / 10) * 10;
edid_block[0..2].copy_from_slice(&clock.to_le_bytes());
let width_lsb: u8 = (info.width() & 0xFF) as u8;
let width_msb: u8 = ((info.width() >> 8) & 0x0F) as u8;
// Horizointal Addressable Video in pixels.
edid_block[2] = width_lsb;
// Horizontal blanking in pixels.
edid_block[3] = horizontal_blanking_lsb;
// Upper bits of the two above vals.
edid_block[4] = horizontal_blanking_msb | (width_msb << 4) as u8;
let vertical_active: u32 = info.height();
let vertical_active_lsb: u8 = (vertical_active & 0xFF) as u8;
let vertical_active_msb: u8 = ((vertical_active >> 8) & 0x0F) as u8;
// Vertical addressable video in *lines*
edid_block[5] = vertical_active_lsb;
// Vertical blanking in lines
edid_block[6] = vertical_blanking_lsb;
// Sigbits of the above.
edid_block[7] = vertical_blanking_msb | (vertical_active_msb << 4);
let horizontal_front_lsb: u8 = (info.horizontal_front & 0xFF) as u8; // least sig 8 bits
let horizontal_front_msb: u8 = ((info.horizontal_front >> 8) & 0x03) as u8; // most sig 2 bits
let horizontal_sync_lsb: u8 = (info.horizontal_sync & 0xFF) as u8; // least sig 8 bits
let horizontal_sync_msb: u8 = ((info.horizontal_sync >> 8) & 0x03) as u8; // most sig 2 bits
let vertical_front_lsb: u8 = (info.vertical_front & 0x0F) as u8; // least sig 4 bits
let vertical_front_msb: u8 = ((info.vertical_front >> 8) & 0x0F) as u8; // most sig 2 bits
let vertical_sync_lsb: u8 = (info.vertical_sync & 0xFF) as u8; // least sig 4 bits
let vertical_sync_msb: u8 = ((info.vertical_sync >> 8) & 0x0F) as u8; // most sig 2 bits
// Horizontal front porch in pixels.
edid_block[8] = horizontal_front_lsb;
// Horizontal sync pulse width in pixels.
edid_block[9] = horizontal_sync_lsb;
// LSB of vertical front porch and sync pulse
edid_block[10] = vertical_sync_lsb | (vertical_front_lsb << 4);
// Upper 2 bits of these values.
edid_block[11] = vertical_sync_msb
| (vertical_front_msb << 2)
| (horizontal_sync_msb << 4)
| (horizontal_front_msb << 6);
}
// The EDID header. This is defined by the EDID spec.
fn populate_header(edid: &mut [u8]) {
edid[0] = 0x00;
edid[1] = 0xFF;
edid[2] = 0xFF;
edid[3] = 0xFF;
edid[4] = 0xFF;
edid[5] = 0xFF;
edid[6] = 0xFF;
edid[7] = 0x00;
let manufacturer_name: [char; 3] = ['G', 'G', 'L'];
// 00001 -> A, 00010 -> B, etc
let manufacturer_id: u16 = manufacturer_name
.iter()
.map(|c| (*c as u8 - b'A' + 1) & 0x1F)
.fold(0u16, |res, lsb| (res << 5) | (lsb as u16));
edid[8..10].copy_from_slice(&manufacturer_id.to_be_bytes());
let manufacture_product_id: u16 = 1;
edid[10..12].copy_from_slice(&manufacture_product_id.to_le_bytes());
let serial_id: u32 = 1;
edid[12..16].copy_from_slice(&serial_id.to_le_bytes());
let manufacture_week: u8 = 8;
edid[16] = manufacture_week;
let manufacture_year: u32 = 2022;
edid[17] = (manufacture_year - 1990u32) as u8;
}
// The standard timings are 8 timing modes with a lower priority (and different data format)
// than the 4 detailed timing modes.
fn populate_standard_timings(edid: &mut [u8]) -> VirtioGpuResult {
let resolutions = [
Resolution::new(1440, 900),
Resolution::new(1600, 900),
Resolution::new(800, 600),
Resolution::new(1680, 1050),
Resolution::new(1856, 1392),
Resolution::new(1280, 1024),
Resolution::new(1400, 1050),
Resolution::new(1920, 1200),
];
// Index 0 is horizontal pixels / 8 - 31
// Index 1 is a combination of the refresh_rate - 60 (so we are setting to 0, for now) and two
// bits for the aspect ratio.
for (index, r) in resolutions.iter().enumerate() {
edid[0x26 + (index * 2)] = (r.width / 8 - 31) as u8;
let ar_bits = match r.get_aspect_ratio() {
(8, 5) => 0x0,
(4, 3) => 0x1,
(5, 4) => 0x2,
(16, 9) => 0x3,
(x, y) => return Err(ErrEdid(format!("Unsupported aspect ratio: {} {}", x, y))),
};
edid[0x27 + (index * 2)] = ar_bits;
}
Ok(OkNoData)
}
// Per the EDID spec, needs to be 1 and 4.
fn populate_edid_version(edid: &mut [u8]) {
edid[18] = 1;
edid[19] = 4;
}
fn calculate_checksum(edid: &mut [u8]) {
let mut checksum: u8 = 0;
for byte in edid.iter().take(EDID_DATA_LENGTH - 1) {
checksum = checksum.wrapping_add(*byte);
}
if checksum!= 0 |
edid[127] = checksum;
}
| {
checksum = 255 - checksum + 1;
} | conditional_block |
off.rs | use petgraph::{graph::NodeIndex, visit::Dfs, Graph};
use std::{collections::HashMap, io::Result, path::Path, str::FromStr};
use super::{Abstract, Concrete, Element, ElementList, Point, Polytope, RankVec};
/// Gets the name for an element with a given rank.
fn element_name(rank: isize) -> String {
match super::ELEMENT_NAMES.get(rank as usize) {
Some(&name) => String::from(name),
None => rank.to_string() + "-elements",
}
}
/// Returns an iterator over the OFF file, with all whitespace and comments
/// removed.
fn data_tokens(src: &str) -> impl Iterator<Item = &str> {
let mut comment = false;
str::split(&src, move |c: char| {
if c == '#' {
comment = true;
} else if c == '\n' {
comment = false;
}
comment || c.is_whitespace()
})
.filter(|s|!s.is_empty())
}
/// Reads the next integer or float from the OFF file.
fn next_tok<'a, T>(toks: &mut impl Iterator<Item = &'a str>) -> T
where
T: FromStr,
<T as FromStr>::Err: std::fmt::Debug,
{
toks.next()
.expect("OFF file ended unexpectedly.")
.parse()
.expect("Could not parse number.")
}
/// Gets the number of elements from the OFF file.
/// This includes components iff dim ≤ 2, as this makes things easier down the
/// line.
fn get_el_nums<'a>(rank: isize, toks: &mut impl Iterator<Item = &'a str>) -> Vec<usize> {
let rank = rank as usize;
let mut el_nums = Vec::with_capacity(rank);
// Reads entries one by one.
for _ in 0..rank {
el_nums.push(next_tok(toks));
}
// A point has a single component (itself)
if rank == 0 {
el_nums.push(1);
}
// A dyad has twice as many vertices as components.
else if rank == 1 {
let comps = el_nums[0] / 2;
el_nums.push(comps);
} else {
// A polygon always has as many vertices as edges.
if rank == 2 {
el_nums.push(el_nums[0]);
}
// 2-elements go before 1-elements, we're undoing that.
el_nums.swap(1, 2);
}
el_nums
}
/// Parses all vertex coordinates from the OFF file.
fn pa | a>(
num: usize,
dim: usize,
toks: &mut impl Iterator<Item = &'a str>,
) -> Vec<Point> {
// Reads all vertices.
let mut vertices = Vec::with_capacity(num);
// Add each vertex to the vector.
for _ in 0..num {
let mut vert = Vec::with_capacity(dim);
for _ in 0..dim {
vert.push(next_tok(toks));
}
vertices.push(vert.into());
}
vertices
}
/// Reads the faces from the OFF file and gets the edges and faces from them.
/// Since the OFF file doesn't store edges explicitly, this is harder than reading
/// general elements.
fn parse_edges_and_faces<'a>(
rank: isize,
num_edges: usize,
num_faces: usize,
toks: &mut impl Iterator<Item = &'a str>,
) -> (ElementList, ElementList) {
let mut edges = ElementList::with_capacity(num_edges);
let mut faces = ElementList::with_capacity(num_faces);
let mut hash_edges = HashMap::new();
// Add each face to the element list.
for _ in 0..num_faces {
let face_sub_num = next_tok(toks);
let mut face = Element::new();
let mut face_verts = Vec::with_capacity(face_sub_num);
// Reads all vertices of the face.
for _ in 0..face_sub_num {
face_verts.push(next_tok(toks));
}
// Gets all edges of the face.
for i in 0..face_sub_num {
let mut edge = Element {
subs: vec![face_verts[i], face_verts[(i + 1) % face_sub_num]],
};
edge.subs.sort_unstable();
if let Some(idx) = hash_edges.get(&edge) {
face.subs.push(*idx);
} else {
hash_edges.insert(edge.clone(), edges.len());
face.subs.push(edges.len());
edges.push(edge);
}
}
// If these are truly faces and not just components, we add them.
if rank!= 2 {
faces.push(face);
}
}
// If this is a polygon, we add a single maximal element as a face.
if rank == 2 {
faces = ElementList::max(edges.len());
}
// The number of edges in the file should match the number of read edges, though this isn't obligatory.
if edges.len()!= num_edges {
println!("Edge count doesn't match expected edge count!");
}
(edges, faces)
}
pub fn parse_els<'a>(num_el: usize, toks: &mut impl Iterator<Item = &'a str>) -> ElementList {
let mut els_subs = ElementList::with_capacity(num_el);
// Adds every d-element to the element list.
for _ in 0..num_el {
let el_sub_num = next_tok(toks);
let mut subs = Vec::with_capacity(el_sub_num);
// Reads all sub-elements of the d-element.
for _ in 0..el_sub_num {
let el_sub = toks.next().expect("OFF file ended unexpectedly.");
subs.push(el_sub.parse().expect("Integer parsing failed!"));
}
els_subs.push(Element { subs });
}
els_subs
}
/// Builds a [`Polytope`] from the string representation of an OFF file.
pub fn from_src(src: String) -> Concrete {
let mut toks = data_tokens(&src);
let rank = {
let first = toks.next().expect("OFF file empty");
let rank = first.strip_suffix("OFF").expect("no \"OFF\" detected");
if rank.is_empty() {
3
} else {
rank.parse()
.expect("could not parse dimension as an integer")
}
};
// Deals with dumb degenerate cases.
if rank == -1 {
return Concrete::nullitope();
} else if rank == 0 {
return Concrete::point();
} else if rank == 1 {
return Concrete::dyad();
}
let num_elems = get_el_nums(rank, &mut toks);
let vertices = parse_vertices(num_elems[0], rank as usize, &mut toks);
let mut abs = Abstract::with_rank(rank);
// Adds nullitope and vertices.
abs.push_min();
abs.push_vertices(vertices.len());
// Reads edges and faces.
if rank >= 2 {
let (edges, faces) = parse_edges_and_faces(rank, num_elems[1], num_elems[2], &mut toks);
abs.push(edges);
abs.push(faces);
}
// Adds all higher elements.
for &num_el in num_elems.iter().take(rank as usize).skip(3) {
abs.push(parse_els(num_el, &mut toks));
}
// Caps the abstract polytope, returns the concrete one.
if rank!= 2 {
abs.push_max();
}
Concrete { vertices, abs }
}
/// Loads a polytope from a file path.
pub fn from_path(fp: &impl AsRef<Path>) -> Result<Concrete> {
Ok(from_src(String::from_utf8(std::fs::read(fp)?).unwrap()))
}
/// A set of options to be used when saving the OFF file.
#[derive(Clone, Copy)]
pub struct OffOptions {
/// Whether the OFF file should have comments specifying each face type.
pub comments: bool,
}
impl Default for OffOptions {
fn default() -> Self {
OffOptions { comments: true }
}
}
fn write_el_counts(off: &mut String, opt: &OffOptions, mut el_counts: RankVec<usize>) {
let rank = el_counts.rank();
// # Vertices, Faces, Edges,...
if opt.comments {
off.push_str("\n# Vertices");
let mut element_names = Vec::with_capacity((rank - 1) as usize);
for r in 1..rank {
element_names.push(element_name(r));
}
if element_names.len() >= 2 {
element_names.swap(0, 1);
}
for element_name in element_names {
off.push_str(", ");
off.push_str(&element_name);
}
off.push('\n');
}
// Swaps edges and faces, because OFF format bad.
if rank >= 3 {
el_counts.swap(1, 2);
}
for r in 0..rank {
off.push_str(&el_counts[r].to_string());
off.push(' ');
}
off.push('\n');
}
/// Writes the vertices of a polytope into an OFF file.
fn write_vertices(off: &mut String, opt: &OffOptions, vertices: &[Point]) {
// # Vertices
if opt.comments {
off.push_str("\n# ");
off.push_str(&element_name(0));
off.push('\n');
}
// Adds the coordinates.
for v in vertices {
for c in v.into_iter() {
off.push_str(&c.to_string());
off.push(' ');
}
off.push('\n');
}
}
/// Gets and writes the faces of a polytope into an OFF file.
fn write_faces(
off: &mut String,
opt: &OffOptions,
rank: usize,
edges: &ElementList,
faces: &ElementList,
) {
// # Faces
if opt.comments {
let el_name = if rank > 2 {
element_name(2)
} else {
super::COMPONENTS.to_string()
};
off.push_str("\n# ");
off.push_str(&el_name);
off.push('\n');
}
// TODO: write components instead of faces in 2D case.
for face in faces.iter() {
off.push_str(&face.subs.len().to_string());
// Maps an OFF index into a graph index.
let mut hash_edges = HashMap::new();
let mut graph = Graph::new_undirected();
// Maps the vertex indices to consecutive integers from 0.
for &edge_idx in &face.subs {
let edge = &edges[edge_idx];
let mut hash_edge = Vec::with_capacity(2);
for &vertex_idx in &edge.subs {
match hash_edges.get(&vertex_idx) {
Some(&idx) => hash_edge.push(idx),
None => {
let idx = hash_edges.len();
hash_edges.insert(vertex_idx, idx);
hash_edge.push(idx);
graph.add_node(vertex_idx);
}
}
}
}
// There should be as many graph indices as edges on the face.
// Otherwise, something went wrong.
debug_assert_eq!(
hash_edges.len(),
face.subs.len(),
"Faces don't have the same number of edges as there are in the polytope!"
);
// Adds the edges to the graph.
for &edge_idx in &face.subs {
let edge = &edges[edge_idx];
graph.add_edge(
NodeIndex::new(*hash_edges.get(&edge.subs[0]).unwrap()),
NodeIndex::new(*hash_edges.get(&edge.subs[1]).unwrap()),
(),
);
}
// Retrieves the cycle of vertices.
let mut dfs = Dfs::new(&graph, NodeIndex::new(0));
while let Some(nx) = dfs.next(&graph) {
off.push(' ');
off.push_str(&graph[nx].to_string());
}
off.push('\n');
}
}
/// Writes the n-elements of a polytope into an OFF file.
fn write_els(off: &mut String, opt: &OffOptions, rank: isize, els: &[Element]) {
// # n-elements
if opt.comments {
off.push_str("\n# ");
off.push_str(&element_name(rank));
off.push('\n');
}
// Adds the elements' indices.
for el in els {
off.push_str(&el.subs.len().to_string());
for &sub in &el.subs {
off.push(' ');
off.push_str(&sub.to_string());
}
off.push('\n');
}
}
/// Converts a polytope into an OFF file.
impl Concrete {
pub fn to_src(&self, opt: OffOptions) -> String {
let rank = self.rank();
let vertices = &self.vertices;
let abs = &self.abs;
let mut off = String::new();
// Blatant advertising.
if opt.comments {
off += &format!(
"# Generated using Miratope v{} (https://github.com/OfficialURL/miratope-rs)\n",
env!("CARGO_PKG_VERSION")
);
}
// Writes header.
if rank!= 3 {
off += &rank.to_string();
}
off += "OFF\n";
// If we have a nullitope or point on our hands, that is all.
if rank < 1 {
return off;
}
// Adds the element counts.
write_el_counts(&mut off, &opt, self.el_counts());
// Adds vertex coordinates.
write_vertices(&mut off, &opt, vertices);
// Adds faces.
if rank >= 2 {
write_faces(&mut off, &opt, rank as usize, &abs[1], &abs[2]);
}
// Adds the rest of the elements.
for r in 3..rank {
write_els(&mut off, &opt, r, &abs[r]);
}
off
}
/// Writes a polytope's OFF file in a specified file path.
pub fn to_path(&self, fp: &impl AsRef<Path>, opt: OffOptions) -> Result<()> {
std::fs::write(fp, self.to_src(opt))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Used to test a particular polytope.
fn test_shape(p: Concrete, el_nums: Vec<usize>) {
// Checks that element counts match up.
assert_eq!(p.el_counts().0, el_nums);
// Checks that the polytope can be reloaded correctly.
assert_eq!(
from_src(p.to_src(OffOptions::default())).el_counts().0,
el_nums
);
}
#[test]
/// Checks that a point has the correct amount of elements.
fn point_nums() {
let point = from_src("0OFF".to_string());
test_shape(point, vec![1, 1])
}
#[test]
/// Checks that a dyad has the correct amount of elements.
fn dyad_nums() {
let dyad = from_src("1OFF 2 -1 1 0 1".to_string());
test_shape(dyad, vec![1, 2, 1])
}
/*
#[test]
/// Checks that a hexagon has the correct amount of elements.
fn hig_nums() {
let hig =from_src(
"2OFF 6 1 1 0 0.5 0.8660254037844386 -0.5 0.8660254037844386 -1 0 -0.5 -0.8660254037844386 0.5 -0.8660254037844386 6 0 1 2 3 4 5".to_string()
);
test_shape(hig, vec![1, 6, 6, 1])
}
#[test]
/// Checks that a hexagram has the correct amount of elements.
fn shig_nums() {
let shig: Concrete = from_src(
"2OFF 6 2 1 0 0.5 0.8660254037844386 -0.5 0.8660254037844386 -1 0 -0.5 -0.8660254037844386 0.5 -0.8660254037844386 3 0 2 4 3 1 3 5".to_string()
).into();
test_shape(shig, vec![1, 6, 6, 1])
}
*/
#[test]
/// Checks that a tetrahedron has the correct amount of elements.
fn tet_nums() {
let tet = from_src(
"OFF 4 4 6 1 1 1 1 -1 -1 -1 1 -1 -1 -1 1 3 0 1 2 3 3 0 2 3 0 1 3 3 3 1 2".to_string(),
);
test_shape(tet, vec![1, 4, 6, 4, 1])
}
#[test]
/// Checks that a 2-tetrahedron compund has the correct amount of elements.
fn so_nums() {
let so = from_src(
"OFF 8 8 12 1 1 1 1 -1 -1 -1 1 -1 -1 -1 1 -1 -1 -1 -1 1 1 1 -1 1 1 1 -1 3 0 1 2 3 3 0 2 3 0 1 3 3 3 1 2 3 4 5 6 3 7 4 6 3 4 5 7 3 7 5 6 ".to_string(),
);
test_shape(so, vec![1, 8, 12, 8, 1])
}
#[test]
/// Checks that a pentachoron has the correct amount of elements.
fn pen_nums() {
let pen = from_src(
"4OFF 5 10 10 5 0.158113883008419 0.204124145231932 0.288675134594813 0.5 0.158113883008419 0.204124145231932 0.288675134594813 -0.5 0.158113883008419 0.204124145231932 -0.577350269189626 0 0.158113883008419 -0.612372435695794 0 0 -0.632455532033676 0 0 0 3 0 3 4 3 0 2 4 3 2 3 4 3 0 2 3 3 0 1 4 3 1 3 4 3 0 1 3 3 1 2 4 3 0 1 2 3 1 2 3 4 0 1 2 3 4 0 4 5 6 4 1 4 7 8 4 2 5 7 9 4 3 6 8 9"
.to_string(),
);
test_shape(pen, vec![1, 5, 10, 10, 5, 1])
}
#[test]
/// Checks that comments are correctly parsed.
fn comments() {
let tet = from_src(
"# So
OFF # this
4 4 6 # is
# a # test # of
1 1 1 # the 1234 5678
1 -1 -1 # comment 987
-1 1 -1 # removal 654
-1 -1 1 # system 321
3 0 1 2 #let #us #see
3 3 0 2# if
3 0 1 3#it
3 3 1 2#works!#"
.to_string(),
);
test_shape(tet, vec![1, 4, 6, 4, 1])
}
#[test]
#[should_panic(expected = "OFF file empty")]
fn empty() {
Concrete::from(from_src("".to_string()));
}
#[test]
#[should_panic(expected = "no \"OFF\" detected")]
fn magic_num() {
Concrete::from(from_src("foo bar".to_string()));
}
}
| rse_vertices<' | identifier_name |
off.rs | use petgraph::{graph::NodeIndex, visit::Dfs, Graph};
use std::{collections::HashMap, io::Result, path::Path, str::FromStr};
use super::{Abstract, Concrete, Element, ElementList, Point, Polytope, RankVec};
/// Gets the name for an element with a given rank.
fn element_name(rank: isize) -> String {
match super::ELEMENT_NAMES.get(rank as usize) {
Some(&name) => String::from(name),
None => rank.to_string() + "-elements",
}
}
/// Returns an iterator over the OFF file, with all whitespace and comments
/// removed.
fn data_tokens(src: &str) -> impl Iterator<Item = &str> {
let mut comment = false;
str::split(&src, move |c: char| {
if c == '#' {
comment = true;
} else if c == '\n' {
comment = false;
}
comment || c.is_whitespace()
})
.filter(|s|!s.is_empty())
}
/// Reads the next integer or float from the OFF file.
fn next_tok<'a, T>(toks: &mut impl Iterator<Item = &'a str>) -> T
where
T: FromStr,
<T as FromStr>::Err: std::fmt::Debug,
{
toks.next()
.expect("OFF file ended unexpectedly.")
.parse()
.expect("Could not parse number.")
}
/// Gets the number of elements from the OFF file.
/// This includes components iff dim ≤ 2, as this makes things easier down the
/// line.
fn get_el_nums<'a>(rank: isize, toks: &mut impl Iterator<Item = &'a str>) -> Vec<usize> {
let rank = rank as usize;
let mut el_nums = Vec::with_capacity(rank);
// Reads entries one by one.
for _ in 0..rank {
el_nums.push(next_tok(toks));
}
// A point has a single component (itself)
if rank == 0 {
el_nums.push(1);
}
// A dyad has twice as many vertices as components.
else if rank == 1 {
let comps = el_nums[0] / 2;
el_nums.push(comps);
} else {
// A polygon always has as many vertices as edges.
if rank == 2 {
el_nums.push(el_nums[0]);
}
// 2-elements go before 1-elements, we're undoing that.
el_nums.swap(1, 2);
}
el_nums
}
/// Parses all vertex coordinates from the OFF file.
fn parse_vertices<'a>(
num: usize,
dim: usize,
toks: &mut impl Iterator<Item = &'a str>,
) -> Vec<Point> {
// Reads all vertices.
let mut vertices = Vec::with_capacity(num);
// Add each vertex to the vector.
for _ in 0..num {
let mut vert = Vec::with_capacity(dim);
for _ in 0..dim {
vert.push(next_tok(toks));
}
vertices.push(vert.into());
}
vertices
}
/// Reads the faces from the OFF file and gets the edges and faces from them.
/// Since the OFF file doesn't store edges explicitly, this is harder than reading
/// general elements.
fn parse_edges_and_faces<'a>(
rank: isize,
num_edges: usize,
num_faces: usize,
toks: &mut impl Iterator<Item = &'a str>,
) -> (ElementList, ElementList) {
let mut edges = ElementList::with_capacity(num_edges);
let mut faces = ElementList::with_capacity(num_faces);
let mut hash_edges = HashMap::new();
// Add each face to the element list.
for _ in 0..num_faces {
let face_sub_num = next_tok(toks);
let mut face = Element::new();
let mut face_verts = Vec::with_capacity(face_sub_num);
// Reads all vertices of the face.
for _ in 0..face_sub_num {
face_verts.push(next_tok(toks));
}
// Gets all edges of the face.
for i in 0..face_sub_num {
let mut edge = Element {
subs: vec![face_verts[i], face_verts[(i + 1) % face_sub_num]],
};
edge.subs.sort_unstable();
if let Some(idx) = hash_edges.get(&edge) {
face.subs.push(*idx);
} else {
hash_edges.insert(edge.clone(), edges.len());
face.subs.push(edges.len());
edges.push(edge);
}
}
// If these are truly faces and not just components, we add them.
if rank!= 2 {
faces.push(face);
}
}
// If this is a polygon, we add a single maximal element as a face.
if rank == 2 {
faces = ElementList::max(edges.len());
}
// The number of edges in the file should match the number of read edges, though this isn't obligatory.
if edges.len()!= num_edges {
println!("Edge count doesn't match expected edge count!");
}
(edges, faces)
}
pub fn parse_els<'a>(num_el: usize, toks: &mut impl Iterator<Item = &'a str>) -> ElementList {
let mut els_subs = ElementList::with_capacity(num_el);
// Adds every d-element to the element list.
for _ in 0..num_el {
let el_sub_num = next_tok(toks);
let mut subs = Vec::with_capacity(el_sub_num);
// Reads all sub-elements of the d-element.
for _ in 0..el_sub_num {
let el_sub = toks.next().expect("OFF file ended unexpectedly.");
subs.push(el_sub.parse().expect("Integer parsing failed!"));
}
els_subs.push(Element { subs });
}
els_subs
}
/// Builds a [`Polytope`] from the string representation of an OFF file.
pub fn from_src(src: String) -> Concrete {
let mut toks = data_tokens(&src);
let rank = {
let first = toks.next().expect("OFF file empty");
let rank = first.strip_suffix("OFF").expect("no \"OFF\" detected");
if rank.is_empty() {
3
} else {
rank.parse()
.expect("could not parse dimension as an integer")
}
};
// Deals with dumb degenerate cases.
if rank == -1 {
return Concrete::nullitope();
} else if rank == 0 {
return Concrete::point();
} else if rank == 1 {
return Concrete::dyad();
}
let num_elems = get_el_nums(rank, &mut toks);
let vertices = parse_vertices(num_elems[0], rank as usize, &mut toks);
let mut abs = Abstract::with_rank(rank);
// Adds nullitope and vertices.
abs.push_min();
abs.push_vertices(vertices.len());
// Reads edges and faces.
if rank >= 2 {
let (edges, faces) = parse_edges_and_faces(rank, num_elems[1], num_elems[2], &mut toks);
abs.push(edges);
abs.push(faces);
}
// Adds all higher elements.
for &num_el in num_elems.iter().take(rank as usize).skip(3) {
abs.push(parse_els(num_el, &mut toks));
}
// Caps the abstract polytope, returns the concrete one.
if rank!= 2 {
abs.push_max();
}
Concrete { vertices, abs }
}
/// Loads a polytope from a file path.
pub fn from_path(fp: &impl AsRef<Path>) -> Result<Concrete> {
| /// A set of options to be used when saving the OFF file.
#[derive(Clone, Copy)]
pub struct OffOptions {
/// Whether the OFF file should have comments specifying each face type.
pub comments: bool,
}
impl Default for OffOptions {
fn default() -> Self {
OffOptions { comments: true }
}
}
fn write_el_counts(off: &mut String, opt: &OffOptions, mut el_counts: RankVec<usize>) {
let rank = el_counts.rank();
// # Vertices, Faces, Edges,...
if opt.comments {
off.push_str("\n# Vertices");
let mut element_names = Vec::with_capacity((rank - 1) as usize);
for r in 1..rank {
element_names.push(element_name(r));
}
if element_names.len() >= 2 {
element_names.swap(0, 1);
}
for element_name in element_names {
off.push_str(", ");
off.push_str(&element_name);
}
off.push('\n');
}
// Swaps edges and faces, because OFF format bad.
if rank >= 3 {
el_counts.swap(1, 2);
}
for r in 0..rank {
off.push_str(&el_counts[r].to_string());
off.push(' ');
}
off.push('\n');
}
/// Writes the vertices of a polytope into an OFF file.
fn write_vertices(off: &mut String, opt: &OffOptions, vertices: &[Point]) {
// # Vertices
if opt.comments {
off.push_str("\n# ");
off.push_str(&element_name(0));
off.push('\n');
}
// Adds the coordinates.
for v in vertices {
for c in v.into_iter() {
off.push_str(&c.to_string());
off.push(' ');
}
off.push('\n');
}
}
/// Gets and writes the faces of a polytope into an OFF file.
fn write_faces(
off: &mut String,
opt: &OffOptions,
rank: usize,
edges: &ElementList,
faces: &ElementList,
) {
// # Faces
if opt.comments {
let el_name = if rank > 2 {
element_name(2)
} else {
super::COMPONENTS.to_string()
};
off.push_str("\n# ");
off.push_str(&el_name);
off.push('\n');
}
// TODO: write components instead of faces in 2D case.
for face in faces.iter() {
off.push_str(&face.subs.len().to_string());
// Maps an OFF index into a graph index.
let mut hash_edges = HashMap::new();
let mut graph = Graph::new_undirected();
// Maps the vertex indices to consecutive integers from 0.
for &edge_idx in &face.subs {
let edge = &edges[edge_idx];
let mut hash_edge = Vec::with_capacity(2);
for &vertex_idx in &edge.subs {
match hash_edges.get(&vertex_idx) {
Some(&idx) => hash_edge.push(idx),
None => {
let idx = hash_edges.len();
hash_edges.insert(vertex_idx, idx);
hash_edge.push(idx);
graph.add_node(vertex_idx);
}
}
}
}
// There should be as many graph indices as edges on the face.
// Otherwise, something went wrong.
debug_assert_eq!(
hash_edges.len(),
face.subs.len(),
"Faces don't have the same number of edges as there are in the polytope!"
);
// Adds the edges to the graph.
for &edge_idx in &face.subs {
let edge = &edges[edge_idx];
graph.add_edge(
NodeIndex::new(*hash_edges.get(&edge.subs[0]).unwrap()),
NodeIndex::new(*hash_edges.get(&edge.subs[1]).unwrap()),
(),
);
}
// Retrieves the cycle of vertices.
let mut dfs = Dfs::new(&graph, NodeIndex::new(0));
while let Some(nx) = dfs.next(&graph) {
off.push(' ');
off.push_str(&graph[nx].to_string());
}
off.push('\n');
}
}
/// Writes the n-elements of a polytope into an OFF file.
fn write_els(off: &mut String, opt: &OffOptions, rank: isize, els: &[Element]) {
// # n-elements
if opt.comments {
off.push_str("\n# ");
off.push_str(&element_name(rank));
off.push('\n');
}
// Adds the elements' indices.
for el in els {
off.push_str(&el.subs.len().to_string());
for &sub in &el.subs {
off.push(' ');
off.push_str(&sub.to_string());
}
off.push('\n');
}
}
/// Converts a polytope into an OFF file.
impl Concrete {
pub fn to_src(&self, opt: OffOptions) -> String {
let rank = self.rank();
let vertices = &self.vertices;
let abs = &self.abs;
let mut off = String::new();
// Blatant advertising.
if opt.comments {
off += &format!(
"# Generated using Miratope v{} (https://github.com/OfficialURL/miratope-rs)\n",
env!("CARGO_PKG_VERSION")
);
}
// Writes header.
if rank!= 3 {
off += &rank.to_string();
}
off += "OFF\n";
// If we have a nullitope or point on our hands, that is all.
if rank < 1 {
return off;
}
// Adds the element counts.
write_el_counts(&mut off, &opt, self.el_counts());
// Adds vertex coordinates.
write_vertices(&mut off, &opt, vertices);
// Adds faces.
if rank >= 2 {
write_faces(&mut off, &opt, rank as usize, &abs[1], &abs[2]);
}
// Adds the rest of the elements.
for r in 3..rank {
write_els(&mut off, &opt, r, &abs[r]);
}
off
}
/// Writes a polytope's OFF file in a specified file path.
pub fn to_path(&self, fp: &impl AsRef<Path>, opt: OffOptions) -> Result<()> {
std::fs::write(fp, self.to_src(opt))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Used to test a particular polytope.
fn test_shape(p: Concrete, el_nums: Vec<usize>) {
// Checks that element counts match up.
assert_eq!(p.el_counts().0, el_nums);
// Checks that the polytope can be reloaded correctly.
assert_eq!(
from_src(p.to_src(OffOptions::default())).el_counts().0,
el_nums
);
}
#[test]
/// Checks that a point has the correct amount of elements.
fn point_nums() {
let point = from_src("0OFF".to_string());
test_shape(point, vec![1, 1])
}
#[test]
/// Checks that a dyad has the correct amount of elements.
fn dyad_nums() {
let dyad = from_src("1OFF 2 -1 1 0 1".to_string());
test_shape(dyad, vec![1, 2, 1])
}
/*
#[test]
/// Checks that a hexagon has the correct amount of elements.
fn hig_nums() {
let hig =from_src(
"2OFF 6 1 1 0 0.5 0.8660254037844386 -0.5 0.8660254037844386 -1 0 -0.5 -0.8660254037844386 0.5 -0.8660254037844386 6 0 1 2 3 4 5".to_string()
);
test_shape(hig, vec![1, 6, 6, 1])
}
#[test]
/// Checks that a hexagram has the correct amount of elements.
fn shig_nums() {
let shig: Concrete = from_src(
"2OFF 6 2 1 0 0.5 0.8660254037844386 -0.5 0.8660254037844386 -1 0 -0.5 -0.8660254037844386 0.5 -0.8660254037844386 3 0 2 4 3 1 3 5".to_string()
).into();
test_shape(shig, vec![1, 6, 6, 1])
}
*/
#[test]
/// Checks that a tetrahedron has the correct amount of elements.
fn tet_nums() {
let tet = from_src(
"OFF 4 4 6 1 1 1 1 -1 -1 -1 1 -1 -1 -1 1 3 0 1 2 3 3 0 2 3 0 1 3 3 3 1 2".to_string(),
);
test_shape(tet, vec![1, 4, 6, 4, 1])
}
#[test]
/// Checks that a 2-tetrahedron compund has the correct amount of elements.
fn so_nums() {
let so = from_src(
"OFF 8 8 12 1 1 1 1 -1 -1 -1 1 -1 -1 -1 1 -1 -1 -1 -1 1 1 1 -1 1 1 1 -1 3 0 1 2 3 3 0 2 3 0 1 3 3 3 1 2 3 4 5 6 3 7 4 6 3 4 5 7 3 7 5 6 ".to_string(),
);
test_shape(so, vec![1, 8, 12, 8, 1])
}
#[test]
/// Checks that a pentachoron has the correct amount of elements.
fn pen_nums() {
let pen = from_src(
"4OFF 5 10 10 5 0.158113883008419 0.204124145231932 0.288675134594813 0.5 0.158113883008419 0.204124145231932 0.288675134594813 -0.5 0.158113883008419 0.204124145231932 -0.577350269189626 0 0.158113883008419 -0.612372435695794 0 0 -0.632455532033676 0 0 0 3 0 3 4 3 0 2 4 3 2 3 4 3 0 2 3 3 0 1 4 3 1 3 4 3 0 1 3 3 1 2 4 3 0 1 2 3 1 2 3 4 0 1 2 3 4 0 4 5 6 4 1 4 7 8 4 2 5 7 9 4 3 6 8 9"
.to_string(),
);
test_shape(pen, vec![1, 5, 10, 10, 5, 1])
}
#[test]
/// Checks that comments are correctly parsed.
fn comments() {
let tet = from_src(
"# So
OFF # this
4 4 6 # is
# a # test # of
1 1 1 # the 1234 5678
1 -1 -1 # comment 987
-1 1 -1 # removal 654
-1 -1 1 # system 321
3 0 1 2 #let #us #see
3 3 0 2# if
3 0 1 3#it
3 3 1 2#works!#"
.to_string(),
);
test_shape(tet, vec![1, 4, 6, 4, 1])
}
#[test]
#[should_panic(expected = "OFF file empty")]
fn empty() {
Concrete::from(from_src("".to_string()));
}
#[test]
#[should_panic(expected = "no \"OFF\" detected")]
fn magic_num() {
Concrete::from(from_src("foo bar".to_string()));
}
}
| Ok(from_src(String::from_utf8(std::fs::read(fp)?).unwrap()))
}
| identifier_body |
off.rs | use petgraph::{graph::NodeIndex, visit::Dfs, Graph};
use std::{collections::HashMap, io::Result, path::Path, str::FromStr};
use super::{Abstract, Concrete, Element, ElementList, Point, Polytope, RankVec};
/// Gets the name for an element with a given rank.
fn element_name(rank: isize) -> String {
match super::ELEMENT_NAMES.get(rank as usize) {
Some(&name) => String::from(name),
None => rank.to_string() + "-elements",
}
}
/// Returns an iterator over the OFF file, with all whitespace and comments
/// removed.
fn data_tokens(src: &str) -> impl Iterator<Item = &str> {
let mut comment = false;
str::split(&src, move |c: char| {
if c == '#' | else if c == '\n' {
comment = false;
}
comment || c.is_whitespace()
})
.filter(|s|!s.is_empty())
}
/// Reads the next integer or float from the OFF file.
fn next_tok<'a, T>(toks: &mut impl Iterator<Item = &'a str>) -> T
where
T: FromStr,
<T as FromStr>::Err: std::fmt::Debug,
{
toks.next()
.expect("OFF file ended unexpectedly.")
.parse()
.expect("Could not parse number.")
}
/// Gets the number of elements from the OFF file.
/// This includes components iff dim ≤ 2, as this makes things easier down the
/// line.
fn get_el_nums<'a>(rank: isize, toks: &mut impl Iterator<Item = &'a str>) -> Vec<usize> {
let rank = rank as usize;
let mut el_nums = Vec::with_capacity(rank);
// Reads entries one by one.
for _ in 0..rank {
el_nums.push(next_tok(toks));
}
// A point has a single component (itself)
if rank == 0 {
el_nums.push(1);
}
// A dyad has twice as many vertices as components.
else if rank == 1 {
let comps = el_nums[0] / 2;
el_nums.push(comps);
} else {
// A polygon always has as many vertices as edges.
if rank == 2 {
el_nums.push(el_nums[0]);
}
// 2-elements go before 1-elements, we're undoing that.
el_nums.swap(1, 2);
}
el_nums
}
/// Parses all vertex coordinates from the OFF file.
fn parse_vertices<'a>(
num: usize,
dim: usize,
toks: &mut impl Iterator<Item = &'a str>,
) -> Vec<Point> {
// Reads all vertices.
let mut vertices = Vec::with_capacity(num);
// Add each vertex to the vector.
for _ in 0..num {
let mut vert = Vec::with_capacity(dim);
for _ in 0..dim {
vert.push(next_tok(toks));
}
vertices.push(vert.into());
}
vertices
}
/// Reads the faces from the OFF file and gets the edges and faces from them.
/// Since the OFF file doesn't store edges explicitly, this is harder than reading
/// general elements.
fn parse_edges_and_faces<'a>(
rank: isize,
num_edges: usize,
num_faces: usize,
toks: &mut impl Iterator<Item = &'a str>,
) -> (ElementList, ElementList) {
let mut edges = ElementList::with_capacity(num_edges);
let mut faces = ElementList::with_capacity(num_faces);
let mut hash_edges = HashMap::new();
// Add each face to the element list.
for _ in 0..num_faces {
let face_sub_num = next_tok(toks);
let mut face = Element::new();
let mut face_verts = Vec::with_capacity(face_sub_num);
// Reads all vertices of the face.
for _ in 0..face_sub_num {
face_verts.push(next_tok(toks));
}
// Gets all edges of the face.
for i in 0..face_sub_num {
let mut edge = Element {
subs: vec![face_verts[i], face_verts[(i + 1) % face_sub_num]],
};
edge.subs.sort_unstable();
if let Some(idx) = hash_edges.get(&edge) {
face.subs.push(*idx);
} else {
hash_edges.insert(edge.clone(), edges.len());
face.subs.push(edges.len());
edges.push(edge);
}
}
// If these are truly faces and not just components, we add them.
if rank!= 2 {
faces.push(face);
}
}
// If this is a polygon, we add a single maximal element as a face.
if rank == 2 {
faces = ElementList::max(edges.len());
}
// The number of edges in the file should match the number of read edges, though this isn't obligatory.
if edges.len()!= num_edges {
println!("Edge count doesn't match expected edge count!");
}
(edges, faces)
}
pub fn parse_els<'a>(num_el: usize, toks: &mut impl Iterator<Item = &'a str>) -> ElementList {
let mut els_subs = ElementList::with_capacity(num_el);
// Adds every d-element to the element list.
for _ in 0..num_el {
let el_sub_num = next_tok(toks);
let mut subs = Vec::with_capacity(el_sub_num);
// Reads all sub-elements of the d-element.
for _ in 0..el_sub_num {
let el_sub = toks.next().expect("OFF file ended unexpectedly.");
subs.push(el_sub.parse().expect("Integer parsing failed!"));
}
els_subs.push(Element { subs });
}
els_subs
}
/// Builds a [`Polytope`] from the string representation of an OFF file.
pub fn from_src(src: String) -> Concrete {
let mut toks = data_tokens(&src);
let rank = {
let first = toks.next().expect("OFF file empty");
let rank = first.strip_suffix("OFF").expect("no \"OFF\" detected");
if rank.is_empty() {
3
} else {
rank.parse()
.expect("could not parse dimension as an integer")
}
};
// Deals with dumb degenerate cases.
if rank == -1 {
return Concrete::nullitope();
} else if rank == 0 {
return Concrete::point();
} else if rank == 1 {
return Concrete::dyad();
}
let num_elems = get_el_nums(rank, &mut toks);
let vertices = parse_vertices(num_elems[0], rank as usize, &mut toks);
let mut abs = Abstract::with_rank(rank);
// Adds nullitope and vertices.
abs.push_min();
abs.push_vertices(vertices.len());
// Reads edges and faces.
if rank >= 2 {
let (edges, faces) = parse_edges_and_faces(rank, num_elems[1], num_elems[2], &mut toks);
abs.push(edges);
abs.push(faces);
}
// Adds all higher elements.
for &num_el in num_elems.iter().take(rank as usize).skip(3) {
abs.push(parse_els(num_el, &mut toks));
}
// Caps the abstract polytope, returns the concrete one.
if rank!= 2 {
abs.push_max();
}
Concrete { vertices, abs }
}
/// Loads a polytope from a file path.
pub fn from_path(fp: &impl AsRef<Path>) -> Result<Concrete> {
Ok(from_src(String::from_utf8(std::fs::read(fp)?).unwrap()))
}
/// A set of options to be used when saving the OFF file.
#[derive(Clone, Copy)]
pub struct OffOptions {
/// Whether the OFF file should have comments specifying each face type.
pub comments: bool,
}
impl Default for OffOptions {
fn default() -> Self {
OffOptions { comments: true }
}
}
fn write_el_counts(off: &mut String, opt: &OffOptions, mut el_counts: RankVec<usize>) {
let rank = el_counts.rank();
// # Vertices, Faces, Edges,...
if opt.comments {
off.push_str("\n# Vertices");
let mut element_names = Vec::with_capacity((rank - 1) as usize);
for r in 1..rank {
element_names.push(element_name(r));
}
if element_names.len() >= 2 {
element_names.swap(0, 1);
}
for element_name in element_names {
off.push_str(", ");
off.push_str(&element_name);
}
off.push('\n');
}
// Swaps edges and faces, because OFF format bad.
if rank >= 3 {
el_counts.swap(1, 2);
}
for r in 0..rank {
off.push_str(&el_counts[r].to_string());
off.push(' ');
}
off.push('\n');
}
/// Writes the vertices of a polytope into an OFF file.
fn write_vertices(off: &mut String, opt: &OffOptions, vertices: &[Point]) {
// # Vertices
if opt.comments {
off.push_str("\n# ");
off.push_str(&element_name(0));
off.push('\n');
}
// Adds the coordinates.
for v in vertices {
for c in v.into_iter() {
off.push_str(&c.to_string());
off.push(' ');
}
off.push('\n');
}
}
/// Gets and writes the faces of a polytope into an OFF file.
fn write_faces(
off: &mut String,
opt: &OffOptions,
rank: usize,
edges: &ElementList,
faces: &ElementList,
) {
// # Faces
if opt.comments {
let el_name = if rank > 2 {
element_name(2)
} else {
super::COMPONENTS.to_string()
};
off.push_str("\n# ");
off.push_str(&el_name);
off.push('\n');
}
// TODO: write components instead of faces in 2D case.
for face in faces.iter() {
off.push_str(&face.subs.len().to_string());
// Maps an OFF index into a graph index.
let mut hash_edges = HashMap::new();
let mut graph = Graph::new_undirected();
// Maps the vertex indices to consecutive integers from 0.
for &edge_idx in &face.subs {
let edge = &edges[edge_idx];
let mut hash_edge = Vec::with_capacity(2);
for &vertex_idx in &edge.subs {
match hash_edges.get(&vertex_idx) {
Some(&idx) => hash_edge.push(idx),
None => {
let idx = hash_edges.len();
hash_edges.insert(vertex_idx, idx);
hash_edge.push(idx);
graph.add_node(vertex_idx);
}
}
}
}
// There should be as many graph indices as edges on the face.
// Otherwise, something went wrong.
debug_assert_eq!(
hash_edges.len(),
face.subs.len(),
"Faces don't have the same number of edges as there are in the polytope!"
);
// Adds the edges to the graph.
for &edge_idx in &face.subs {
let edge = &edges[edge_idx];
graph.add_edge(
NodeIndex::new(*hash_edges.get(&edge.subs[0]).unwrap()),
NodeIndex::new(*hash_edges.get(&edge.subs[1]).unwrap()),
(),
);
}
// Retrieves the cycle of vertices.
let mut dfs = Dfs::new(&graph, NodeIndex::new(0));
while let Some(nx) = dfs.next(&graph) {
off.push(' ');
off.push_str(&graph[nx].to_string());
}
off.push('\n');
}
}
/// Writes the n-elements of a polytope into an OFF file.
fn write_els(off: &mut String, opt: &OffOptions, rank: isize, els: &[Element]) {
// # n-elements
if opt.comments {
off.push_str("\n# ");
off.push_str(&element_name(rank));
off.push('\n');
}
// Adds the elements' indices.
for el in els {
off.push_str(&el.subs.len().to_string());
for &sub in &el.subs {
off.push(' ');
off.push_str(&sub.to_string());
}
off.push('\n');
}
}
/// Converts a polytope into an OFF file.
impl Concrete {
pub fn to_src(&self, opt: OffOptions) -> String {
let rank = self.rank();
let vertices = &self.vertices;
let abs = &self.abs;
let mut off = String::new();
// Blatant advertising.
if opt.comments {
off += &format!(
"# Generated using Miratope v{} (https://github.com/OfficialURL/miratope-rs)\n",
env!("CARGO_PKG_VERSION")
);
}
// Writes header.
if rank!= 3 {
off += &rank.to_string();
}
off += "OFF\n";
// If we have a nullitope or point on our hands, that is all.
if rank < 1 {
return off;
}
// Adds the element counts.
write_el_counts(&mut off, &opt, self.el_counts());
// Adds vertex coordinates.
write_vertices(&mut off, &opt, vertices);
// Adds faces.
if rank >= 2 {
write_faces(&mut off, &opt, rank as usize, &abs[1], &abs[2]);
}
// Adds the rest of the elements.
for r in 3..rank {
write_els(&mut off, &opt, r, &abs[r]);
}
off
}
/// Writes a polytope's OFF file in a specified file path.
pub fn to_path(&self, fp: &impl AsRef<Path>, opt: OffOptions) -> Result<()> {
std::fs::write(fp, self.to_src(opt))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Used to test a particular polytope.
fn test_shape(p: Concrete, el_nums: Vec<usize>) {
// Checks that element counts match up.
assert_eq!(p.el_counts().0, el_nums);
// Checks that the polytope can be reloaded correctly.
assert_eq!(
from_src(p.to_src(OffOptions::default())).el_counts().0,
el_nums
);
}
#[test]
/// Checks that a point has the correct amount of elements.
fn point_nums() {
let point = from_src("0OFF".to_string());
test_shape(point, vec![1, 1])
}
#[test]
/// Checks that a dyad has the correct amount of elements.
fn dyad_nums() {
let dyad = from_src("1OFF 2 -1 1 0 1".to_string());
test_shape(dyad, vec![1, 2, 1])
}
/*
#[test]
/// Checks that a hexagon has the correct amount of elements.
fn hig_nums() {
let hig =from_src(
"2OFF 6 1 1 0 0.5 0.8660254037844386 -0.5 0.8660254037844386 -1 0 -0.5 -0.8660254037844386 0.5 -0.8660254037844386 6 0 1 2 3 4 5".to_string()
);
test_shape(hig, vec![1, 6, 6, 1])
}
#[test]
/// Checks that a hexagram has the correct amount of elements.
fn shig_nums() {
let shig: Concrete = from_src(
"2OFF 6 2 1 0 0.5 0.8660254037844386 -0.5 0.8660254037844386 -1 0 -0.5 -0.8660254037844386 0.5 -0.8660254037844386 3 0 2 4 3 1 3 5".to_string()
).into();
test_shape(shig, vec![1, 6, 6, 1])
}
*/
#[test]
/// Checks that a tetrahedron has the correct amount of elements.
fn tet_nums() {
let tet = from_src(
"OFF 4 4 6 1 1 1 1 -1 -1 -1 1 -1 -1 -1 1 3 0 1 2 3 3 0 2 3 0 1 3 3 3 1 2".to_string(),
);
test_shape(tet, vec![1, 4, 6, 4, 1])
}
#[test]
/// Checks that a 2-tetrahedron compund has the correct amount of elements.
fn so_nums() {
let so = from_src(
"OFF 8 8 12 1 1 1 1 -1 -1 -1 1 -1 -1 -1 1 -1 -1 -1 -1 1 1 1 -1 1 1 1 -1 3 0 1 2 3 3 0 2 3 0 1 3 3 3 1 2 3 4 5 6 3 7 4 6 3 4 5 7 3 7 5 6 ".to_string(),
);
test_shape(so, vec![1, 8, 12, 8, 1])
}
#[test]
/// Checks that a pentachoron has the correct amount of elements.
fn pen_nums() {
let pen = from_src(
"4OFF 5 10 10 5 0.158113883008419 0.204124145231932 0.288675134594813 0.5 0.158113883008419 0.204124145231932 0.288675134594813 -0.5 0.158113883008419 0.204124145231932 -0.577350269189626 0 0.158113883008419 -0.612372435695794 0 0 -0.632455532033676 0 0 0 3 0 3 4 3 0 2 4 3 2 3 4 3 0 2 3 3 0 1 4 3 1 3 4 3 0 1 3 3 1 2 4 3 0 1 2 3 1 2 3 4 0 1 2 3 4 0 4 5 6 4 1 4 7 8 4 2 5 7 9 4 3 6 8 9"
.to_string(),
);
test_shape(pen, vec![1, 5, 10, 10, 5, 1])
}
#[test]
/// Checks that comments are correctly parsed.
fn comments() {
let tet = from_src(
"# So
OFF # this
4 4 6 # is
# a # test # of
1 1 1 # the 1234 5678
1 -1 -1 # comment 987
-1 1 -1 # removal 654
-1 -1 1 # system 321
3 0 1 2 #let #us #see
3 3 0 2# if
3 0 1 3#it
3 3 1 2#works!#"
.to_string(),
);
test_shape(tet, vec![1, 4, 6, 4, 1])
}
#[test]
#[should_panic(expected = "OFF file empty")]
fn empty() {
Concrete::from(from_src("".to_string()));
}
#[test]
#[should_panic(expected = "no \"OFF\" detected")]
fn magic_num() {
Concrete::from(from_src("foo bar".to_string()));
}
}
| {
comment = true;
} | conditional_block |
off.rs | use petgraph::{graph::NodeIndex, visit::Dfs, Graph};
use std::{collections::HashMap, io::Result, path::Path, str::FromStr};
use super::{Abstract, Concrete, Element, ElementList, Point, Polytope, RankVec};
/// Gets the name for an element with a given rank.
fn element_name(rank: isize) -> String {
match super::ELEMENT_NAMES.get(rank as usize) {
Some(&name) => String::from(name),
None => rank.to_string() + "-elements",
}
}
/// Returns an iterator over the OFF file, with all whitespace and comments
/// removed.
fn data_tokens(src: &str) -> impl Iterator<Item = &str> {
let mut comment = false;
str::split(&src, move |c: char| {
if c == '#' {
comment = true;
} else if c == '\n' {
comment = false;
}
comment || c.is_whitespace()
})
.filter(|s|!s.is_empty())
}
/// Reads the next integer or float from the OFF file.
fn next_tok<'a, T>(toks: &mut impl Iterator<Item = &'a str>) -> T
where
T: FromStr,
<T as FromStr>::Err: std::fmt::Debug,
{
toks.next()
.expect("OFF file ended unexpectedly.")
.parse()
.expect("Could not parse number.")
}
/// Gets the number of elements from the OFF file.
/// This includes components iff dim ≤ 2, as this makes things easier down the
/// line.
fn get_el_nums<'a>(rank: isize, toks: &mut impl Iterator<Item = &'a str>) -> Vec<usize> {
let rank = rank as usize;
let mut el_nums = Vec::with_capacity(rank);
// Reads entries one by one.
for _ in 0..rank {
el_nums.push(next_tok(toks));
}
// A point has a single component (itself)
if rank == 0 {
el_nums.push(1);
}
// A dyad has twice as many vertices as components.
else if rank == 1 {
let comps = el_nums[0] / 2;
el_nums.push(comps);
} else {
// A polygon always has as many vertices as edges.
if rank == 2 {
el_nums.push(el_nums[0]);
}
// 2-elements go before 1-elements, we're undoing that.
el_nums.swap(1, 2);
}
el_nums
}
/// Parses all vertex coordinates from the OFF file.
fn parse_vertices<'a>(
num: usize,
dim: usize,
toks: &mut impl Iterator<Item = &'a str>,
) -> Vec<Point> {
// Reads all vertices.
let mut vertices = Vec::with_capacity(num);
// Add each vertex to the vector.
for _ in 0..num {
let mut vert = Vec::with_capacity(dim);
for _ in 0..dim {
vert.push(next_tok(toks));
}
vertices.push(vert.into());
}
vertices
}
/// Reads the faces from the OFF file and gets the edges and faces from them.
/// Since the OFF file doesn't store edges explicitly, this is harder than reading
/// general elements.
fn parse_edges_and_faces<'a>(
rank: isize,
num_edges: usize,
num_faces: usize,
toks: &mut impl Iterator<Item = &'a str>,
) -> (ElementList, ElementList) {
let mut edges = ElementList::with_capacity(num_edges);
let mut faces = ElementList::with_capacity(num_faces);
let mut hash_edges = HashMap::new();
// Add each face to the element list.
for _ in 0..num_faces {
let face_sub_num = next_tok(toks);
let mut face = Element::new();
let mut face_verts = Vec::with_capacity(face_sub_num);
// Reads all vertices of the face.
for _ in 0..face_sub_num {
face_verts.push(next_tok(toks));
}
// Gets all edges of the face.
for i in 0..face_sub_num {
let mut edge = Element {
subs: vec![face_verts[i], face_verts[(i + 1) % face_sub_num]],
};
edge.subs.sort_unstable();
if let Some(idx) = hash_edges.get(&edge) {
face.subs.push(*idx);
} else {
hash_edges.insert(edge.clone(), edges.len());
face.subs.push(edges.len());
edges.push(edge);
}
}
// If these are truly faces and not just components, we add them.
if rank!= 2 {
faces.push(face);
}
}
// If this is a polygon, we add a single maximal element as a face.
if rank == 2 {
faces = ElementList::max(edges.len());
}
// The number of edges in the file should match the number of read edges, though this isn't obligatory.
if edges.len()!= num_edges {
println!("Edge count doesn't match expected edge count!");
}
(edges, faces)
}
pub fn parse_els<'a>(num_el: usize, toks: &mut impl Iterator<Item = &'a str>) -> ElementList {
let mut els_subs = ElementList::with_capacity(num_el);
// Adds every d-element to the element list.
for _ in 0..num_el { |
// Reads all sub-elements of the d-element.
for _ in 0..el_sub_num {
let el_sub = toks.next().expect("OFF file ended unexpectedly.");
subs.push(el_sub.parse().expect("Integer parsing failed!"));
}
els_subs.push(Element { subs });
}
els_subs
}
/// Builds a [`Polytope`] from the string representation of an OFF file.
pub fn from_src(src: String) -> Concrete {
let mut toks = data_tokens(&src);
let rank = {
let first = toks.next().expect("OFF file empty");
let rank = first.strip_suffix("OFF").expect("no \"OFF\" detected");
if rank.is_empty() {
3
} else {
rank.parse()
.expect("could not parse dimension as an integer")
}
};
// Deals with dumb degenerate cases.
if rank == -1 {
return Concrete::nullitope();
} else if rank == 0 {
return Concrete::point();
} else if rank == 1 {
return Concrete::dyad();
}
let num_elems = get_el_nums(rank, &mut toks);
let vertices = parse_vertices(num_elems[0], rank as usize, &mut toks);
let mut abs = Abstract::with_rank(rank);
// Adds nullitope and vertices.
abs.push_min();
abs.push_vertices(vertices.len());
// Reads edges and faces.
if rank >= 2 {
let (edges, faces) = parse_edges_and_faces(rank, num_elems[1], num_elems[2], &mut toks);
abs.push(edges);
abs.push(faces);
}
// Adds all higher elements.
for &num_el in num_elems.iter().take(rank as usize).skip(3) {
abs.push(parse_els(num_el, &mut toks));
}
// Caps the abstract polytope, returns the concrete one.
if rank!= 2 {
abs.push_max();
}
Concrete { vertices, abs }
}
/// Loads a polytope from a file path.
pub fn from_path(fp: &impl AsRef<Path>) -> Result<Concrete> {
Ok(from_src(String::from_utf8(std::fs::read(fp)?).unwrap()))
}
/// A set of options to be used when saving the OFF file.
#[derive(Clone, Copy)]
pub struct OffOptions {
/// Whether the OFF file should have comments specifying each face type.
pub comments: bool,
}
impl Default for OffOptions {
fn default() -> Self {
OffOptions { comments: true }
}
}
fn write_el_counts(off: &mut String, opt: &OffOptions, mut el_counts: RankVec<usize>) {
let rank = el_counts.rank();
// # Vertices, Faces, Edges,...
if opt.comments {
off.push_str("\n# Vertices");
let mut element_names = Vec::with_capacity((rank - 1) as usize);
for r in 1..rank {
element_names.push(element_name(r));
}
if element_names.len() >= 2 {
element_names.swap(0, 1);
}
for element_name in element_names {
off.push_str(", ");
off.push_str(&element_name);
}
off.push('\n');
}
// Swaps edges and faces, because OFF format bad.
if rank >= 3 {
el_counts.swap(1, 2);
}
for r in 0..rank {
off.push_str(&el_counts[r].to_string());
off.push(' ');
}
off.push('\n');
}
/// Writes the vertices of a polytope into an OFF file.
fn write_vertices(off: &mut String, opt: &OffOptions, vertices: &[Point]) {
// # Vertices
if opt.comments {
off.push_str("\n# ");
off.push_str(&element_name(0));
off.push('\n');
}
// Adds the coordinates.
for v in vertices {
for c in v.into_iter() {
off.push_str(&c.to_string());
off.push(' ');
}
off.push('\n');
}
}
/// Gets and writes the faces of a polytope into an OFF file.
fn write_faces(
off: &mut String,
opt: &OffOptions,
rank: usize,
edges: &ElementList,
faces: &ElementList,
) {
// # Faces
if opt.comments {
let el_name = if rank > 2 {
element_name(2)
} else {
super::COMPONENTS.to_string()
};
off.push_str("\n# ");
off.push_str(&el_name);
off.push('\n');
}
// TODO: write components instead of faces in 2D case.
for face in faces.iter() {
off.push_str(&face.subs.len().to_string());
// Maps an OFF index into a graph index.
let mut hash_edges = HashMap::new();
let mut graph = Graph::new_undirected();
// Maps the vertex indices to consecutive integers from 0.
for &edge_idx in &face.subs {
let edge = &edges[edge_idx];
let mut hash_edge = Vec::with_capacity(2);
for &vertex_idx in &edge.subs {
match hash_edges.get(&vertex_idx) {
Some(&idx) => hash_edge.push(idx),
None => {
let idx = hash_edges.len();
hash_edges.insert(vertex_idx, idx);
hash_edge.push(idx);
graph.add_node(vertex_idx);
}
}
}
}
// There should be as many graph indices as edges on the face.
// Otherwise, something went wrong.
debug_assert_eq!(
hash_edges.len(),
face.subs.len(),
"Faces don't have the same number of edges as there are in the polytope!"
);
// Adds the edges to the graph.
for &edge_idx in &face.subs {
let edge = &edges[edge_idx];
graph.add_edge(
NodeIndex::new(*hash_edges.get(&edge.subs[0]).unwrap()),
NodeIndex::new(*hash_edges.get(&edge.subs[1]).unwrap()),
(),
);
}
// Retrieves the cycle of vertices.
let mut dfs = Dfs::new(&graph, NodeIndex::new(0));
while let Some(nx) = dfs.next(&graph) {
off.push(' ');
off.push_str(&graph[nx].to_string());
}
off.push('\n');
}
}
/// Writes the n-elements of a polytope into an OFF file.
fn write_els(off: &mut String, opt: &OffOptions, rank: isize, els: &[Element]) {
// # n-elements
if opt.comments {
off.push_str("\n# ");
off.push_str(&element_name(rank));
off.push('\n');
}
// Adds the elements' indices.
for el in els {
off.push_str(&el.subs.len().to_string());
for &sub in &el.subs {
off.push(' ');
off.push_str(&sub.to_string());
}
off.push('\n');
}
}
/// Converts a polytope into an OFF file.
impl Concrete {
pub fn to_src(&self, opt: OffOptions) -> String {
let rank = self.rank();
let vertices = &self.vertices;
let abs = &self.abs;
let mut off = String::new();
// Blatant advertising.
if opt.comments {
off += &format!(
"# Generated using Miratope v{} (https://github.com/OfficialURL/miratope-rs)\n",
env!("CARGO_PKG_VERSION")
);
}
// Writes header.
if rank!= 3 {
off += &rank.to_string();
}
off += "OFF\n";
// If we have a nullitope or point on our hands, that is all.
if rank < 1 {
return off;
}
// Adds the element counts.
write_el_counts(&mut off, &opt, self.el_counts());
// Adds vertex coordinates.
write_vertices(&mut off, &opt, vertices);
// Adds faces.
if rank >= 2 {
write_faces(&mut off, &opt, rank as usize, &abs[1], &abs[2]);
}
// Adds the rest of the elements.
for r in 3..rank {
write_els(&mut off, &opt, r, &abs[r]);
}
off
}
/// Writes a polytope's OFF file in a specified file path.
pub fn to_path(&self, fp: &impl AsRef<Path>, opt: OffOptions) -> Result<()> {
std::fs::write(fp, self.to_src(opt))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Used to test a particular polytope.
fn test_shape(p: Concrete, el_nums: Vec<usize>) {
// Checks that element counts match up.
assert_eq!(p.el_counts().0, el_nums);
// Checks that the polytope can be reloaded correctly.
assert_eq!(
from_src(p.to_src(OffOptions::default())).el_counts().0,
el_nums
);
}
#[test]
/// Checks that a point has the correct amount of elements.
fn point_nums() {
let point = from_src("0OFF".to_string());
test_shape(point, vec![1, 1])
}
#[test]
/// Checks that a dyad has the correct amount of elements.
fn dyad_nums() {
let dyad = from_src("1OFF 2 -1 1 0 1".to_string());
test_shape(dyad, vec![1, 2, 1])
}
/*
#[test]
/// Checks that a hexagon has the correct amount of elements.
fn hig_nums() {
let hig =from_src(
"2OFF 6 1 1 0 0.5 0.8660254037844386 -0.5 0.8660254037844386 -1 0 -0.5 -0.8660254037844386 0.5 -0.8660254037844386 6 0 1 2 3 4 5".to_string()
);
test_shape(hig, vec![1, 6, 6, 1])
}
#[test]
/// Checks that a hexagram has the correct amount of elements.
fn shig_nums() {
let shig: Concrete = from_src(
"2OFF 6 2 1 0 0.5 0.8660254037844386 -0.5 0.8660254037844386 -1 0 -0.5 -0.8660254037844386 0.5 -0.8660254037844386 3 0 2 4 3 1 3 5".to_string()
).into();
test_shape(shig, vec![1, 6, 6, 1])
}
*/
#[test]
/// Checks that a tetrahedron has the correct amount of elements.
fn tet_nums() {
let tet = from_src(
"OFF 4 4 6 1 1 1 1 -1 -1 -1 1 -1 -1 -1 1 3 0 1 2 3 3 0 2 3 0 1 3 3 3 1 2".to_string(),
);
test_shape(tet, vec![1, 4, 6, 4, 1])
}
#[test]
/// Checks that a 2-tetrahedron compund has the correct amount of elements.
fn so_nums() {
let so = from_src(
"OFF 8 8 12 1 1 1 1 -1 -1 -1 1 -1 -1 -1 1 -1 -1 -1 -1 1 1 1 -1 1 1 1 -1 3 0 1 2 3 3 0 2 3 0 1 3 3 3 1 2 3 4 5 6 3 7 4 6 3 4 5 7 3 7 5 6 ".to_string(),
);
test_shape(so, vec![1, 8, 12, 8, 1])
}
#[test]
/// Checks that a pentachoron has the correct amount of elements.
fn pen_nums() {
let pen = from_src(
"4OFF 5 10 10 5 0.158113883008419 0.204124145231932 0.288675134594813 0.5 0.158113883008419 0.204124145231932 0.288675134594813 -0.5 0.158113883008419 0.204124145231932 -0.577350269189626 0 0.158113883008419 -0.612372435695794 0 0 -0.632455532033676 0 0 0 3 0 3 4 3 0 2 4 3 2 3 4 3 0 2 3 3 0 1 4 3 1 3 4 3 0 1 3 3 1 2 4 3 0 1 2 3 1 2 3 4 0 1 2 3 4 0 4 5 6 4 1 4 7 8 4 2 5 7 9 4 3 6 8 9"
.to_string(),
);
test_shape(pen, vec![1, 5, 10, 10, 5, 1])
}
#[test]
/// Checks that comments are correctly parsed.
fn comments() {
let tet = from_src(
"# So
OFF # this
4 4 6 # is
# a # test # of
1 1 1 # the 1234 5678
1 -1 -1 # comment 987
-1 1 -1 # removal 654
-1 -1 1 # system 321
3 0 1 2 #let #us #see
3 3 0 2# if
3 0 1 3#it
3 3 1 2#works!#"
.to_string(),
);
test_shape(tet, vec![1, 4, 6, 4, 1])
}
#[test]
#[should_panic(expected = "OFF file empty")]
fn empty() {
Concrete::from(from_src("".to_string()));
}
#[test]
#[should_panic(expected = "no \"OFF\" detected")]
fn magic_num() {
Concrete::from(from_src("foo bar".to_string()));
}
} | let el_sub_num = next_tok(toks);
let mut subs = Vec::with_capacity(el_sub_num); | random_line_split |
lib.rs | /*!
# Strip MapMaking library
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur facilisis consectetur arcu. Etiam semper, sem sit amet lacinia dignissim, mauris eros rutrum massa, a imperdiet orci urna vel elit. Nulla at sagittis lacus. Curabitur eu gravida turpis. Mauris blandit porta orci. Aliquam fringilla felis a sem aliquet rhoncus. Suspendisse porta, mi vel euismod porta, mi ex cursus diam, quis iaculis sapien massa eget massa. Fusce sit amet neque vel turpis interdum tempus et non nisl. Nunc aliquam nunc vitae justo accumsan pretium. Morbi eget urna quis ex pellentesque molestie. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer vehicula vehicula tortor sit amet dignissim. Duis finibus, felis ut fringilla tincidunt, mi lectus fermentum eros, ut laoreet justo lacus id urna.
Duis iaculis faucibus mollis. Maecenas dignissim efficitur ex. Sed pulvinar justo a arcu lobortis imperdiet. Suspendisse placerat venenatis volutpat. Aenean eu nulla vitae libero porta dignissim ut sit amet ante. Vestibulum porttitor sodales nibh, nec imperdiet tortor accumsan quis. Ut sagittis arcu eu efficitur varius. Etiam at ex condimentum, volutpat ipsum sed, posuere nibh. Sed posuere fringilla mi in commodo. Ut sodales, elit volutpat finibus dapibus, dui lacus porttitor enim, ac placerat erat ligula quis ipsum. Morbi sagittis et nisl mollis fringilla. Praesent commodo faucibus erat, nec congue lectus finibus vitae. Sed eu ipsum in lorem congue vehicula.
# Using the Strip MapMaking
Duis iaculis faucibus mollis. Maecenas dignissim efficitur ex. Sed pulvinar justo a arcu lobortis imperdiet. Suspendisse placerat venenatis volutpat. Aenean eu nulla vitae libero porta dignissim ut sit amet ante. Vestibulum porttitor sodales nibh, nec imperdiet tortor accumsan quis. Ut sagittis arcu eu efficitur varius. Etiam at ex condimentum, volutpat ipsum sed, posuere nibh. Sed posuere fringilla mi in commodo. Ut sodales, elit volutpat finibus dapibus, dui lacus porttitor enim, ac placerat erat ligula quis ipsum. Morbi sagittis et nisl mollis fringilla. Praesent commodo faucibus erat, nec congue lectus finibus vitae. Sed eu ipsum in lorem congue vehicula.
*/
extern crate rustfft;
pub mod directory;
pub mod iteratorscustom;
pub mod sky;
pub mod threadpool;
pub mod misc;
pub mod noisemodel;
pub mod plot_suite;
pub mod conjugategradient;
use threadpool::ThreadPool;
use std::{fs::File, io::Write, sync::mpsc, usize, vec};
use colored::Colorize;
use conjugategradient::conjgrad;
use iteratorscustom::FloatIterator;
use num::{ToPrimitive, complex::Complex32};
use rustfft::{FftPlanner, num_complex::Complex};
// use rustfft::algorithm::Radix4;
// use noisemodel::NoiseModel;
// use std::time::Instant;
// use gnuplot::*;
use std::marker::PhantomData;
#[derive(Debug)]
pub struct Obs <'a> {
start: String,
stop: String,
detector: Vec<String>,
mc_id: u8,
alpha: f32,
f_knee: f32,
pix: Vec<Vec<i32>>,
tod: Vec<Vec<f32>>,
sky_t: Vec<f32>,
phantom: PhantomData<&'a f32>,
}
// ```
// Documentation
// Creation function
// ```
impl <'a> Obs <'a> {
pub fn new(
start: String,
stop: String,
detector: Vec<String>,
mc_id: u8,
alpha: f32,
f_knee: f32,
tod: Vec<Vec<f32>>,
sky: Vec<f32>,
pix: Vec<Vec<i32>> ) -> Self
{
let mut tod_final: Vec<Vec<f32>> = Vec::new();
for (i, j) in tod.iter().zip(pix.iter()){
//let noise = NoiseModel::new(50.0, 7e9, 1.0/20.0, 0.1, 1.0, 123, i.len());
//let tod_noise = noise.get_noise_tod();
let mut tmp: Vec<f32> = Vec::new();
for (_n, (k, l)) in i.into_iter().zip(j.iter()).enumerate(){
let t_sky = sky[match l.to_usize() {Some(p) => p, None=>0}];
//let r = tod_noise[_n];
tmp.push(0.54*k + t_sky);
}
tod_final.push(tmp);
}
return Obs {
start,
stop,
detector,
mc_id,
alpha,
f_knee,
pix,
tod: tod_final,
sky_t: sky,
phantom: PhantomData,
}
}
}
// The `get` methods
impl <'a> Obs <'a>{
pub fn get_start(&self) -> &String {
&self.start
}
pub fn get_stop(&self) -> &String {
&self.stop
}
pub fn get_detector(&self) -> &Vec<String> {
&self.detector
}
pub fn get_mcid(&self) -> &u8 |
pub fn get_pix(&self) -> &Vec<Vec<i32>> {
&self.pix
}
pub fn get_tod(&self) -> &Vec<Vec<f32>> {
&self.tod
}
}
// Mitigation of the systematic effects
// Starting from the binning, to the
// implementation of a de_noise model
impl <'a> Obs <'a>{
pub fn binning(&self) -> (Vec<f32>, Vec<i32>) {
println!("");
println!("Start {}", "binning".bright_blue().bold());
const NSIDE: usize = 128;
const NUM_PIX: usize = NSIDE*NSIDE*12;
let mut signal_maps: Vec<Vec<f32>> = Vec::new();
let mut hit_maps: Vec<Vec<i32>> = Vec::new();
let pix = &self.pix;
let tod = &self.tod;
let num_threads = num_cpus::get();
let bin_pool = ThreadPool::new(num_threads);
let (tx, rx) = mpsc::channel();
for i in 0..tod.len() {
let t = tod[i].clone();
let p = pix[i].clone();
let tx = tx.clone();
bin_pool.execute(move ||{
let (sig_par, hit_par) = bin_map(t.clone(), p.clone(), 128);
tx.send((sig_par, hit_par)).unwrap();
});
}
for _i in 0..tod.len() {
let rec = rx.recv().unwrap();
signal_maps.push(rec.0.clone());
hit_maps.push(rec.1.clone());
}
let mut final_sig: Vec<f32> = vec![0.0; NUM_PIX];
let mut final_hit: Vec<i32> = vec![0; NUM_PIX];
for idx in 0..signal_maps.len() {
let s = signal_maps[idx].clone();
let h = hit_maps[idx].clone();
for pidx in 0..NUM_PIX{
let signal = s[pidx];
let hits = h[pidx];
final_sig[pidx] += signal;
final_hit[pidx] += hits;
}
}
println!("{}", "COMPLETED".bright_green());
/***PRINT ON FILE */
println!("");
let id_number = self.get_mcid();
let file_name = format!("binned_{}.dat", id_number);
println!("Print maps on file: {}", file_name.bright_green().bold());
let mut f = File::create(file_name).unwrap();
let hit: Vec<String> = final_hit.iter().map(|a| a.to_string()).collect();
let sig: Vec<String> = final_sig.iter().map(|a| a.to_string()).collect();
for (i,j) in hit.iter().zip(sig.iter()) {
writeln!(f, "{}\t{}",i, j).unwrap();
}
println!("{}", "COMPLETED".bright_green());
(final_sig, final_hit)
}
}
// GLS DENOISE
impl <'a> Obs <'a>{
pub fn gls_denoise(&self, _tol: f32, _maxiter: usize, _nside: usize){
println!("{}", "Execution of the gls_denoise".bright_blue().bold());
const NUM_PIX: usize = 12*128*128;
let _x: Vec<f32> = vec![0.0; NUM_PIX];
let (tx, rx) = mpsc::channel();
let tods = &self.tod;
let pixs = &self.pix;
//println!("Len TODs: {}", tods.len()); // 55 * n_hour
let mut partial_maps: Vec<Vec<f32>> = Vec::new();
let num_threads = num_cpus::get();
let my_pool_b = ThreadPool::new(num_threads);
for idx_th in 0..tods.len() {
let t = tods[idx_th].clone();
let p = pixs[idx_th].clone();
let tx = tx.clone();
my_pool_b.execute(move || {
let b = get_b(t, p, 128);
tx.send(b).expect("channel will be there waiting for the pool");
});
}
for _ in 0..tods.len(){
partial_maps.push(rx.recv().unwrap());
}
let mut b: Vec<f32> = vec![0.0; 12*128*128];
for i in partial_maps.iter(){
for (n,j) in i.iter().enumerate(){
b[n] += j;
}
}
let map = conjgrad(a(), b, _tol, _maxiter, p(), pixs.clone());
/***PRINT ON FILE */
println!("");
let id_number = self.get_mcid();
let file_name = format!("gls_{}.dat", id_number);
println!("Print maps on file: {}", file_name.bright_green().bold());
let mut f = File::create(file_name).unwrap();
let sig: Vec<String> = map.iter().map(|a| a.to_string()).collect();
for i in sig.iter() {
writeln!(f, "{}",i).unwrap();
}
println!("{}", "COMPLETED".bright_green());
}// End of GLS_DENOISE
}
// UTILS functions
pub fn fn_noise_prior(f: f32, alpha: f32, f_k: f32, sigma: f32, _n: f32) -> f32 {
let mut _np: f32 = 0.0;
if f > 0.0 {
let _np_g = f32::exp( -((10.0 - f) * (10.0-f)) / (2.0 * 0.0002));
_np = sigma * f32::powf( 1.0 + f_k/(10.0-f), alpha.clone()) + 8E8 * _np_g ;
} else {
let _np_g = f32::exp( -((10.0 + f) * (10.0-f)) / (2.0 * 0.0002));
_np = sigma*sigma * f32::powf( 1.0 + f_k/(10.0+f), alpha.clone()) + 8E8 * _np_g;
}
_np
}
pub fn kaiser(beta: f32, length: i32) -> Vec<f32> {
use crate::misc::bessel_i0 as bessel;
let mut window: Vec<f32> = Vec::new();
let start: f32 = (-(length - 1) / 2) as f32;
let end: f32 = ((length - 1) / 2) as f32;
let n_idx = iteratorscustom::FloatIterator::new(start, end, match length.to_u32(){Some(p) => p, None => 0});
for n in n_idx {
let m = length as f32;
window.push(bessel(beta * (1. - (n / (m / 2.)).powi(2)).sqrt()) / bessel(beta))
}// 70-80
window
}
pub fn hann(length: i32) -> Vec<f32> {
let mut window: Vec<f32> = Vec::new();
let n_idx = iteratorscustom::FloatIterator::new(0.0, length as f32, match length.to_u32(){Some(p) => p, None => 0});
for n in n_idx {
window.push(f32::powi( f32::sin(3.141592 * n / (length as f32)), 2));
}
window
}
pub fn denoise(tod: Vec<f32>, _alpha: f32, _f_k: f32, _sigma: f32, _fs: f32) -> Vec<f32> {
let win: Vec<f32> = kaiser(5.0, match tod.len().to_i32(){Some(p)=>p, None=> 0});//70!!!!!
//let win: Vec<f32> = hann( match tod.len().to_i32(){Some(p)=>p, None=> 0});
// let mut fg = Figure::new();
// fg.axes2d().lines(0..win.len(), win.clone(), &[Caption("Kaiser")]).
// lines(0..win.len(), win_h, &[Caption("Hanning")]);
// fg.show().unwrap();
//let now = Instant::now();
let mut input: Vec<Complex<f32>> = tod.iter().zip(win.iter()).map(|x| Complex32::new(
*x.0 *x.1,
0.0)).
collect(); // ~0
//println!("Denoise process: {}", now.elapsed().as_millis());
let mut planner = FftPlanner::new();
let fft = planner.plan_fft_forward(tod.len()); // 10
//let fft = Radix4::new()
fft.process(&mut input); // 50
let mut noise_p: Vec<f32> = Vec::new();
let freq_iter: FloatIterator = FloatIterator::new(-10.0, 10.0, match input.len().to_u32() {Some(p) => p, None => 0});
let mut freq: Vec<f32> = Vec::new();
for f in freq_iter {
noise_p.push(fn_noise_prior(f, _alpha, _f_k, _sigma, match tod.len().to_f32(){Some(p)=>p, None=>0.0} ));
freq.push(f);
}
// Denoise
let mut tod_denoised: Vec<Complex32> = input.iter().zip(noise_p.iter()).map(|(a, b)| {
let (_, angle) = a.to_polar();
let module = a.norm()/b;
Complex32::from_polar(module, angle)
}).collect();
// let mut fg = Figure::new();
// fg.axes2d().points(0..input.len()/2, input.iter().map(|t| t.re).collect::<Vec<f32>>(), &[Caption("FFT - raw")]).set_x_log(Some(10.0)).set_y_log(Some(10.0)).
// points(0..tod_denoised.len()/2, tod_denoised.iter().map(|f| f.re).collect::<Vec<f32>>(), &[Caption("FFT - denoised")]).set_x_log(Some(10.0)).set_y_log(Some(10.0)).
// lines(0..noise_p.len()/2, noise_p, &[Caption("Noise model")]);
// fg.show().unwrap();
let mut planner = FftPlanner::new(); // 60
let ifft = planner.plan_fft_inverse(tod.len());
ifft.process(&mut tod_denoised);
let tod_denoised: Vec<Complex32> = tod_denoised.iter().map(|c| {
let (module, angle) = c.to_polar();
let module2 = module / (tod.len() as f32);
Complex32::from_polar(module2, angle)
}).collect();
let tod_real: Vec<f32> = tod_denoised.iter().zip( win.iter()).map(|t| t.0.re / t.1 ).collect();
// let mut fg = Figure::new();
// fg.axes2d().lines(0..tod_real.len(), tod_real.clone(), &[Caption("TOD denoised")]).lines(0..tod.len(), tod, &[Caption("TOD RAW")]);
// fg.show().unwrap();
tod_real
}
pub fn get_b(tod: Vec<f32>, pix: Vec<i32>, nside: usize) -> Vec<f32> {
let mut b: Vec<f32> = vec![0.0; 12*128*128];
let tod_n = denoise(tod.clone(), 4.0/3.0, 7.0, 30.0, 20.0);
let (map, _) = bin_map(tod_n.clone(), pix, nside);
for i in 0..12*nside*nside {
b[i] += map[i];
}
b
}
fn a() -> Box<dyn Fn(Vec<f32>, Vec<Vec<i32>>) -> Vec<f32>> {
Box::new(|_x: Vec<f32>, pointings: Vec<Vec<i32>>| {
let mut temp_maps: Vec<Vec<f32>> = Vec::new();
let mut res: Vec<f32> = vec![0.0; 12*128*128];
let num_threads = num_cpus::get();
let pool_denoise = ThreadPool::new(num_threads);
let (tx, rx) = mpsc::channel();
for i_det in pointings.iter() {
let mut tmp: Vec<f32> = Vec::new();
let tx = tx.clone();
let point_i = i_det.clone();
let x = _x.clone();
pool_denoise.execute(move ||{
for i in point_i.iter() {
tmp.push(x[*i as usize]);
}
let tmp_denoised = denoise(tmp.clone(), 4.0/3.0, 7.0, 30.0, 20.0);
let (map, _) = bin_map(tmp_denoised.clone(), point_i.clone(), 128);
// let mut final_map = Vec::new();
// for (m, h) in map.iter().zip(hit.iter()) {
// final_map.push(m.clone()/(h.clone() as f32));
// }
tx.send(map).unwrap();
});
}
for _i in 0..pointings.len() {
temp_maps.push(rx.recv().unwrap());
}
for map in temp_maps.iter() {
res = res.iter().zip(map.iter()).map(|(r, m)| r+m).collect::<Vec<f32>>();
}
res
})
}
pub fn p() -> Box<dyn Fn(Vec<f32>) -> Vec<f32>> {
Box::new(|m| m.iter().map(|m| { 1.0*m } ).collect::<Vec<f32>>())
}
pub fn bin_map(tod: Vec<f32>, pix: Vec<i32>, nside: usize) -> (Vec<f32>, Vec<i32>) {
let num_pixs: usize = 12*nside*nside;
let mut signal_map: Vec<f32> = vec![0.0; num_pixs];
let mut hit_map: Vec<i32> = vec![0; num_pixs];
let mut iterator: usize = 0;
for i in pix.iter() {
let pixel = match i.to_usize(){Some(p)=> p, None=> 0};
hit_map[pixel] += 1;
signal_map[pixel] += tod[iterator];
iterator += 1;
}
(signal_map, hit_map)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_obs() {
let nside = 128;
let sky = vec![0.0; 12*nside*nside];
let obs = Obs::new(
String::from("start"),
String::from("stop"),
vec![String::from("det1")],
1,
1.0,
0.01,
vec![vec![300.0, 300.0, 300.0]],
sky,
vec![vec![1, 1, 3]]
);
let bin_map = obs.binning();
let sig_1_map = bin_map.0[1];
let pix_1_map = bin_map.1[1];
assert_eq!(sig_1_map, 0.54*(300.0+300.0));
assert_eq!(pix_1_map, 2);
}
} | {
&self.mc_id
} | identifier_body |
lib.rs | /*!
# Strip MapMaking library
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur facilisis consectetur arcu. Etiam semper, sem sit amet lacinia dignissim, mauris eros rutrum massa, a imperdiet orci urna vel elit. Nulla at sagittis lacus. Curabitur eu gravida turpis. Mauris blandit porta orci. Aliquam fringilla felis a sem aliquet rhoncus. Suspendisse porta, mi vel euismod porta, mi ex cursus diam, quis iaculis sapien massa eget massa. Fusce sit amet neque vel turpis interdum tempus et non nisl. Nunc aliquam nunc vitae justo accumsan pretium. Morbi eget urna quis ex pellentesque molestie. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer vehicula vehicula tortor sit amet dignissim. Duis finibus, felis ut fringilla tincidunt, mi lectus fermentum eros, ut laoreet justo lacus id urna.
Duis iaculis faucibus mollis. Maecenas dignissim efficitur ex. Sed pulvinar justo a arcu lobortis imperdiet. Suspendisse placerat venenatis volutpat. Aenean eu nulla vitae libero porta dignissim ut sit amet ante. Vestibulum porttitor sodales nibh, nec imperdiet tortor accumsan quis. Ut sagittis arcu eu efficitur varius. Etiam at ex condimentum, volutpat ipsum sed, posuere nibh. Sed posuere fringilla mi in commodo. Ut sodales, elit volutpat finibus dapibus, dui lacus porttitor enim, ac placerat erat ligula quis ipsum. Morbi sagittis et nisl mollis fringilla. Praesent commodo faucibus erat, nec congue lectus finibus vitae. Sed eu ipsum in lorem congue vehicula.
# Using the Strip MapMaking
Duis iaculis faucibus mollis. Maecenas dignissim efficitur ex. Sed pulvinar justo a arcu lobortis imperdiet. Suspendisse placerat venenatis volutpat. Aenean eu nulla vitae libero porta dignissim ut sit amet ante. Vestibulum porttitor sodales nibh, nec imperdiet tortor accumsan quis. Ut sagittis arcu eu efficitur varius. Etiam at ex condimentum, volutpat ipsum sed, posuere nibh. Sed posuere fringilla mi in commodo. Ut sodales, elit volutpat finibus dapibus, dui lacus porttitor enim, ac placerat erat ligula quis ipsum. Morbi sagittis et nisl mollis fringilla. Praesent commodo faucibus erat, nec congue lectus finibus vitae. Sed eu ipsum in lorem congue vehicula.
*/
extern crate rustfft;
pub mod directory;
pub mod iteratorscustom;
pub mod sky;
pub mod threadpool;
pub mod misc;
pub mod noisemodel;
pub mod plot_suite;
pub mod conjugategradient;
use threadpool::ThreadPool;
use std::{fs::File, io::Write, sync::mpsc, usize, vec};
use colored::Colorize;
use conjugategradient::conjgrad;
use iteratorscustom::FloatIterator;
use num::{ToPrimitive, complex::Complex32};
use rustfft::{FftPlanner, num_complex::Complex};
// use rustfft::algorithm::Radix4;
// use noisemodel::NoiseModel;
// use std::time::Instant;
// use gnuplot::*;
use std::marker::PhantomData;
#[derive(Debug)]
pub struct Obs <'a> {
start: String,
stop: String,
detector: Vec<String>,
mc_id: u8,
alpha: f32,
f_knee: f32,
pix: Vec<Vec<i32>>,
tod: Vec<Vec<f32>>,
sky_t: Vec<f32>,
phantom: PhantomData<&'a f32>,
}
// ```
// Documentation
// Creation function
// ```
impl <'a> Obs <'a> {
pub fn new(
start: String,
stop: String,
detector: Vec<String>,
mc_id: u8,
alpha: f32,
f_knee: f32,
tod: Vec<Vec<f32>>,
sky: Vec<f32>,
pix: Vec<Vec<i32>> ) -> Self
{
let mut tod_final: Vec<Vec<f32>> = Vec::new();
for (i, j) in tod.iter().zip(pix.iter()){
//let noise = NoiseModel::new(50.0, 7e9, 1.0/20.0, 0.1, 1.0, 123, i.len());
//let tod_noise = noise.get_noise_tod();
let mut tmp: Vec<f32> = Vec::new();
for (_n, (k, l)) in i.into_iter().zip(j.iter()).enumerate(){
let t_sky = sky[match l.to_usize() {Some(p) => p, None=>0}];
//let r = tod_noise[_n];
tmp.push(0.54*k + t_sky);
}
tod_final.push(tmp);
}
return Obs {
start,
stop,
detector,
mc_id,
alpha,
f_knee,
pix,
tod: tod_final,
sky_t: sky,
phantom: PhantomData,
}
}
}
// The `get` methods
impl <'a> Obs <'a>{
pub fn get_start(&self) -> &String {
&self.start
}
pub fn get_stop(&self) -> &String {
&self.stop
}
pub fn get_detector(&self) -> &Vec<String> {
&self.detector
}
pub fn get_mcid(&self) -> &u8 {
&self.mc_id
}
pub fn | (&self) -> &Vec<Vec<i32>> {
&self.pix
}
pub fn get_tod(&self) -> &Vec<Vec<f32>> {
&self.tod
}
}
// Mitigation of the systematic effects
// Starting from the binning, to the
// implementation of a de_noise model
impl <'a> Obs <'a>{
pub fn binning(&self) -> (Vec<f32>, Vec<i32>) {
println!("");
println!("Start {}", "binning".bright_blue().bold());
const NSIDE: usize = 128;
const NUM_PIX: usize = NSIDE*NSIDE*12;
let mut signal_maps: Vec<Vec<f32>> = Vec::new();
let mut hit_maps: Vec<Vec<i32>> = Vec::new();
let pix = &self.pix;
let tod = &self.tod;
let num_threads = num_cpus::get();
let bin_pool = ThreadPool::new(num_threads);
let (tx, rx) = mpsc::channel();
for i in 0..tod.len() {
let t = tod[i].clone();
let p = pix[i].clone();
let tx = tx.clone();
bin_pool.execute(move ||{
let (sig_par, hit_par) = bin_map(t.clone(), p.clone(), 128);
tx.send((sig_par, hit_par)).unwrap();
});
}
for _i in 0..tod.len() {
let rec = rx.recv().unwrap();
signal_maps.push(rec.0.clone());
hit_maps.push(rec.1.clone());
}
let mut final_sig: Vec<f32> = vec![0.0; NUM_PIX];
let mut final_hit: Vec<i32> = vec![0; NUM_PIX];
for idx in 0..signal_maps.len() {
let s = signal_maps[idx].clone();
let h = hit_maps[idx].clone();
for pidx in 0..NUM_PIX{
let signal = s[pidx];
let hits = h[pidx];
final_sig[pidx] += signal;
final_hit[pidx] += hits;
}
}
println!("{}", "COMPLETED".bright_green());
/***PRINT ON FILE */
println!("");
let id_number = self.get_mcid();
let file_name = format!("binned_{}.dat", id_number);
println!("Print maps on file: {}", file_name.bright_green().bold());
let mut f = File::create(file_name).unwrap();
let hit: Vec<String> = final_hit.iter().map(|a| a.to_string()).collect();
let sig: Vec<String> = final_sig.iter().map(|a| a.to_string()).collect();
for (i,j) in hit.iter().zip(sig.iter()) {
writeln!(f, "{}\t{}",i, j).unwrap();
}
println!("{}", "COMPLETED".bright_green());
(final_sig, final_hit)
}
}
// GLS DENOISE
impl <'a> Obs <'a>{
pub fn gls_denoise(&self, _tol: f32, _maxiter: usize, _nside: usize){
println!("{}", "Execution of the gls_denoise".bright_blue().bold());
const NUM_PIX: usize = 12*128*128;
let _x: Vec<f32> = vec![0.0; NUM_PIX];
let (tx, rx) = mpsc::channel();
let tods = &self.tod;
let pixs = &self.pix;
//println!("Len TODs: {}", tods.len()); // 55 * n_hour
let mut partial_maps: Vec<Vec<f32>> = Vec::new();
let num_threads = num_cpus::get();
let my_pool_b = ThreadPool::new(num_threads);
for idx_th in 0..tods.len() {
let t = tods[idx_th].clone();
let p = pixs[idx_th].clone();
let tx = tx.clone();
my_pool_b.execute(move || {
let b = get_b(t, p, 128);
tx.send(b).expect("channel will be there waiting for the pool");
});
}
for _ in 0..tods.len(){
partial_maps.push(rx.recv().unwrap());
}
let mut b: Vec<f32> = vec![0.0; 12*128*128];
for i in partial_maps.iter(){
for (n,j) in i.iter().enumerate(){
b[n] += j;
}
}
let map = conjgrad(a(), b, _tol, _maxiter, p(), pixs.clone());
/***PRINT ON FILE */
println!("");
let id_number = self.get_mcid();
let file_name = format!("gls_{}.dat", id_number);
println!("Print maps on file: {}", file_name.bright_green().bold());
let mut f = File::create(file_name).unwrap();
let sig: Vec<String> = map.iter().map(|a| a.to_string()).collect();
for i in sig.iter() {
writeln!(f, "{}",i).unwrap();
}
println!("{}", "COMPLETED".bright_green());
}// End of GLS_DENOISE
}
// UTILS functions
pub fn fn_noise_prior(f: f32, alpha: f32, f_k: f32, sigma: f32, _n: f32) -> f32 {
let mut _np: f32 = 0.0;
if f > 0.0 {
let _np_g = f32::exp( -((10.0 - f) * (10.0-f)) / (2.0 * 0.0002));
_np = sigma * f32::powf( 1.0 + f_k/(10.0-f), alpha.clone()) + 8E8 * _np_g ;
} else {
let _np_g = f32::exp( -((10.0 + f) * (10.0-f)) / (2.0 * 0.0002));
_np = sigma*sigma * f32::powf( 1.0 + f_k/(10.0+f), alpha.clone()) + 8E8 * _np_g;
}
_np
}
pub fn kaiser(beta: f32, length: i32) -> Vec<f32> {
use crate::misc::bessel_i0 as bessel;
let mut window: Vec<f32> = Vec::new();
let start: f32 = (-(length - 1) / 2) as f32;
let end: f32 = ((length - 1) / 2) as f32;
let n_idx = iteratorscustom::FloatIterator::new(start, end, match length.to_u32(){Some(p) => p, None => 0});
for n in n_idx {
let m = length as f32;
window.push(bessel(beta * (1. - (n / (m / 2.)).powi(2)).sqrt()) / bessel(beta))
}// 70-80
window
}
pub fn hann(length: i32) -> Vec<f32> {
let mut window: Vec<f32> = Vec::new();
let n_idx = iteratorscustom::FloatIterator::new(0.0, length as f32, match length.to_u32(){Some(p) => p, None => 0});
for n in n_idx {
window.push(f32::powi( f32::sin(3.141592 * n / (length as f32)), 2));
}
window
}
pub fn denoise(tod: Vec<f32>, _alpha: f32, _f_k: f32, _sigma: f32, _fs: f32) -> Vec<f32> {
let win: Vec<f32> = kaiser(5.0, match tod.len().to_i32(){Some(p)=>p, None=> 0});//70!!!!!
//let win: Vec<f32> = hann( match tod.len().to_i32(){Some(p)=>p, None=> 0});
// let mut fg = Figure::new();
// fg.axes2d().lines(0..win.len(), win.clone(), &[Caption("Kaiser")]).
// lines(0..win.len(), win_h, &[Caption("Hanning")]);
// fg.show().unwrap();
//let now = Instant::now();
let mut input: Vec<Complex<f32>> = tod.iter().zip(win.iter()).map(|x| Complex32::new(
*x.0 *x.1,
0.0)).
collect(); // ~0
//println!("Denoise process: {}", now.elapsed().as_millis());
let mut planner = FftPlanner::new();
let fft = planner.plan_fft_forward(tod.len()); // 10
//let fft = Radix4::new()
fft.process(&mut input); // 50
let mut noise_p: Vec<f32> = Vec::new();
let freq_iter: FloatIterator = FloatIterator::new(-10.0, 10.0, match input.len().to_u32() {Some(p) => p, None => 0});
let mut freq: Vec<f32> = Vec::new();
for f in freq_iter {
noise_p.push(fn_noise_prior(f, _alpha, _f_k, _sigma, match tod.len().to_f32(){Some(p)=>p, None=>0.0} ));
freq.push(f);
}
// Denoise
let mut tod_denoised: Vec<Complex32> = input.iter().zip(noise_p.iter()).map(|(a, b)| {
let (_, angle) = a.to_polar();
let module = a.norm()/b;
Complex32::from_polar(module, angle)
}).collect();
// let mut fg = Figure::new();
// fg.axes2d().points(0..input.len()/2, input.iter().map(|t| t.re).collect::<Vec<f32>>(), &[Caption("FFT - raw")]).set_x_log(Some(10.0)).set_y_log(Some(10.0)).
// points(0..tod_denoised.len()/2, tod_denoised.iter().map(|f| f.re).collect::<Vec<f32>>(), &[Caption("FFT - denoised")]).set_x_log(Some(10.0)).set_y_log(Some(10.0)).
// lines(0..noise_p.len()/2, noise_p, &[Caption("Noise model")]);
// fg.show().unwrap();
let mut planner = FftPlanner::new(); // 60
let ifft = planner.plan_fft_inverse(tod.len());
ifft.process(&mut tod_denoised);
let tod_denoised: Vec<Complex32> = tod_denoised.iter().map(|c| {
let (module, angle) = c.to_polar();
let module2 = module / (tod.len() as f32);
Complex32::from_polar(module2, angle)
}).collect();
let tod_real: Vec<f32> = tod_denoised.iter().zip( win.iter()).map(|t| t.0.re / t.1 ).collect();
// let mut fg = Figure::new();
// fg.axes2d().lines(0..tod_real.len(), tod_real.clone(), &[Caption("TOD denoised")]).lines(0..tod.len(), tod, &[Caption("TOD RAW")]);
// fg.show().unwrap();
tod_real
}
pub fn get_b(tod: Vec<f32>, pix: Vec<i32>, nside: usize) -> Vec<f32> {
let mut b: Vec<f32> = vec![0.0; 12*128*128];
let tod_n = denoise(tod.clone(), 4.0/3.0, 7.0, 30.0, 20.0);
let (map, _) = bin_map(tod_n.clone(), pix, nside);
for i in 0..12*nside*nside {
b[i] += map[i];
}
b
}
fn a() -> Box<dyn Fn(Vec<f32>, Vec<Vec<i32>>) -> Vec<f32>> {
Box::new(|_x: Vec<f32>, pointings: Vec<Vec<i32>>| {
let mut temp_maps: Vec<Vec<f32>> = Vec::new();
let mut res: Vec<f32> = vec![0.0; 12*128*128];
let num_threads = num_cpus::get();
let pool_denoise = ThreadPool::new(num_threads);
let (tx, rx) = mpsc::channel();
for i_det in pointings.iter() {
let mut tmp: Vec<f32> = Vec::new();
let tx = tx.clone();
let point_i = i_det.clone();
let x = _x.clone();
pool_denoise.execute(move ||{
for i in point_i.iter() {
tmp.push(x[*i as usize]);
}
let tmp_denoised = denoise(tmp.clone(), 4.0/3.0, 7.0, 30.0, 20.0);
let (map, _) = bin_map(tmp_denoised.clone(), point_i.clone(), 128);
// let mut final_map = Vec::new();
// for (m, h) in map.iter().zip(hit.iter()) {
// final_map.push(m.clone()/(h.clone() as f32));
// }
tx.send(map).unwrap();
});
}
for _i in 0..pointings.len() {
temp_maps.push(rx.recv().unwrap());
}
for map in temp_maps.iter() {
res = res.iter().zip(map.iter()).map(|(r, m)| r+m).collect::<Vec<f32>>();
}
res
})
}
pub fn p() -> Box<dyn Fn(Vec<f32>) -> Vec<f32>> {
Box::new(|m| m.iter().map(|m| { 1.0*m } ).collect::<Vec<f32>>())
}
pub fn bin_map(tod: Vec<f32>, pix: Vec<i32>, nside: usize) -> (Vec<f32>, Vec<i32>) {
let num_pixs: usize = 12*nside*nside;
let mut signal_map: Vec<f32> = vec![0.0; num_pixs];
let mut hit_map: Vec<i32> = vec![0; num_pixs];
let mut iterator: usize = 0;
for i in pix.iter() {
let pixel = match i.to_usize(){Some(p)=> p, None=> 0};
hit_map[pixel] += 1;
signal_map[pixel] += tod[iterator];
iterator += 1;
}
(signal_map, hit_map)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_obs() {
let nside = 128;
let sky = vec![0.0; 12*nside*nside];
let obs = Obs::new(
String::from("start"),
String::from("stop"),
vec![String::from("det1")],
1,
1.0,
0.01,
vec![vec![300.0, 300.0, 300.0]],
sky,
vec![vec![1, 1, 3]]
);
let bin_map = obs.binning();
let sig_1_map = bin_map.0[1];
let pix_1_map = bin_map.1[1];
assert_eq!(sig_1_map, 0.54*(300.0+300.0));
assert_eq!(pix_1_map, 2);
}
} | get_pix | identifier_name |
lib.rs | /*!
# Strip MapMaking library
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur facilisis consectetur arcu. Etiam semper, sem sit amet lacinia dignissim, mauris eros rutrum massa, a imperdiet orci urna vel elit. Nulla at sagittis lacus. Curabitur eu gravida turpis. Mauris blandit porta orci. Aliquam fringilla felis a sem aliquet rhoncus. Suspendisse porta, mi vel euismod porta, mi ex cursus diam, quis iaculis sapien massa eget massa. Fusce sit amet neque vel turpis interdum tempus et non nisl. Nunc aliquam nunc vitae justo accumsan pretium. Morbi eget urna quis ex pellentesque molestie. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer vehicula vehicula tortor sit amet dignissim. Duis finibus, felis ut fringilla tincidunt, mi lectus fermentum eros, ut laoreet justo lacus id urna.
Duis iaculis faucibus mollis. Maecenas dignissim efficitur ex. Sed pulvinar justo a arcu lobortis imperdiet. Suspendisse placerat venenatis volutpat. Aenean eu nulla vitae libero porta dignissim ut sit amet ante. Vestibulum porttitor sodales nibh, nec imperdiet tortor accumsan quis. Ut sagittis arcu eu efficitur varius. Etiam at ex condimentum, volutpat ipsum sed, posuere nibh. Sed posuere fringilla mi in commodo. Ut sodales, elit volutpat finibus dapibus, dui lacus porttitor enim, ac placerat erat ligula quis ipsum. Morbi sagittis et nisl mollis fringilla. Praesent commodo faucibus erat, nec congue lectus finibus vitae. Sed eu ipsum in lorem congue vehicula.
# Using the Strip MapMaking
Duis iaculis faucibus mollis. Maecenas dignissim efficitur ex. Sed pulvinar justo a arcu lobortis imperdiet. Suspendisse placerat venenatis volutpat. Aenean eu nulla vitae libero porta dignissim ut sit amet ante. Vestibulum porttitor sodales nibh, nec imperdiet tortor accumsan quis. Ut sagittis arcu eu efficitur varius. Etiam at ex condimentum, volutpat ipsum sed, posuere nibh. Sed posuere fringilla mi in commodo. Ut sodales, elit volutpat finibus dapibus, dui lacus porttitor enim, ac placerat erat ligula quis ipsum. Morbi sagittis et nisl mollis fringilla. Praesent commodo faucibus erat, nec congue lectus finibus vitae. Sed eu ipsum in lorem congue vehicula.
*/
extern crate rustfft;
pub mod directory;
pub mod iteratorscustom;
pub mod sky;
pub mod threadpool;
pub mod misc;
pub mod noisemodel;
pub mod plot_suite;
pub mod conjugategradient;
use threadpool::ThreadPool;
use std::{fs::File, io::Write, sync::mpsc, usize, vec};
use colored::Colorize;
use conjugategradient::conjgrad;
use iteratorscustom::FloatIterator;
use num::{ToPrimitive, complex::Complex32};
use rustfft::{FftPlanner, num_complex::Complex};
// use rustfft::algorithm::Radix4;
// use noisemodel::NoiseModel;
// use std::time::Instant;
// use gnuplot::*;
use std::marker::PhantomData;
#[derive(Debug)]
pub struct Obs <'a> {
start: String,
stop: String,
detector: Vec<String>,
mc_id: u8,
alpha: f32,
f_knee: f32,
pix: Vec<Vec<i32>>,
tod: Vec<Vec<f32>>,
sky_t: Vec<f32>,
phantom: PhantomData<&'a f32>,
}
// ```
// Documentation
// Creation function
// ```
impl <'a> Obs <'a> {
pub fn new(
start: String,
stop: String,
detector: Vec<String>,
mc_id: u8,
alpha: f32,
f_knee: f32,
tod: Vec<Vec<f32>>,
sky: Vec<f32>,
pix: Vec<Vec<i32>> ) -> Self
{
let mut tod_final: Vec<Vec<f32>> = Vec::new();
for (i, j) in tod.iter().zip(pix.iter()){
//let noise = NoiseModel::new(50.0, 7e9, 1.0/20.0, 0.1, 1.0, 123, i.len());
//let tod_noise = noise.get_noise_tod();
let mut tmp: Vec<f32> = Vec::new();
for (_n, (k, l)) in i.into_iter().zip(j.iter()).enumerate(){
let t_sky = sky[match l.to_usize() {Some(p) => p, None=>0}];
//let r = tod_noise[_n];
tmp.push(0.54*k + t_sky);
} | }
return Obs {
start,
stop,
detector,
mc_id,
alpha,
f_knee,
pix,
tod: tod_final,
sky_t: sky,
phantom: PhantomData,
}
}
}
// The `get` methods
impl <'a> Obs <'a>{
pub fn get_start(&self) -> &String {
&self.start
}
pub fn get_stop(&self) -> &String {
&self.stop
}
pub fn get_detector(&self) -> &Vec<String> {
&self.detector
}
pub fn get_mcid(&self) -> &u8 {
&self.mc_id
}
pub fn get_pix(&self) -> &Vec<Vec<i32>> {
&self.pix
}
pub fn get_tod(&self) -> &Vec<Vec<f32>> {
&self.tod
}
}
// Mitigation of the systematic effects
// Starting from the binning, to the
// implementation of a de_noise model
impl <'a> Obs <'a>{
pub fn binning(&self) -> (Vec<f32>, Vec<i32>) {
println!("");
println!("Start {}", "binning".bright_blue().bold());
const NSIDE: usize = 128;
const NUM_PIX: usize = NSIDE*NSIDE*12;
let mut signal_maps: Vec<Vec<f32>> = Vec::new();
let mut hit_maps: Vec<Vec<i32>> = Vec::new();
let pix = &self.pix;
let tod = &self.tod;
let num_threads = num_cpus::get();
let bin_pool = ThreadPool::new(num_threads);
let (tx, rx) = mpsc::channel();
for i in 0..tod.len() {
let t = tod[i].clone();
let p = pix[i].clone();
let tx = tx.clone();
bin_pool.execute(move ||{
let (sig_par, hit_par) = bin_map(t.clone(), p.clone(), 128);
tx.send((sig_par, hit_par)).unwrap();
});
}
for _i in 0..tod.len() {
let rec = rx.recv().unwrap();
signal_maps.push(rec.0.clone());
hit_maps.push(rec.1.clone());
}
let mut final_sig: Vec<f32> = vec![0.0; NUM_PIX];
let mut final_hit: Vec<i32> = vec![0; NUM_PIX];
for idx in 0..signal_maps.len() {
let s = signal_maps[idx].clone();
let h = hit_maps[idx].clone();
for pidx in 0..NUM_PIX{
let signal = s[pidx];
let hits = h[pidx];
final_sig[pidx] += signal;
final_hit[pidx] += hits;
}
}
println!("{}", "COMPLETED".bright_green());
/***PRINT ON FILE */
println!("");
let id_number = self.get_mcid();
let file_name = format!("binned_{}.dat", id_number);
println!("Print maps on file: {}", file_name.bright_green().bold());
let mut f = File::create(file_name).unwrap();
let hit: Vec<String> = final_hit.iter().map(|a| a.to_string()).collect();
let sig: Vec<String> = final_sig.iter().map(|a| a.to_string()).collect();
for (i,j) in hit.iter().zip(sig.iter()) {
writeln!(f, "{}\t{}",i, j).unwrap();
}
println!("{}", "COMPLETED".bright_green());
(final_sig, final_hit)
}
}
// GLS DENOISE
impl <'a> Obs <'a>{
pub fn gls_denoise(&self, _tol: f32, _maxiter: usize, _nside: usize){
println!("{}", "Execution of the gls_denoise".bright_blue().bold());
const NUM_PIX: usize = 12*128*128;
let _x: Vec<f32> = vec![0.0; NUM_PIX];
let (tx, rx) = mpsc::channel();
let tods = &self.tod;
let pixs = &self.pix;
//println!("Len TODs: {}", tods.len()); // 55 * n_hour
let mut partial_maps: Vec<Vec<f32>> = Vec::new();
let num_threads = num_cpus::get();
let my_pool_b = ThreadPool::new(num_threads);
for idx_th in 0..tods.len() {
let t = tods[idx_th].clone();
let p = pixs[idx_th].clone();
let tx = tx.clone();
my_pool_b.execute(move || {
let b = get_b(t, p, 128);
tx.send(b).expect("channel will be there waiting for the pool");
});
}
for _ in 0..tods.len(){
partial_maps.push(rx.recv().unwrap());
}
let mut b: Vec<f32> = vec![0.0; 12*128*128];
for i in partial_maps.iter(){
for (n,j) in i.iter().enumerate(){
b[n] += j;
}
}
let map = conjgrad(a(), b, _tol, _maxiter, p(), pixs.clone());
/***PRINT ON FILE */
println!("");
let id_number = self.get_mcid();
let file_name = format!("gls_{}.dat", id_number);
println!("Print maps on file: {}", file_name.bright_green().bold());
let mut f = File::create(file_name).unwrap();
let sig: Vec<String> = map.iter().map(|a| a.to_string()).collect();
for i in sig.iter() {
writeln!(f, "{}",i).unwrap();
}
println!("{}", "COMPLETED".bright_green());
}// End of GLS_DENOISE
}
// UTILS functions
pub fn fn_noise_prior(f: f32, alpha: f32, f_k: f32, sigma: f32, _n: f32) -> f32 {
let mut _np: f32 = 0.0;
if f > 0.0 {
let _np_g = f32::exp( -((10.0 - f) * (10.0-f)) / (2.0 * 0.0002));
_np = sigma * f32::powf( 1.0 + f_k/(10.0-f), alpha.clone()) + 8E8 * _np_g ;
} else {
let _np_g = f32::exp( -((10.0 + f) * (10.0-f)) / (2.0 * 0.0002));
_np = sigma*sigma * f32::powf( 1.0 + f_k/(10.0+f), alpha.clone()) + 8E8 * _np_g;
}
_np
}
pub fn kaiser(beta: f32, length: i32) -> Vec<f32> {
use crate::misc::bessel_i0 as bessel;
let mut window: Vec<f32> = Vec::new();
let start: f32 = (-(length - 1) / 2) as f32;
let end: f32 = ((length - 1) / 2) as f32;
let n_idx = iteratorscustom::FloatIterator::new(start, end, match length.to_u32(){Some(p) => p, None => 0});
for n in n_idx {
let m = length as f32;
window.push(bessel(beta * (1. - (n / (m / 2.)).powi(2)).sqrt()) / bessel(beta))
}// 70-80
window
}
pub fn hann(length: i32) -> Vec<f32> {
let mut window: Vec<f32> = Vec::new();
let n_idx = iteratorscustom::FloatIterator::new(0.0, length as f32, match length.to_u32(){Some(p) => p, None => 0});
for n in n_idx {
window.push(f32::powi( f32::sin(3.141592 * n / (length as f32)), 2));
}
window
}
pub fn denoise(tod: Vec<f32>, _alpha: f32, _f_k: f32, _sigma: f32, _fs: f32) -> Vec<f32> {
let win: Vec<f32> = kaiser(5.0, match tod.len().to_i32(){Some(p)=>p, None=> 0});//70!!!!!
//let win: Vec<f32> = hann( match tod.len().to_i32(){Some(p)=>p, None=> 0});
// let mut fg = Figure::new();
// fg.axes2d().lines(0..win.len(), win.clone(), &[Caption("Kaiser")]).
// lines(0..win.len(), win_h, &[Caption("Hanning")]);
// fg.show().unwrap();
//let now = Instant::now();
let mut input: Vec<Complex<f32>> = tod.iter().zip(win.iter()).map(|x| Complex32::new(
*x.0 *x.1,
0.0)).
collect(); // ~0
//println!("Denoise process: {}", now.elapsed().as_millis());
let mut planner = FftPlanner::new();
let fft = planner.plan_fft_forward(tod.len()); // 10
//let fft = Radix4::new()
fft.process(&mut input); // 50
let mut noise_p: Vec<f32> = Vec::new();
let freq_iter: FloatIterator = FloatIterator::new(-10.0, 10.0, match input.len().to_u32() {Some(p) => p, None => 0});
let mut freq: Vec<f32> = Vec::new();
for f in freq_iter {
noise_p.push(fn_noise_prior(f, _alpha, _f_k, _sigma, match tod.len().to_f32(){Some(p)=>p, None=>0.0} ));
freq.push(f);
}
// Denoise
let mut tod_denoised: Vec<Complex32> = input.iter().zip(noise_p.iter()).map(|(a, b)| {
let (_, angle) = a.to_polar();
let module = a.norm()/b;
Complex32::from_polar(module, angle)
}).collect();
// let mut fg = Figure::new();
// fg.axes2d().points(0..input.len()/2, input.iter().map(|t| t.re).collect::<Vec<f32>>(), &[Caption("FFT - raw")]).set_x_log(Some(10.0)).set_y_log(Some(10.0)).
// points(0..tod_denoised.len()/2, tod_denoised.iter().map(|f| f.re).collect::<Vec<f32>>(), &[Caption("FFT - denoised")]).set_x_log(Some(10.0)).set_y_log(Some(10.0)).
// lines(0..noise_p.len()/2, noise_p, &[Caption("Noise model")]);
// fg.show().unwrap();
let mut planner = FftPlanner::new(); // 60
let ifft = planner.plan_fft_inverse(tod.len());
ifft.process(&mut tod_denoised);
let tod_denoised: Vec<Complex32> = tod_denoised.iter().map(|c| {
let (module, angle) = c.to_polar();
let module2 = module / (tod.len() as f32);
Complex32::from_polar(module2, angle)
}).collect();
let tod_real: Vec<f32> = tod_denoised.iter().zip( win.iter()).map(|t| t.0.re / t.1 ).collect();
// let mut fg = Figure::new();
// fg.axes2d().lines(0..tod_real.len(), tod_real.clone(), &[Caption("TOD denoised")]).lines(0..tod.len(), tod, &[Caption("TOD RAW")]);
// fg.show().unwrap();
tod_real
}
pub fn get_b(tod: Vec<f32>, pix: Vec<i32>, nside: usize) -> Vec<f32> {
let mut b: Vec<f32> = vec![0.0; 12*128*128];
let tod_n = denoise(tod.clone(), 4.0/3.0, 7.0, 30.0, 20.0);
let (map, _) = bin_map(tod_n.clone(), pix, nside);
for i in 0..12*nside*nside {
b[i] += map[i];
}
b
}
fn a() -> Box<dyn Fn(Vec<f32>, Vec<Vec<i32>>) -> Vec<f32>> {
Box::new(|_x: Vec<f32>, pointings: Vec<Vec<i32>>| {
let mut temp_maps: Vec<Vec<f32>> = Vec::new();
let mut res: Vec<f32> = vec![0.0; 12*128*128];
let num_threads = num_cpus::get();
let pool_denoise = ThreadPool::new(num_threads);
let (tx, rx) = mpsc::channel();
for i_det in pointings.iter() {
let mut tmp: Vec<f32> = Vec::new();
let tx = tx.clone();
let point_i = i_det.clone();
let x = _x.clone();
pool_denoise.execute(move ||{
for i in point_i.iter() {
tmp.push(x[*i as usize]);
}
let tmp_denoised = denoise(tmp.clone(), 4.0/3.0, 7.0, 30.0, 20.0);
let (map, _) = bin_map(tmp_denoised.clone(), point_i.clone(), 128);
// let mut final_map = Vec::new();
// for (m, h) in map.iter().zip(hit.iter()) {
// final_map.push(m.clone()/(h.clone() as f32));
// }
tx.send(map).unwrap();
});
}
for _i in 0..pointings.len() {
temp_maps.push(rx.recv().unwrap());
}
for map in temp_maps.iter() {
res = res.iter().zip(map.iter()).map(|(r, m)| r+m).collect::<Vec<f32>>();
}
res
})
}
pub fn p() -> Box<dyn Fn(Vec<f32>) -> Vec<f32>> {
Box::new(|m| m.iter().map(|m| { 1.0*m } ).collect::<Vec<f32>>())
}
pub fn bin_map(tod: Vec<f32>, pix: Vec<i32>, nside: usize) -> (Vec<f32>, Vec<i32>) {
let num_pixs: usize = 12*nside*nside;
let mut signal_map: Vec<f32> = vec![0.0; num_pixs];
let mut hit_map: Vec<i32> = vec![0; num_pixs];
let mut iterator: usize = 0;
for i in pix.iter() {
let pixel = match i.to_usize(){Some(p)=> p, None=> 0};
hit_map[pixel] += 1;
signal_map[pixel] += tod[iterator];
iterator += 1;
}
(signal_map, hit_map)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_obs() {
let nside = 128;
let sky = vec![0.0; 12*nside*nside];
let obs = Obs::new(
String::from("start"),
String::from("stop"),
vec![String::from("det1")],
1,
1.0,
0.01,
vec![vec![300.0, 300.0, 300.0]],
sky,
vec![vec![1, 1, 3]]
);
let bin_map = obs.binning();
let sig_1_map = bin_map.0[1];
let pix_1_map = bin_map.1[1];
assert_eq!(sig_1_map, 0.54*(300.0+300.0));
assert_eq!(pix_1_map, 2);
}
} | tod_final.push(tmp); | random_line_split |
bindings.rs | //! Setting up and responding to user defined key/mouse bindings
use crate::{
core::{State, Xid},
pure::geometry::Point,
x::XConn,
Error, Result,
};
#[cfg(feature = "keysyms")]
use penrose_keysyms::XKeySym;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, convert::TryFrom, fmt, process::Command};
use strum::{EnumIter, IntoEnumIterator};
use tracing::trace;
/// Run the xmodmap command to dump the system keymap table.
///
/// This is done in a form that we can load in and convert back to key
/// codes. This lets the user define key bindings in the way that they
/// would expect while also ensuring that it is east to debug any odd
/// issues with bindings by referring the user to the xmodmap output.
///
/// # Panics
/// This function will panic if it is unable to fetch keycodes using the xmodmap
/// binary on your system or if the output of `xmodmap -pke` is not valid
pub fn keycodes_from_xmodmap() -> Result<HashMap<String, u8>> {
let output = Command::new("xmodmap").arg("-pke").output()?;
let m = String::from_utf8(output.stdout)?
.lines()
.flat_map(|l| {
let mut words = l.split_whitespace(); // keycode <code> = <names...>
let key_code: u8 = match words.nth(1) {
Some(word) => match word.parse() {
Ok(val) => val,
Err(e) => panic!("{}", e),
},
None => panic!("unexpected output format from xmodmap -pke"),
};
words.skip(1).map(move |name| (name.into(), key_code))
})
.collect();
Ok(m)
}
fn parse_binding(pattern: &str, known_codes: &HashMap<String, u8>) -> Result<KeyCode> {
let mut parts: Vec<&str> = pattern.split('-').collect();
let name = parts.remove(parts.len() - 1);
match known_codes.get(name) {
Some(code) => {
let mask = parts
.iter()
.map(|&s| ModifierKey::try_from(s))
.try_fold(0, |acc, v| v.map(|inner| acc | u16::from(inner)))?;
trace!(?pattern, mask, code, "parsed keybinding");
Ok(KeyCode { mask, code: *code })
}
None => Err(Error::UnknownKeyName {
name: name.to_owned(),
}),
}
}
/// Parse string format key bindings into [KeyCode] based [KeyBindings] using
/// the command line `xmodmap` utility.
///
/// See [keycodes_from_xmodmap] for details of how `xmodmap` is used.
pub fn parse_keybindings_with_xmodmap<S, X>(
str_bindings: HashMap<S, Box<dyn KeyEventHandler<X>>>,
) -> Result<KeyBindings<X>>
where
S: AsRef<str>,
X: XConn,
{
let m = keycodes_from_xmodmap()?;
str_bindings
.into_iter()
.map(|(s, v)| parse_binding(s.as_ref(), &m).map(|k| (k, v)))
.collect()
}
/// Some action to be run by a user key binding
pub trait KeyEventHandler<X>
where
X: XConn,
{
/// Call this handler with the current window manager state
fn call(&mut self, state: &mut State<X>, x: &X) -> Result<()>;
}
impl<X: XConn> fmt::Debug for Box<dyn KeyEventHandler<X>> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyEventHandler").finish()
}
}
impl<F, X> KeyEventHandler<X> for F
where
F: FnMut(&mut State<X>, &X) -> Result<()>,
X: XConn,
{
fn call(&mut self, state: &mut State<X>, x: &X) -> Result<()> {
(self)(state, x)
}
}
/// User defined key bindings
pub type KeyBindings<X> = HashMap<KeyCode, Box<dyn KeyEventHandler<X>>>;
/// An action to be run in response to a mouse event
pub trait MouseEventHandler<X>
where
X: XConn,
{
/// Call this handler with the current window manager state and mouse state
fn call(&mut self, evt: &MouseEvent, state: &mut State<X>, x: &X) -> Result<()>;
}
impl<X: XConn> fmt::Debug for Box<dyn MouseEventHandler<X>> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyEventHandler").finish()
}
}
impl<F, X> MouseEventHandler<X> for F
where
F: FnMut(&MouseEvent, &mut State<X>, &X) -> Result<()>,
X: XConn,
{
fn call(&mut self, evt: &MouseEvent, state: &mut State<X>, x: &X) -> Result<()> {
(self)(evt, state, x)
}
}
/// User defined mouse bindings
pub type MouseBindings<X> = HashMap<(MouseEventKind, MouseState), Box<dyn MouseEventHandler<X>>>;
/// Abstraction layer for working with key presses
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyPress {
/// A raw character key
Utf8(String),
/// Return / enter key
Return,
/// Escape
Escape,
/// Tab
Tab,
/// Backspace
Backspace,
/// Delete
Delete,
/// PageUp
PageUp,
/// PageDown
PageDown,
/// Up
Up,
/// Down
Down,
/// Left
Left,
/// Right
Right,
}
#[cfg(feature = "keysyms")]
impl TryFrom<XKeySym> for KeyPress {
type Error = std::string::FromUtf8Error;
fn try_from(s: XKeySym) -> std::result::Result<KeyPress, Self::Error> {
Ok(match s {
XKeySym::XK_Return | XKeySym::XK_KP_Enter | XKeySym::XK_ISO_Enter => KeyPress::Return,
XKeySym::XK_Escape => KeyPress::Escape,
XKeySym::XK_Tab | XKeySym::XK_ISO_Left_Tab | XKeySym::XK_KP_Tab => KeyPress::Tab,
XKeySym::XK_BackSpace => KeyPress::Backspace,
XKeySym::XK_Delete | XKeySym::XK_KP_Delete => KeyPress::Delete,
XKeySym::XK_Page_Up | XKeySym::XK_KP_Page_Up => KeyPress::PageUp,
XKeySym::XK_Page_Down | XKeySym::XK_KP_Page_Down => KeyPress::PageDown,
XKeySym::XK_Up | XKeySym::XK_KP_Up => KeyPress::Up,
XKeySym::XK_Down | XKeySym::XK_KP_Down => KeyPress::Down,
XKeySym::XK_Left | XKeySym::XK_KP_Left => KeyPress::Left,
XKeySym::XK_Right | XKeySym::XK_KP_Right => KeyPress::Right,
s => KeyPress::Utf8(s.as_utf8_string()?),
})
}
}
/// A u16 X key-code bitmask
pub type KeyCodeMask = u16;
/// A u8 X key-code enum value
pub type KeyCodeValue = u8;
/// A key press and held modifiers
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct KeyCode {
/// The held modifier mask
pub mask: KeyCodeMask,
/// The key code that was held
pub code: KeyCodeValue,
}
impl KeyCode {
/// Create a new [KeyCode] from this one that removes the given mask
pub fn ignoring_modifier(&self, mask: KeyCodeMask) -> KeyCode {
KeyCode {
mask: self.mask &!mask,
code: self.code,
}
}
}
/// Known mouse buttons for binding actions
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum MouseButton {
/// 1
Left,
/// 2
Middle,
/// 3
Right,
/// 4
ScrollUp,
/// 5
ScrollDown,
}
impl From<MouseButton> for u8 {
fn from(b: MouseButton) -> u8 {
match b {
MouseButton::Left => 1,
MouseButton::Middle => 2,
MouseButton::Right => 3,
MouseButton::ScrollUp => 4,
MouseButton::ScrollDown => 5,
}
}
}
impl TryFrom<u8> for MouseButton {
type Error = Error;
fn try_from(n: u8) -> Result<Self> {
match n {
1 => Ok(Self::Left),
2 => Ok(Self::Middle),
3 => Ok(Self::Right),
4 => Ok(Self::ScrollUp),
5 => Ok(Self::ScrollDown),
_ => Err(Error::UnknownMouseButton { button: n }),
}
}
}
/// Known modifier keys for bindings
#[derive(Debug, EnumIter, PartialEq, Eq, Hash, Clone, Copy, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ModifierKey {
/// Control
Ctrl,
/// Alt
Alt,
/// Shift
Shift,
/// Meta / super / windows
Meta,
}
impl ModifierKey {
fn was_held(&self, mask: u16) -> bool {
mask & u16::from(*self) > 0
}
}
impl From<ModifierKey> for u16 {
fn from(m: ModifierKey) -> u16 {
(match m {
ModifierKey::Shift => 1 << 0,
ModifierKey::Ctrl => 1 << 2,
ModifierKey::Alt => 1 << 3,
ModifierKey::Meta => 1 << 6,
}) as u16
}
}
impl TryFrom<&str> for ModifierKey {
type Error = Error;
fn try_from(s: &str) -> std::result::Result<Self, Self::Error> {
match s {
"C" => Ok(Self::Ctrl),
"A" => Ok(Self::Alt),
"S" => Ok(Self::Shift),
"M" => Ok(Self::Meta),
_ => Err(Error::UnknownModifier { name: s.to_owned() }),
}
}
}
/// A mouse state specification indicating the button and modifiers held
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MouseState {
/// The [MouseButton] being held
pub button: MouseButton,
/// All [ModifierKey]s being held
pub modifiers: Vec<ModifierKey>,
}
impl MouseState {
/// Construct a new MouseState
pub fn new(button: MouseButton, mut modifiers: Vec<ModifierKey>) -> Self {
modifiers.sort();
Self { button, modifiers }
}
/// Parse raw mouse state values into a [MouseState]
pub fn from_detail_and_state(detail: u8, state: u16) -> Result<Self> {
Ok(Self {
button: MouseButton::try_from(detail)?,
modifiers: ModifierKey::iter().filter(|m| m.was_held(state)).collect(),
})
}
/// The xcb bitmask for this [MouseState]
pub fn mask(&self) -> u16 {
self.modifiers
.iter()
.fold(0, |acc, &val| acc | u16::from(val))
}
/// The xcb button ID for this [MouseState]
pub fn button(&self) -> u8 |
}
/// The types of mouse events represented by a MouseEvent
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum MouseEventKind {
/// A button was pressed
Press,
/// A button was released
Release,
/// The mouse was moved while a button was held
Motion,
}
/// A mouse movement or button event
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MouseEvent {
/// The ID of the window that was contained the click
pub id: Xid,
/// Absolute coordinate of the event
pub rpt: Point,
/// Coordinate of the event relative to top-left of the window itself
pub wpt: Point,
/// The modifier and button code that was received
pub state: MouseState,
/// Was this press, release or motion?
pub kind: MouseEventKind,
}
impl MouseEvent {
/// Construct a new [MouseEvent] from raw data
pub fn new(
id: Xid,
rx: i16,
ry: i16,
ex: i16,
ey: i16,
state: MouseState,
kind: MouseEventKind,
) -> Self {
MouseEvent {
id,
rpt: Point::new(rx as u32, ry as u32),
wpt: Point::new(ex as u32, ey as u32),
state,
kind,
}
}
}
| {
self.button.into()
} | identifier_body |
bindings.rs | //! Setting up and responding to user defined key/mouse bindings
use crate::{
core::{State, Xid},
pure::geometry::Point,
x::XConn,
Error, Result,
};
#[cfg(feature = "keysyms")]
use penrose_keysyms::XKeySym;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, convert::TryFrom, fmt, process::Command};
use strum::{EnumIter, IntoEnumIterator};
use tracing::trace;
/// Run the xmodmap command to dump the system keymap table.
///
/// This is done in a form that we can load in and convert back to key
/// codes. This lets the user define key bindings in the way that they
/// would expect while also ensuring that it is east to debug any odd
/// issues with bindings by referring the user to the xmodmap output.
///
/// # Panics
/// This function will panic if it is unable to fetch keycodes using the xmodmap
/// binary on your system or if the output of `xmodmap -pke` is not valid
pub fn keycodes_from_xmodmap() -> Result<HashMap<String, u8>> {
let output = Command::new("xmodmap").arg("-pke").output()?;
let m = String::from_utf8(output.stdout)?
.lines()
.flat_map(|l| {
let mut words = l.split_whitespace(); // keycode <code> = <names...>
let key_code: u8 = match words.nth(1) {
Some(word) => match word.parse() {
Ok(val) => val,
Err(e) => panic!("{}", e),
},
None => panic!("unexpected output format from xmodmap -pke"),
};
words.skip(1).map(move |name| (name.into(), key_code))
})
.collect();
Ok(m)
}
fn parse_binding(pattern: &str, known_codes: &HashMap<String, u8>) -> Result<KeyCode> {
let mut parts: Vec<&str> = pattern.split('-').collect();
let name = parts.remove(parts.len() - 1);
match known_codes.get(name) {
Some(code) => {
let mask = parts
.iter()
.map(|&s| ModifierKey::try_from(s))
.try_fold(0, |acc, v| v.map(|inner| acc | u16::from(inner)))?;
trace!(?pattern, mask, code, "parsed keybinding");
Ok(KeyCode { mask, code: *code })
}
None => Err(Error::UnknownKeyName {
name: name.to_owned(),
}),
}
}
/// Parse string format key bindings into [KeyCode] based [KeyBindings] using
/// the command line `xmodmap` utility.
///
/// See [keycodes_from_xmodmap] for details of how `xmodmap` is used.
pub fn parse_keybindings_with_xmodmap<S, X>(
str_bindings: HashMap<S, Box<dyn KeyEventHandler<X>>>,
) -> Result<KeyBindings<X>>
where
S: AsRef<str>,
X: XConn,
{
let m = keycodes_from_xmodmap()?;
str_bindings
.into_iter()
.map(|(s, v)| parse_binding(s.as_ref(), &m).map(|k| (k, v)))
.collect()
}
/// Some action to be run by a user key binding
pub trait KeyEventHandler<X>
where
X: XConn,
{
/// Call this handler with the current window manager state
fn call(&mut self, state: &mut State<X>, x: &X) -> Result<()>;
}
impl<X: XConn> fmt::Debug for Box<dyn KeyEventHandler<X>> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyEventHandler").finish()
}
}
impl<F, X> KeyEventHandler<X> for F
where
F: FnMut(&mut State<X>, &X) -> Result<()>,
X: XConn,
{
fn call(&mut self, state: &mut State<X>, x: &X) -> Result<()> {
(self)(state, x)
}
}
/// User defined key bindings
pub type KeyBindings<X> = HashMap<KeyCode, Box<dyn KeyEventHandler<X>>>;
/// An action to be run in response to a mouse event
pub trait MouseEventHandler<X>
where
X: XConn,
{
/// Call this handler with the current window manager state and mouse state
fn call(&mut self, evt: &MouseEvent, state: &mut State<X>, x: &X) -> Result<()>;
}
impl<X: XConn> fmt::Debug for Box<dyn MouseEventHandler<X>> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyEventHandler").finish()
}
}
impl<F, X> MouseEventHandler<X> for F
where
F: FnMut(&MouseEvent, &mut State<X>, &X) -> Result<()>,
X: XConn,
{
fn call(&mut self, evt: &MouseEvent, state: &mut State<X>, x: &X) -> Result<()> {
(self)(evt, state, x)
}
}
/// User defined mouse bindings
pub type MouseBindings<X> = HashMap<(MouseEventKind, MouseState), Box<dyn MouseEventHandler<X>>>;
/// Abstraction layer for working with key presses
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyPress {
/// A raw character key
Utf8(String),
/// Return / enter key
Return,
/// Escape
Escape,
/// Tab
Tab,
/// Backspace
Backspace,
/// Delete
Delete,
/// PageUp
PageUp,
/// PageDown
PageDown,
/// Up
Up,
/// Down
Down,
/// Left
Left,
/// Right
Right,
}
#[cfg(feature = "keysyms")]
impl TryFrom<XKeySym> for KeyPress {
type Error = std::string::FromUtf8Error;
fn try_from(s: XKeySym) -> std::result::Result<KeyPress, Self::Error> {
Ok(match s {
XKeySym::XK_Return | XKeySym::XK_KP_Enter | XKeySym::XK_ISO_Enter => KeyPress::Return,
XKeySym::XK_Escape => KeyPress::Escape,
XKeySym::XK_Tab | XKeySym::XK_ISO_Left_Tab | XKeySym::XK_KP_Tab => KeyPress::Tab,
XKeySym::XK_BackSpace => KeyPress::Backspace,
XKeySym::XK_Delete | XKeySym::XK_KP_Delete => KeyPress::Delete,
XKeySym::XK_Page_Up | XKeySym::XK_KP_Page_Up => KeyPress::PageUp,
XKeySym::XK_Page_Down | XKeySym::XK_KP_Page_Down => KeyPress::PageDown,
XKeySym::XK_Up | XKeySym::XK_KP_Up => KeyPress::Up,
XKeySym::XK_Down | XKeySym::XK_KP_Down => KeyPress::Down,
XKeySym::XK_Left | XKeySym::XK_KP_Left => KeyPress::Left,
XKeySym::XK_Right | XKeySym::XK_KP_Right => KeyPress::Right,
s => KeyPress::Utf8(s.as_utf8_string()?),
})
}
}
/// A u16 X key-code bitmask
pub type KeyCodeMask = u16;
/// A u8 X key-code enum value
pub type KeyCodeValue = u8;
/// A key press and held modifiers
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct KeyCode {
/// The held modifier mask
pub mask: KeyCodeMask,
/// The key code that was held
pub code: KeyCodeValue,
}
impl KeyCode {
/// Create a new [KeyCode] from this one that removes the given mask
pub fn ignoring_modifier(&self, mask: KeyCodeMask) -> KeyCode {
KeyCode {
mask: self.mask &!mask,
code: self.code,
}
}
}
/// Known mouse buttons for binding actions
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum MouseButton {
/// 1
Left,
/// 2
Middle,
/// 3
Right,
/// 4
ScrollUp,
/// 5
ScrollDown,
}
impl From<MouseButton> for u8 {
fn from(b: MouseButton) -> u8 {
match b {
MouseButton::Left => 1,
MouseButton::Middle => 2,
MouseButton::Right => 3,
MouseButton::ScrollUp => 4,
MouseButton::ScrollDown => 5,
}
}
}
impl TryFrom<u8> for MouseButton {
type Error = Error;
fn try_from(n: u8) -> Result<Self> {
match n {
1 => Ok(Self::Left),
2 => Ok(Self::Middle),
3 => Ok(Self::Right),
4 => Ok(Self::ScrollUp),
5 => Ok(Self::ScrollDown),
_ => Err(Error::UnknownMouseButton { button: n }),
}
}
}
/// Known modifier keys for bindings
#[derive(Debug, EnumIter, PartialEq, Eq, Hash, Clone, Copy, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ModifierKey {
/// Control
Ctrl,
/// Alt
Alt,
/// Shift
Shift,
/// Meta / super / windows
Meta,
}
impl ModifierKey {
fn was_held(&self, mask: u16) -> bool {
mask & u16::from(*self) > 0
}
}
impl From<ModifierKey> for u16 {
fn from(m: ModifierKey) -> u16 {
(match m {
ModifierKey::Shift => 1 << 0,
ModifierKey::Ctrl => 1 << 2,
ModifierKey::Alt => 1 << 3,
ModifierKey::Meta => 1 << 6,
}) as u16
}
}
impl TryFrom<&str> for ModifierKey {
type Error = Error;
fn try_from(s: &str) -> std::result::Result<Self, Self::Error> {
match s {
"C" => Ok(Self::Ctrl),
"A" => Ok(Self::Alt),
"S" => Ok(Self::Shift),
"M" => Ok(Self::Meta),
_ => Err(Error::UnknownModifier { name: s.to_owned() }),
}
}
}
/// A mouse state specification indicating the button and modifiers held
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MouseState {
/// The [MouseButton] being held
pub button: MouseButton,
/// All [ModifierKey]s being held
pub modifiers: Vec<ModifierKey>,
}
impl MouseState {
/// Construct a new MouseState
pub fn new(button: MouseButton, mut modifiers: Vec<ModifierKey>) -> Self {
modifiers.sort();
Self { button, modifiers }
}
/// Parse raw mouse state values into a [MouseState]
pub fn from_detail_and_state(detail: u8, state: u16) -> Result<Self> {
Ok(Self {
button: MouseButton::try_from(detail)?,
modifiers: ModifierKey::iter().filter(|m| m.was_held(state)).collect(),
})
}
/// The xcb bitmask for this [MouseState]
pub fn mask(&self) -> u16 {
self.modifiers
.iter()
.fold(0, |acc, &val| acc | u16::from(val))
}
/// The xcb button ID for this [MouseState]
pub fn button(&self) -> u8 { | self.button.into()
}
}
/// The types of mouse events represented by a MouseEvent
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum MouseEventKind {
/// A button was pressed
Press,
/// A button was released
Release,
/// The mouse was moved while a button was held
Motion,
}
/// A mouse movement or button event
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MouseEvent {
/// The ID of the window that was contained the click
pub id: Xid,
/// Absolute coordinate of the event
pub rpt: Point,
/// Coordinate of the event relative to top-left of the window itself
pub wpt: Point,
/// The modifier and button code that was received
pub state: MouseState,
/// Was this press, release or motion?
pub kind: MouseEventKind,
}
impl MouseEvent {
/// Construct a new [MouseEvent] from raw data
pub fn new(
id: Xid,
rx: i16,
ry: i16,
ex: i16,
ey: i16,
state: MouseState,
kind: MouseEventKind,
) -> Self {
MouseEvent {
id,
rpt: Point::new(rx as u32, ry as u32),
wpt: Point::new(ex as u32, ey as u32),
state,
kind,
}
}
} | random_line_split |
|
bindings.rs | //! Setting up and responding to user defined key/mouse bindings
use crate::{
core::{State, Xid},
pure::geometry::Point,
x::XConn,
Error, Result,
};
#[cfg(feature = "keysyms")]
use penrose_keysyms::XKeySym;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, convert::TryFrom, fmt, process::Command};
use strum::{EnumIter, IntoEnumIterator};
use tracing::trace;
/// Run the xmodmap command to dump the system keymap table.
///
/// This is done in a form that we can load in and convert back to key
/// codes. This lets the user define key bindings in the way that they
/// would expect while also ensuring that it is east to debug any odd
/// issues with bindings by referring the user to the xmodmap output.
///
/// # Panics
/// This function will panic if it is unable to fetch keycodes using the xmodmap
/// binary on your system or if the output of `xmodmap -pke` is not valid
pub fn keycodes_from_xmodmap() -> Result<HashMap<String, u8>> {
let output = Command::new("xmodmap").arg("-pke").output()?;
let m = String::from_utf8(output.stdout)?
.lines()
.flat_map(|l| {
let mut words = l.split_whitespace(); // keycode <code> = <names...>
let key_code: u8 = match words.nth(1) {
Some(word) => match word.parse() {
Ok(val) => val,
Err(e) => panic!("{}", e),
},
None => panic!("unexpected output format from xmodmap -pke"),
};
words.skip(1).map(move |name| (name.into(), key_code))
})
.collect();
Ok(m)
}
fn parse_binding(pattern: &str, known_codes: &HashMap<String, u8>) -> Result<KeyCode> {
let mut parts: Vec<&str> = pattern.split('-').collect();
let name = parts.remove(parts.len() - 1);
match known_codes.get(name) {
Some(code) => {
let mask = parts
.iter()
.map(|&s| ModifierKey::try_from(s))
.try_fold(0, |acc, v| v.map(|inner| acc | u16::from(inner)))?;
trace!(?pattern, mask, code, "parsed keybinding");
Ok(KeyCode { mask, code: *code })
}
None => Err(Error::UnknownKeyName {
name: name.to_owned(),
}),
}
}
/// Parse string format key bindings into [KeyCode] based [KeyBindings] using
/// the command line `xmodmap` utility.
///
/// See [keycodes_from_xmodmap] for details of how `xmodmap` is used.
pub fn parse_keybindings_with_xmodmap<S, X>(
str_bindings: HashMap<S, Box<dyn KeyEventHandler<X>>>,
) -> Result<KeyBindings<X>>
where
S: AsRef<str>,
X: XConn,
{
let m = keycodes_from_xmodmap()?;
str_bindings
.into_iter()
.map(|(s, v)| parse_binding(s.as_ref(), &m).map(|k| (k, v)))
.collect()
}
/// Some action to be run by a user key binding
pub trait KeyEventHandler<X>
where
X: XConn,
{
/// Call this handler with the current window manager state
fn call(&mut self, state: &mut State<X>, x: &X) -> Result<()>;
}
impl<X: XConn> fmt::Debug for Box<dyn KeyEventHandler<X>> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyEventHandler").finish()
}
}
impl<F, X> KeyEventHandler<X> for F
where
F: FnMut(&mut State<X>, &X) -> Result<()>,
X: XConn,
{
fn call(&mut self, state: &mut State<X>, x: &X) -> Result<()> {
(self)(state, x)
}
}
/// User defined key bindings
pub type KeyBindings<X> = HashMap<KeyCode, Box<dyn KeyEventHandler<X>>>;
/// An action to be run in response to a mouse event
pub trait MouseEventHandler<X>
where
X: XConn,
{
/// Call this handler with the current window manager state and mouse state
fn call(&mut self, evt: &MouseEvent, state: &mut State<X>, x: &X) -> Result<()>;
}
impl<X: XConn> fmt::Debug for Box<dyn MouseEventHandler<X>> {
fn | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyEventHandler").finish()
}
}
impl<F, X> MouseEventHandler<X> for F
where
F: FnMut(&MouseEvent, &mut State<X>, &X) -> Result<()>,
X: XConn,
{
fn call(&mut self, evt: &MouseEvent, state: &mut State<X>, x: &X) -> Result<()> {
(self)(evt, state, x)
}
}
/// User defined mouse bindings
pub type MouseBindings<X> = HashMap<(MouseEventKind, MouseState), Box<dyn MouseEventHandler<X>>>;
/// Abstraction layer for working with key presses
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyPress {
/// A raw character key
Utf8(String),
/// Return / enter key
Return,
/// Escape
Escape,
/// Tab
Tab,
/// Backspace
Backspace,
/// Delete
Delete,
/// PageUp
PageUp,
/// PageDown
PageDown,
/// Up
Up,
/// Down
Down,
/// Left
Left,
/// Right
Right,
}
#[cfg(feature = "keysyms")]
impl TryFrom<XKeySym> for KeyPress {
type Error = std::string::FromUtf8Error;
fn try_from(s: XKeySym) -> std::result::Result<KeyPress, Self::Error> {
Ok(match s {
XKeySym::XK_Return | XKeySym::XK_KP_Enter | XKeySym::XK_ISO_Enter => KeyPress::Return,
XKeySym::XK_Escape => KeyPress::Escape,
XKeySym::XK_Tab | XKeySym::XK_ISO_Left_Tab | XKeySym::XK_KP_Tab => KeyPress::Tab,
XKeySym::XK_BackSpace => KeyPress::Backspace,
XKeySym::XK_Delete | XKeySym::XK_KP_Delete => KeyPress::Delete,
XKeySym::XK_Page_Up | XKeySym::XK_KP_Page_Up => KeyPress::PageUp,
XKeySym::XK_Page_Down | XKeySym::XK_KP_Page_Down => KeyPress::PageDown,
XKeySym::XK_Up | XKeySym::XK_KP_Up => KeyPress::Up,
XKeySym::XK_Down | XKeySym::XK_KP_Down => KeyPress::Down,
XKeySym::XK_Left | XKeySym::XK_KP_Left => KeyPress::Left,
XKeySym::XK_Right | XKeySym::XK_KP_Right => KeyPress::Right,
s => KeyPress::Utf8(s.as_utf8_string()?),
})
}
}
/// A u16 X key-code bitmask
pub type KeyCodeMask = u16;
/// A u8 X key-code enum value
pub type KeyCodeValue = u8;
/// A key press and held modifiers
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct KeyCode {
/// The held modifier mask
pub mask: KeyCodeMask,
/// The key code that was held
pub code: KeyCodeValue,
}
impl KeyCode {
/// Create a new [KeyCode] from this one that removes the given mask
pub fn ignoring_modifier(&self, mask: KeyCodeMask) -> KeyCode {
KeyCode {
mask: self.mask &!mask,
code: self.code,
}
}
}
/// Known mouse buttons for binding actions
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum MouseButton {
/// 1
Left,
/// 2
Middle,
/// 3
Right,
/// 4
ScrollUp,
/// 5
ScrollDown,
}
impl From<MouseButton> for u8 {
fn from(b: MouseButton) -> u8 {
match b {
MouseButton::Left => 1,
MouseButton::Middle => 2,
MouseButton::Right => 3,
MouseButton::ScrollUp => 4,
MouseButton::ScrollDown => 5,
}
}
}
impl TryFrom<u8> for MouseButton {
type Error = Error;
fn try_from(n: u8) -> Result<Self> {
match n {
1 => Ok(Self::Left),
2 => Ok(Self::Middle),
3 => Ok(Self::Right),
4 => Ok(Self::ScrollUp),
5 => Ok(Self::ScrollDown),
_ => Err(Error::UnknownMouseButton { button: n }),
}
}
}
/// Known modifier keys for bindings
#[derive(Debug, EnumIter, PartialEq, Eq, Hash, Clone, Copy, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ModifierKey {
/// Control
Ctrl,
/// Alt
Alt,
/// Shift
Shift,
/// Meta / super / windows
Meta,
}
impl ModifierKey {
fn was_held(&self, mask: u16) -> bool {
mask & u16::from(*self) > 0
}
}
impl From<ModifierKey> for u16 {
fn from(m: ModifierKey) -> u16 {
(match m {
ModifierKey::Shift => 1 << 0,
ModifierKey::Ctrl => 1 << 2,
ModifierKey::Alt => 1 << 3,
ModifierKey::Meta => 1 << 6,
}) as u16
}
}
impl TryFrom<&str> for ModifierKey {
type Error = Error;
fn try_from(s: &str) -> std::result::Result<Self, Self::Error> {
match s {
"C" => Ok(Self::Ctrl),
"A" => Ok(Self::Alt),
"S" => Ok(Self::Shift),
"M" => Ok(Self::Meta),
_ => Err(Error::UnknownModifier { name: s.to_owned() }),
}
}
}
/// A mouse state specification indicating the button and modifiers held
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MouseState {
/// The [MouseButton] being held
pub button: MouseButton,
/// All [ModifierKey]s being held
pub modifiers: Vec<ModifierKey>,
}
impl MouseState {
/// Construct a new MouseState
pub fn new(button: MouseButton, mut modifiers: Vec<ModifierKey>) -> Self {
modifiers.sort();
Self { button, modifiers }
}
/// Parse raw mouse state values into a [MouseState]
pub fn from_detail_and_state(detail: u8, state: u16) -> Result<Self> {
Ok(Self {
button: MouseButton::try_from(detail)?,
modifiers: ModifierKey::iter().filter(|m| m.was_held(state)).collect(),
})
}
/// The xcb bitmask for this [MouseState]
pub fn mask(&self) -> u16 {
self.modifiers
.iter()
.fold(0, |acc, &val| acc | u16::from(val))
}
/// The xcb button ID for this [MouseState]
pub fn button(&self) -> u8 {
self.button.into()
}
}
/// The types of mouse events represented by a MouseEvent
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum MouseEventKind {
/// A button was pressed
Press,
/// A button was released
Release,
/// The mouse was moved while a button was held
Motion,
}
/// A mouse movement or button event
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MouseEvent {
/// The ID of the window that was contained the click
pub id: Xid,
/// Absolute coordinate of the event
pub rpt: Point,
/// Coordinate of the event relative to top-left of the window itself
pub wpt: Point,
/// The modifier and button code that was received
pub state: MouseState,
/// Was this press, release or motion?
pub kind: MouseEventKind,
}
impl MouseEvent {
/// Construct a new [MouseEvent] from raw data
pub fn new(
id: Xid,
rx: i16,
ry: i16,
ex: i16,
ey: i16,
state: MouseState,
kind: MouseEventKind,
) -> Self {
MouseEvent {
id,
rpt: Point::new(rx as u32, ry as u32),
wpt: Point::new(ex as u32, ey as u32),
state,
kind,
}
}
}
| fmt | identifier_name |
pack.rs | .map(|s| PackId::Pack(s.to_owned()))
}
fn is_valid(s: &str) -> bool {
s.chars()
.all(|c| c.is_ascii_alphanumeric() || EXTRA_ID_CHARS.contains(&c))
}
}
impl FromStr for PackId {
type Err = IdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if!PackId::is_valid(s) {
return Err(IdError::InvalidPack(s.to_owned()));
}
Ok(PackId::Pack(s.to_owned()))
}
}
impl Display for PackId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
PackId::Pack(s) => write!(f, "{}", s),
}
}
}
/// Identifies a snapshot using a pack base filename [`Path::file_stem`] and a snapshot tag.
#[derive(PartialEq, Clone, Debug)]
pub struct SnapshotId {
pack: PackId,
tag: String,
}
impl SnapshotId {
/// Creates a [`SnapshotId`] from a pack and a snapshot tag
pub fn new(pack: PackId, tag: &str) -> Result<Self, IdError> {
if!Self::is_valid(tag) {
return Err(IdError::InvalidSnapshot(tag.to_owned()));
}
Ok(Self {
pack,
tag: tag.to_owned(),
})
}
pub fn pack(&self) -> &PackId {
&self.pack
}
pub fn tag(&self) -> &str {
&self.tag
}
fn is_valid(tag: &str) -> bool {
tag.chars()
.all(|c| c.is_ascii_alphanumeric() || EXTRA_ID_CHARS.contains(&c))
}
}
/// [`SnapshotId`] equality is a full equivalence relation.
impl Eq for SnapshotId {}
/// Prints the canonical form for [`SnapshotId`].
impl Display for SnapshotId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{}:{}", self.pack, self.tag)
}
}
/// Parses a [`SnapshotId`] from a canonical form string 'pack_name:snapshot_name'.
impl FromStr for SnapshotId {
type Err = IdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some((pack, snapshot)) = s.trim_end().rsplit_once(':') {
if pack.is_empty() {
return Err(IdError::InvalidPack(pack.to_owned()));
}
if snapshot.is_empty() {
return Err(IdError::InvalidSnapshot(snapshot.to_owned()));
}
Ok(SnapshotId {
pack: PackId::from_str(pack)?,
tag: snapshot.to_owned(),
})
} else {
Err(IdError::BadFormat(s.to_owned()))
}
}
}
/// A magic constant that has no use other than to indicate a custom.pack header
/// stored in a Zstandard skippable frame.
const SKIPPABLE_MAGIC_MASK: u32 = 0x184D2A50;
/// Reads a Zstandard skippable frame from reader and writes the result to `buf`.
/// Returns the size of the frame, *not* the number of bytes read.
pub fn read_skippable_frame(mut reader: impl Read, buf: &mut Vec<u8>) -> io::Result<u64> {
fn read_u32_le(mut reader: impl Read) -> io::Result<u32> {
let mut bytes = [0u8; 4];
reader.read_exact(&mut bytes)?;
Ok(u32::from_le_bytes(bytes))
}
// Ensure this is a skippable frame.
let magic = read_u32_le(&mut reader)?;
if magic & SKIPPABLE_MAGIC_MASK!= SKIPPABLE_MAGIC_MASK {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Not a Zstandard skippable frame!",
));
}
let frame_size = read_u32_le(&mut reader)?;
buf.resize(frame_size as usize, 0);
reader.read_exact(buf)?;
// Compute overall frame size.
Ok((std::mem::size_of::<u32>() * 2 + buf.len()) as u64)
}
/// Writes a Zstandard skippable frame with the given user data.
/// Returns the number of bytes written to writer (the size of the frame, including the magic number and header).
pub fn write_skippable_frame(mut writer: impl Write, buf: &[u8]) -> io::Result<u64> {
fn write_u32_le(mut writer: impl Write, value: u32) -> io::Result<()> {
writer.write_all(&value.to_le_bytes())
}
// Ensure this is a skippable frame.
write_u32_le(&mut writer, SKIPPABLE_MAGIC_MASK)?;
write_u32_le(&mut writer, buf.len() as u32)?;
writer.write_all(buf)?;
// Compute overall frame size.
Ok((std::mem::size_of::<u32>() * 2 + buf.len()) as u64)
}
/// The unidirectional stream of data stored in the pack.
enum PackReader {
Compressed(Decoder<'static, BufReader<File>>),
}
impl PackReader {
/// Consumes the specified number of bytes from the reader.
fn seek(&mut self, bytes: u64) -> io::Result<()> {
match self {
Self::Compressed(decoder) => {
io::copy(&mut decoder.by_ref().take(bytes), &mut io::sink()).map(|_| {})
}
}
}
// Reads the exact number of bytes into `buf`.
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
match self {
Self::Compressed(decoder) => decoder.read_exact(buf),
}
}
}
/// Represents a compressed Zstandard frame in the.pack file.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PackFrame {
/// The size of the frame, in bytes.
pub frame_size: u64,
/// The size of the data stream in the frame, once decompressed, in bytes.
pub decompressed_size: u64,
}
/// Represents the custom header in the beginning of a.pack file.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PackHeader {
/// Valid pack headers have this value set to [`PACK_HEADER_MAGIC`].
magic: u64,
/// The list of frames in the pack file, sorted by their byte offsets.
frames: Vec<PackFrame>,
}
impl PackHeader {
/// Create a new pack header.
pub fn new(frames: Vec<PackFrame>) -> Self {
Self {
magic: PACK_HEADER_MAGIC,
frames,
}
}
/// Verifies the header magic.
pub fn is_valid(&self) -> bool {
self.magic == PACK_HEADER_MAGIC
}
}
impl Default for PackHeader {
fn default() -> Self {
Self {
magic: PACK_HEADER_MAGIC,
frames: vec![],
}
}
}
/// Represents an pack file.
pub struct Pack {
/// The base filename ([`Path::file_stem`]) of the pack.
name: String,
/// The index for the pack.
index: PackIndex,
/// The header of the pack.
header: PackHeader,
/// PackReader instances for each frame in the.pack file.
frame_readers: Vec<PackReader>,
/// The file size of the pack (in bytes).
file_size: u64,
}
impl Pack {
/// Opens a pack file and its corresponding index.
///
/// # Arguments
///
/// * `pack_name` - The base filename ([`Path::file_stem`]) of the pack.
pub fn open<P>(repo: P, pack_name: &PackId) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let PackId::Pack(pack_name) = pack_name;
let mut packs_data = repo.as_ref().join(&*Repository::data_dir());
packs_data.push(PACKS_DIR);
let mut pack_index_path = packs_data.join(pack_name);
pack_index_path.set_extension(PACK_INDEX_EXTENSION);
let mut pack_path = packs_data.join(pack_name);
pack_path.set_extension(PACK_EXTENSION);
info!("Reading pack index {:?}...", pack_index_path);
let pack_index = PackIndex::load(&pack_index_path)?;
info!("Opening pack file {:?}...", pack_path);
let (file_size, header, frame_readers) =
Self::open_pack(&pack_path).or_else(|_| Self::open_pack_legacy(&pack_path))?;
Ok(Pack {
name: pack_name.to_owned(),
index: pack_index,
header,
frame_readers,
file_size,
})
}
/// Opens the pack file for reading.
fn open_pack(pack_path: &Path) -> Result<(u64, PackHeader, Vec<PackReader>), Error> {
let file = File::open(&pack_path)?;
let file_size = file.metadata()?.len();
let mut reader = io::BufReader::new(file);
let mut header = vec![];
let header_size = read_skippable_frame(&mut reader, &mut header)?;
let header: PackHeader =
rmp_serde::decode::from_read(&header[..]).map_err(|_| Error::CorruptPack)?;
drop(reader);
if!header.is_valid() {
return Err(Error::CorruptPack);
}
let frame_offsets = compute_frame_offsets(&header.frames);
let frame_readers = frame_offsets
.iter()
.map(|offset| -> Result<_, Error> {
let mut reader = File::open(&pack_path)?;
io::Seek::seek(&mut reader, io::SeekFrom::Start(header_size + offset))?;
let mut reader = Decoder::new(reader)?;
reader.set_parameter(DParameter::WindowLogMax(DEFAULT_WINDOW_LOG_MAX))?;
// Wrap in a `PackReader`.
let reader = PackReader::Compressed(reader);
Ok(reader)
})
.collect::<Result<Vec<_>, _>>()?;
Ok((file_size, header, frame_readers))
}
/// Backwards-compatible open_pack for the legacy pack format (no skippable frame/no header).
fn open_pack_legacy(pack_path: &Path) -> Result<(u64, PackHeader, Vec<PackReader>), Error> {
let file = File::open(&pack_path)?;
let file_size = file.metadata()?.len();
// This manufactured pack header works for the current implementation. We might
// change how/whether we support the legacy pack format in the future...
let header = PackHeader::new(vec![PackFrame {
frame_size: file_size,
decompressed_size: u64::MAX,
}]);
let mut reader = Decoder::new(file)?;
reader.set_parameter(DParameter::WindowLogMax(DEFAULT_WINDOW_LOG_MAX))?;
let frame_reader = PackReader::Compressed(reader);
Ok((file_size, header, vec![frame_reader]))
}
/// The base filename ([`Path::file_stem`]) of the pack.
pub fn name(&self) -> &str {
&self.name
}
/// A reference to the pack index.
pub fn index(&self) -> &PackIndex {
&self.index
}
/// The size of the pack in bytes.
pub fn file_size(&self) -> u64 {
self.file_size
}
/// Extracts the specified entries from the pack into the specified directory.
/// This operation consumes the pack, since [`Pack`] objects contain a unidirectional
/// data stream that becomes unusable after it is read.
///
/// # Arguments
///
/// * `entries` - The list of entries to extract. These *must* be entries contained in the pack index.
/// * `output_dir` - The directory relative to which the files will be extracted.
/// * `verify` - Enable/disable checksum verification.
#[allow(unused_mut)]
#[allow(clippy::needless_collect)]
pub(crate) fn extract_entries<P>(
mut self,
entries: &[FileEntry],
output_dir: P,
verify: bool,
num_workers: u32,
) -> Result<(), Error>
where
P: AsRef<Path> + Sync,
{
if entries.is_empty() {
return Ok(());
}
let num_frames = self.header.frames.len();
assert_ne!(0, num_workers);
assert_ne!(0, num_frames);
if num_frames < num_workers as usize {
info!(
"Requested {} workers, but there are only {} frames!",
num_workers, num_frames
);
}
let num_workers = std::cmp::min(num_workers, num_frames as u32);
// Assign entries to the frames they reside in.
// The resulting entries will have offsets relative to their containing frame.
let frame_to_entries = assign_to_frames(&self.header.frames, entries)?;
// Compute and log total amount of seeking and decompression needed.
let bytes_to_decompress = frame_to_entries
.iter()
.flat_map(|entries| {
entries
.iter()
.map(|e| e.metadata.offset + e.metadata.offset)
.max()
})
.sum::<u64>();
info!(
"Decompressing {:.3} MiB of data...",
bytes_to_decompress as f64 / 1024f64 / 1024f64
);
// Collect required for run_in_parallel ExactSizeIterator argument.
let tasks = self
.frame_readers
.into_iter()
.zip(frame_to_entries.into_iter())
// Skip empty frames.
.filter(|(_, entries)|!entries.is_empty())
.collect::<Vec<_>>();
// Record start time
let start_time = std::time::Instant::now();
let results = run_in_parallel(
num_workers as usize,
tasks.into_iter(),
|(frame_reader, entries)| extract_files(frame_reader, &entries, &output_dir, verify),
);
// Collect stats
let stats = results
.into_iter()
.sum::<Result<ExtractStats, Error>>()?
// Convert the statistics into fractions, since summing the time per thread doesn't make much sense.
.fractions();
// Log statistics about the decompression performance
let real_time = std::time::Instant::now() - start_time;
info!(
"Decompression statistics ({:?})\n\
\tSeeking: {:.1}%\n\
\tObject decompression: {:.1}%\n\
\tVerification: {:.1}%\n\
\tWriting to disk: {:.1}%\n\
\tOther: {:.1}%",
real_time,
stats.seek_time * 100f64,
stats.object_time * 100f64,
stats.verify_time * 100f64,
stats.write_time * 100f64,
stats.other_time() * 100f64,
);
Ok(())
}
}
/// Verifies that the object has the expected checksum.
fn verify_object(buf: &[u8], exp_checksum: &ObjectChecksum) -> Result<(), Error> {
// Verify checksum
let mut checksum = [0u8; 20];
let mut hasher = Sha1::new();
hasher.input(buf);
hasher.result(&mut checksum);
if &checksum!= exp_checksum |
Ok(())
}
/// Writes the object to the specified path, taking care
/// of adjusting file permissions.
fn write_object(buf: &[u8], path: &Path) -> Result<(), Error> {
fs::create_dir_all(path.parent().unwrap())?;
let mut f = File::create(path)?;
f.write_all(buf)?;
Ok(())
}
/// Returns a list of the frame offsets, computed
/// using the order and sizes of the given frames.
fn compute_frame_offsets(frames: &[PackFrame]) -> Vec<u64> {
let mut frame_offsets: Vec<_> = vec![0; frames.len()];
for i in 1..frame_offsets.len() {
frame_offsets[i] = frames[i - 1].frame_size + frame_offsets[i - 1];
}
frame_offsets
}
/// Returns a list of the data offsets, computed using the order and
/// decompressed sizes of the given frames.
fn compute_frame_decompressed_offset(frames: &[PackFrame]) -> Vec<u64> {
let mut frame_decompressed_offset: Vec<_> = vec![0; frames.len()];
for i in 1..frame_decompressed_offset.len() {
frame_decompressed_offset[i] =
frames[i - 1].decompressed_size + frame_decompressed_offset[i - 1];
}
frame_decompressed_offset
}
/// Groups and transforms the list of [`FileEntry`]-s taken from a pack index
/// (and with absolute offsets into the decompressed stream) into sets of
/// entries per frame, with adjusted (relative) offsets to that corresponding
/// Zstandard frame. Objects are assumed to not be split across two frames.
fn assign_to_frames(
frames: &[PackFrame],
entries: &[FileEntry],
) -> Result<Vec<Vec<FileEntry>>, Error> {
let frame_decompressed_offset: Vec<_> = compute_frame_decompressed_offset(frames);
// Figure out frame belonging of the objects,
// using the frame offset and the object offset.
let mut frames: Vec<Vec<FileEntry>> = (0..frames.len()).map(|_| Vec::new()).collect();
for entry in entries {
let frame_index = frame_decompressed_offset
.iter()
// Find the index of the frame containing the object (objects are
// assumed to not be split across two frames)
.rposition(|&x| x <= entry.metadata.offset)
.ok_or(Error::CorruptPack)?;
// Compute the offset relative to that frame.
let local_offset = entry.metadata.offset - frame_decompressed_offset[frame_index];
let local_entry = FileEntry::new(
entry.path.clone(),
entry.checksum,
ObjectMetadata {
offset: local_offset, // Replace global offset -> local offset
size: entry.metadata.size,
},
);
frames[frame_index].push(local_entry);
}
Ok(frames)
}
/// Used for timing the different parts of the extraction process.
#[derive(Default)]
struct ExtractStats {
total_time: f64,
seek_time: f64,
object_time: f64,
verify_time: f64,
write_time: f64,
}
impl ExtractStats {
fn other_time(&self) -> f64 {
self.total_time - (self.seek_time + self.object_time + self.verify_time + self.write_time)
}
/// Convert the statistics into fractions, taken relative to `self.total_time`.
fn fractions(&self) -> Self {
let norm_factor = 1f64 / self.total_time;
Self {
total_time: norm_factor * self.total_time,
seek_time: norm_factor * self.seek_time,
object_time: norm_factor * self.object_time,
verify_time: norm_factor * self.verify_time,
write_time: norm_factor * self.write_time,
}
}
}
impl std::ops::Add for ExtractStats {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
total_time: self.total_time + other.total_time,
seek_time: self.seek_time + other.seek_time,
object_time: self.object_time + other.object_time,
verify_time: self.verify_time + other.verify_time,
write_time: self.write_time + other.write_time,
}
}
}
impl std::iter::Sum<ExtractStats> for ExtractStats {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = ExtractStats>,
{
let mut acc = ExtractStats::default();
for x in iter {
acc = acc + x;
}
acc
}
}
/// Extracts the given entries from the pack reader into the specified output directory.
/// Checksum verification can be toggled on/off.
fn extract_files(
mut reader: PackReader,
entries: &[FileEntry],
output_dir: impl AsRef<Path>,
verify: bool,
) -> Result<ExtractStats, Error> {
let mut entries: Vec<FileEntry> = entries.to_vec();
// Sort objects to allow for forward-only seeking
entries.sort_by(|x, y| {
let offset_x = x.metadata.offset;
let offset_y = y.metadata.offset;
offset_x.cmp(&offset_y)
});
// Used for timing
let mut stats = ExtractStats::default();
let total_time = measure_ok(|| -> Result<(), Error> {
// Decompression buffer
let mut buf = vec![];
let mut path_buf = PathBuf::new();
let mut pos = 0;
for entry in entries {
let metadata = &entry.metadata;
// Seek forward
let discard_bytes = metadata.offset - pos;
// Check if we need to read a new object.
// The current position in stream can be AFTER the object offset only
// if the previous and this object are the same. This is because the objects
// are sorted by offset, and the current position is set to the offset at the
// end of each object, after that object is consumed.
if pos <= metadata.offset {
stats.seek_time += measure_ok(|| reader.seek(discard_bytes | {
return Err(PackError::ChecksumMismatch(*exp_checksum, checksum).into());
} | conditional_block |
pack.rs | .map(|s| PackId::Pack(s.to_owned()))
}
fn is_valid(s: &str) -> bool {
s.chars()
.all(|c| c.is_ascii_alphanumeric() || EXTRA_ID_CHARS.contains(&c))
}
}
impl FromStr for PackId {
type Err = IdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if!PackId::is_valid(s) {
return Err(IdError::InvalidPack(s.to_owned()));
}
Ok(PackId::Pack(s.to_owned()))
}
}
impl Display for PackId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
PackId::Pack(s) => write!(f, "{}", s),
}
}
}
/// Identifies a snapshot using a pack base filename [`Path::file_stem`] and a snapshot tag.
#[derive(PartialEq, Clone, Debug)]
pub struct SnapshotId {
pack: PackId,
tag: String,
}
impl SnapshotId {
/// Creates a [`SnapshotId`] from a pack and a snapshot tag
pub fn new(pack: PackId, tag: &str) -> Result<Self, IdError> {
if!Self::is_valid(tag) {
return Err(IdError::InvalidSnapshot(tag.to_owned()));
}
Ok(Self {
pack,
tag: tag.to_owned(),
})
}
pub fn pack(&self) -> &PackId {
&self.pack
}
pub fn tag(&self) -> &str {
&self.tag
}
fn is_valid(tag: &str) -> bool {
tag.chars()
.all(|c| c.is_ascii_alphanumeric() || EXTRA_ID_CHARS.contains(&c))
}
}
/// [`SnapshotId`] equality is a full equivalence relation.
impl Eq for SnapshotId {}
/// Prints the canonical form for [`SnapshotId`].
impl Display for SnapshotId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{}:{}", self.pack, self.tag)
}
}
/// Parses a [`SnapshotId`] from a canonical form string 'pack_name:snapshot_name'.
impl FromStr for SnapshotId {
type Err = IdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some((pack, snapshot)) = s.trim_end().rsplit_once(':') {
if pack.is_empty() {
return Err(IdError::InvalidPack(pack.to_owned()));
}
if snapshot.is_empty() {
return Err(IdError::InvalidSnapshot(snapshot.to_owned()));
}
Ok(SnapshotId {
pack: PackId::from_str(pack)?,
tag: snapshot.to_owned(),
})
} else {
Err(IdError::BadFormat(s.to_owned()))
}
}
}
/// A magic constant that has no use other than to indicate a custom.pack header
/// stored in a Zstandard skippable frame.
const SKIPPABLE_MAGIC_MASK: u32 = 0x184D2A50;
/// Reads a Zstandard skippable frame from reader and writes the result to `buf`.
/// Returns the size of the frame, *not* the number of bytes read.
pub fn read_skippable_frame(mut reader: impl Read, buf: &mut Vec<u8>) -> io::Result<u64> {
fn read_u32_le(mut reader: impl Read) -> io::Result<u32> {
let mut bytes = [0u8; 4];
reader.read_exact(&mut bytes)?;
Ok(u32::from_le_bytes(bytes))
}
// Ensure this is a skippable frame.
let magic = read_u32_le(&mut reader)?;
if magic & SKIPPABLE_MAGIC_MASK!= SKIPPABLE_MAGIC_MASK {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Not a Zstandard skippable frame!",
));
}
let frame_size = read_u32_le(&mut reader)?;
buf.resize(frame_size as usize, 0);
reader.read_exact(buf)?;
// Compute overall frame size.
Ok((std::mem::size_of::<u32>() * 2 + buf.len()) as u64)
}
/// Writes a Zstandard skippable frame with the given user data.
/// Returns the number of bytes written to writer (the size of the frame, including the magic number and header).
pub fn write_skippable_frame(mut writer: impl Write, buf: &[u8]) -> io::Result<u64> {
fn write_u32_le(mut writer: impl Write, value: u32) -> io::Result<()> {
writer.write_all(&value.to_le_bytes())
}
// Ensure this is a skippable frame.
write_u32_le(&mut writer, SKIPPABLE_MAGIC_MASK)?;
write_u32_le(&mut writer, buf.len() as u32)?;
writer.write_all(buf)?;
// Compute overall frame size.
Ok((std::mem::size_of::<u32>() * 2 + buf.len()) as u64)
}
/// The unidirectional stream of data stored in the pack.
enum PackReader {
Compressed(Decoder<'static, BufReader<File>>),
}
impl PackReader {
/// Consumes the specified number of bytes from the reader.
fn seek(&mut self, bytes: u64) -> io::Result<()> {
match self {
Self::Compressed(decoder) => {
io::copy(&mut decoder.by_ref().take(bytes), &mut io::sink()).map(|_| {})
}
}
}
// Reads the exact number of bytes into `buf`.
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
match self {
Self::Compressed(decoder) => decoder.read_exact(buf),
}
}
}
/// Represents a compressed Zstandard frame in the.pack file.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PackFrame {
/// The size of the frame, in bytes.
pub frame_size: u64,
/// The size of the data stream in the frame, once decompressed, in bytes.
pub decompressed_size: u64,
}
/// Represents the custom header in the beginning of a.pack file.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PackHeader {
/// Valid pack headers have this value set to [`PACK_HEADER_MAGIC`].
magic: u64,
/// The list of frames in the pack file, sorted by their byte offsets.
frames: Vec<PackFrame>,
}
impl PackHeader {
/// Create a new pack header.
pub fn new(frames: Vec<PackFrame>) -> Self {
Self {
magic: PACK_HEADER_MAGIC,
frames,
}
}
/// Verifies the header magic.
pub fn is_valid(&self) -> bool {
self.magic == PACK_HEADER_MAGIC
}
}
impl Default for PackHeader {
fn default() -> Self {
Self {
magic: PACK_HEADER_MAGIC,
frames: vec![],
}
}
}
/// Represents an pack file.
pub struct Pack {
/// The base filename ([`Path::file_stem`]) of the pack.
name: String,
/// The index for the pack.
index: PackIndex,
/// The header of the pack.
header: PackHeader,
/// PackReader instances for each frame in the.pack file.
frame_readers: Vec<PackReader>,
/// The file size of the pack (in bytes).
file_size: u64,
}
impl Pack {
/// Opens a pack file and its corresponding index.
///
/// # Arguments
///
/// * `pack_name` - The base filename ([`Path::file_stem`]) of the pack.
pub fn open<P>(repo: P, pack_name: &PackId) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let PackId::Pack(pack_name) = pack_name;
let mut packs_data = repo.as_ref().join(&*Repository::data_dir());
packs_data.push(PACKS_DIR);
let mut pack_index_path = packs_data.join(pack_name);
pack_index_path.set_extension(PACK_INDEX_EXTENSION);
let mut pack_path = packs_data.join(pack_name);
pack_path.set_extension(PACK_EXTENSION);
info!("Reading pack index {:?}...", pack_index_path);
let pack_index = PackIndex::load(&pack_index_path)?;
info!("Opening pack file {:?}...", pack_path);
let (file_size, header, frame_readers) =
Self::open_pack(&pack_path).or_else(|_| Self::open_pack_legacy(&pack_path))?;
Ok(Pack {
name: pack_name.to_owned(),
index: pack_index,
header,
frame_readers,
file_size,
})
}
/// Opens the pack file for reading.
fn open_pack(pack_path: &Path) -> Result<(u64, PackHeader, Vec<PackReader>), Error> {
let file = File::open(&pack_path)?;
let file_size = file.metadata()?.len();
let mut reader = io::BufReader::new(file);
let mut header = vec![];
let header_size = read_skippable_frame(&mut reader, &mut header)?;
let header: PackHeader =
rmp_serde::decode::from_read(&header[..]).map_err(|_| Error::CorruptPack)?;
drop(reader);
if!header.is_valid() {
return Err(Error::CorruptPack);
}
let frame_offsets = compute_frame_offsets(&header.frames);
let frame_readers = frame_offsets
.iter()
.map(|offset| -> Result<_, Error> {
let mut reader = File::open(&pack_path)?;
io::Seek::seek(&mut reader, io::SeekFrom::Start(header_size + offset))?;
let mut reader = Decoder::new(reader)?;
reader.set_parameter(DParameter::WindowLogMax(DEFAULT_WINDOW_LOG_MAX))?;
// Wrap in a `PackReader`.
let reader = PackReader::Compressed(reader);
Ok(reader)
})
.collect::<Result<Vec<_>, _>>()?;
Ok((file_size, header, frame_readers))
}
/// Backwards-compatible open_pack for the legacy pack format (no skippable frame/no header).
fn open_pack_legacy(pack_path: &Path) -> Result<(u64, PackHeader, Vec<PackReader>), Error> {
let file = File::open(&pack_path)?;
let file_size = file.metadata()?.len();
// This manufactured pack header works for the current implementation. We might
// change how/whether we support the legacy pack format in the future...
let header = PackHeader::new(vec![PackFrame {
frame_size: file_size,
decompressed_size: u64::MAX,
}]);
let mut reader = Decoder::new(file)?;
reader.set_parameter(DParameter::WindowLogMax(DEFAULT_WINDOW_LOG_MAX))?;
let frame_reader = PackReader::Compressed(reader);
Ok((file_size, header, vec![frame_reader]))
}
/// The base filename ([`Path::file_stem`]) of the pack.
pub fn name(&self) -> &str {
&self.name
}
/// A reference to the pack index.
pub fn index(&self) -> &PackIndex {
&self.index
}
/// The size of the pack in bytes.
pub fn file_size(&self) -> u64 {
self.file_size
}
/// Extracts the specified entries from the pack into the specified directory.
/// This operation consumes the pack, since [`Pack`] objects contain a unidirectional
/// data stream that becomes unusable after it is read.
///
/// # Arguments
///
/// * `entries` - The list of entries to extract. These *must* be entries contained in the pack index.
/// * `output_dir` - The directory relative to which the files will be extracted.
/// * `verify` - Enable/disable checksum verification.
#[allow(unused_mut)]
#[allow(clippy::needless_collect)]
pub(crate) fn extract_entries<P>(
mut self,
entries: &[FileEntry],
output_dir: P,
verify: bool,
num_workers: u32,
) -> Result<(), Error>
where
P: AsRef<Path> + Sync,
{
if entries.is_empty() {
return Ok(());
}
let num_frames = self.header.frames.len();
assert_ne!(0, num_workers);
assert_ne!(0, num_frames);
if num_frames < num_workers as usize {
info!(
"Requested {} workers, but there are only {} frames!",
num_workers, num_frames
);
}
let num_workers = std::cmp::min(num_workers, num_frames as u32);
// Assign entries to the frames they reside in.
// The resulting entries will have offsets relative to their containing frame.
let frame_to_entries = assign_to_frames(&self.header.frames, entries)?;
// Compute and log total amount of seeking and decompression needed.
let bytes_to_decompress = frame_to_entries
.iter()
.flat_map(|entries| {
entries
.iter()
.map(|e| e.metadata.offset + e.metadata.offset)
.max()
})
.sum::<u64>();
info!(
"Decompressing {:.3} MiB of data...",
bytes_to_decompress as f64 / 1024f64 / 1024f64
);
// Collect required for run_in_parallel ExactSizeIterator argument.
let tasks = self
.frame_readers
.into_iter()
.zip(frame_to_entries.into_iter())
// Skip empty frames.
.filter(|(_, entries)|!entries.is_empty())
.collect::<Vec<_>>();
// Record start time
let start_time = std::time::Instant::now();
let results = run_in_parallel(
num_workers as usize,
tasks.into_iter(),
|(frame_reader, entries)| extract_files(frame_reader, &entries, &output_dir, verify),
);
// Collect stats
let stats = results
.into_iter()
.sum::<Result<ExtractStats, Error>>()?
// Convert the statistics into fractions, since summing the time per thread doesn't make much sense.
.fractions();
// Log statistics about the decompression performance
let real_time = std::time::Instant::now() - start_time;
info!(
"Decompression statistics ({:?})\n\
\tSeeking: {:.1}%\n\
\tObject decompression: {:.1}%\n\
\tVerification: {:.1}%\n\
\tWriting to disk: {:.1}%\n\
\tOther: {:.1}%",
real_time,
stats.seek_time * 100f64,
stats.object_time * 100f64,
stats.verify_time * 100f64,
stats.write_time * 100f64,
stats.other_time() * 100f64,
);
Ok(())
}
}
/// Verifies that the object has the expected checksum.
fn verify_object(buf: &[u8], exp_checksum: &ObjectChecksum) -> Result<(), Error> {
// Verify checksum
let mut checksum = [0u8; 20];
let mut hasher = Sha1::new();
hasher.input(buf);
hasher.result(&mut checksum);
if &checksum!= exp_checksum {
return Err(PackError::ChecksumMismatch(*exp_checksum, checksum).into());
}
Ok(())
}
/// Writes the object to the specified path, taking care
/// of adjusting file permissions.
fn write_object(buf: &[u8], path: &Path) -> Result<(), Error> {
fs::create_dir_all(path.parent().unwrap())?;
let mut f = File::create(path)?;
f.write_all(buf)?;
Ok(())
}
/// Returns a list of the frame offsets, computed
/// using the order and sizes of the given frames.
fn | (frames: &[PackFrame]) -> Vec<u64> {
let mut frame_offsets: Vec<_> = vec![0; frames.len()];
for i in 1..frame_offsets.len() {
frame_offsets[i] = frames[i - 1].frame_size + frame_offsets[i - 1];
}
frame_offsets
}
/// Returns a list of the data offsets, computed using the order and
/// decompressed sizes of the given frames.
fn compute_frame_decompressed_offset(frames: &[PackFrame]) -> Vec<u64> {
let mut frame_decompressed_offset: Vec<_> = vec![0; frames.len()];
for i in 1..frame_decompressed_offset.len() {
frame_decompressed_offset[i] =
frames[i - 1].decompressed_size + frame_decompressed_offset[i - 1];
}
frame_decompressed_offset
}
/// Groups and transforms the list of [`FileEntry`]-s taken from a pack index
/// (and with absolute offsets into the decompressed stream) into sets of
/// entries per frame, with adjusted (relative) offsets to that corresponding
/// Zstandard frame. Objects are assumed to not be split across two frames.
fn assign_to_frames(
frames: &[PackFrame],
entries: &[FileEntry],
) -> Result<Vec<Vec<FileEntry>>, Error> {
let frame_decompressed_offset: Vec<_> = compute_frame_decompressed_offset(frames);
// Figure out frame belonging of the objects,
// using the frame offset and the object offset.
let mut frames: Vec<Vec<FileEntry>> = (0..frames.len()).map(|_| Vec::new()).collect();
for entry in entries {
let frame_index = frame_decompressed_offset
.iter()
// Find the index of the frame containing the object (objects are
// assumed to not be split across two frames)
.rposition(|&x| x <= entry.metadata.offset)
.ok_or(Error::CorruptPack)?;
// Compute the offset relative to that frame.
let local_offset = entry.metadata.offset - frame_decompressed_offset[frame_index];
let local_entry = FileEntry::new(
entry.path.clone(),
entry.checksum,
ObjectMetadata {
offset: local_offset, // Replace global offset -> local offset
size: entry.metadata.size,
},
);
frames[frame_index].push(local_entry);
}
Ok(frames)
}
/// Used for timing the different parts of the extraction process.
#[derive(Default)]
struct ExtractStats {
total_time: f64,
seek_time: f64,
object_time: f64,
verify_time: f64,
write_time: f64,
}
impl ExtractStats {
fn other_time(&self) -> f64 {
self.total_time - (self.seek_time + self.object_time + self.verify_time + self.write_time)
}
/// Convert the statistics into fractions, taken relative to `self.total_time`.
fn fractions(&self) -> Self {
let norm_factor = 1f64 / self.total_time;
Self {
total_time: norm_factor * self.total_time,
seek_time: norm_factor * self.seek_time,
object_time: norm_factor * self.object_time,
verify_time: norm_factor * self.verify_time,
write_time: norm_factor * self.write_time,
}
}
}
impl std::ops::Add for ExtractStats {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
total_time: self.total_time + other.total_time,
seek_time: self.seek_time + other.seek_time,
object_time: self.object_time + other.object_time,
verify_time: self.verify_time + other.verify_time,
write_time: self.write_time + other.write_time,
}
}
}
impl std::iter::Sum<ExtractStats> for ExtractStats {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = ExtractStats>,
{
let mut acc = ExtractStats::default();
for x in iter {
acc = acc + x;
}
acc
}
}
/// Extracts the given entries from the pack reader into the specified output directory.
/// Checksum verification can be toggled on/off.
fn extract_files(
mut reader: PackReader,
entries: &[FileEntry],
output_dir: impl AsRef<Path>,
verify: bool,
) -> Result<ExtractStats, Error> {
let mut entries: Vec<FileEntry> = entries.to_vec();
// Sort objects to allow for forward-only seeking
entries.sort_by(|x, y| {
let offset_x = x.metadata.offset;
let offset_y = y.metadata.offset;
offset_x.cmp(&offset_y)
});
// Used for timing
let mut stats = ExtractStats::default();
let total_time = measure_ok(|| -> Result<(), Error> {
// Decompression buffer
let mut buf = vec![];
let mut path_buf = PathBuf::new();
let mut pos = 0;
for entry in entries {
let metadata = &entry.metadata;
// Seek forward
let discard_bytes = metadata.offset - pos;
// Check if we need to read a new object.
// The current position in stream can be AFTER the object offset only
// if the previous and this object are the same. This is because the objects
// are sorted by offset, and the current position is set to the offset at the
// end of each object, after that object is consumed.
if pos <= metadata.offset {
stats.seek_time += measure_ok(|| reader.seek(discard_bytes | compute_frame_offsets | identifier_name |
pack.rs | Result<Self, Self::Err> {
if let Some((pack, snapshot)) = s.trim_end().rsplit_once(':') {
if pack.is_empty() {
return Err(IdError::InvalidPack(pack.to_owned()));
}
if snapshot.is_empty() {
return Err(IdError::InvalidSnapshot(snapshot.to_owned()));
}
Ok(SnapshotId {
pack: PackId::from_str(pack)?,
tag: snapshot.to_owned(),
})
} else {
Err(IdError::BadFormat(s.to_owned()))
}
}
}
/// A magic constant that has no use other than to indicate a custom.pack header
/// stored in a Zstandard skippable frame.
const SKIPPABLE_MAGIC_MASK: u32 = 0x184D2A50;
/// Reads a Zstandard skippable frame from reader and writes the result to `buf`.
/// Returns the size of the frame, *not* the number of bytes read.
pub fn read_skippable_frame(mut reader: impl Read, buf: &mut Vec<u8>) -> io::Result<u64> {
fn read_u32_le(mut reader: impl Read) -> io::Result<u32> {
let mut bytes = [0u8; 4];
reader.read_exact(&mut bytes)?;
Ok(u32::from_le_bytes(bytes))
}
// Ensure this is a skippable frame.
let magic = read_u32_le(&mut reader)?;
if magic & SKIPPABLE_MAGIC_MASK!= SKIPPABLE_MAGIC_MASK {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Not a Zstandard skippable frame!",
));
}
let frame_size = read_u32_le(&mut reader)?;
buf.resize(frame_size as usize, 0);
reader.read_exact(buf)?;
// Compute overall frame size.
Ok((std::mem::size_of::<u32>() * 2 + buf.len()) as u64)
}
/// Writes a Zstandard skippable frame with the given user data.
/// Returns the number of bytes written to writer (the size of the frame, including the magic number and header).
pub fn write_skippable_frame(mut writer: impl Write, buf: &[u8]) -> io::Result<u64> {
fn write_u32_le(mut writer: impl Write, value: u32) -> io::Result<()> {
writer.write_all(&value.to_le_bytes())
}
// Ensure this is a skippable frame.
write_u32_le(&mut writer, SKIPPABLE_MAGIC_MASK)?;
write_u32_le(&mut writer, buf.len() as u32)?;
writer.write_all(buf)?;
// Compute overall frame size.
Ok((std::mem::size_of::<u32>() * 2 + buf.len()) as u64)
}
/// The unidirectional stream of data stored in the pack.
enum PackReader {
Compressed(Decoder<'static, BufReader<File>>),
}
impl PackReader {
/// Consumes the specified number of bytes from the reader.
fn seek(&mut self, bytes: u64) -> io::Result<()> {
match self {
Self::Compressed(decoder) => {
io::copy(&mut decoder.by_ref().take(bytes), &mut io::sink()).map(|_| {})
}
}
}
// Reads the exact number of bytes into `buf`.
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
match self {
Self::Compressed(decoder) => decoder.read_exact(buf),
}
}
}
/// Represents a compressed Zstandard frame in the.pack file.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PackFrame {
/// The size of the frame, in bytes.
pub frame_size: u64,
/// The size of the data stream in the frame, once decompressed, in bytes.
pub decompressed_size: u64,
}
/// Represents the custom header in the beginning of a.pack file.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PackHeader {
/// Valid pack headers have this value set to [`PACK_HEADER_MAGIC`].
magic: u64,
/// The list of frames in the pack file, sorted by their byte offsets.
frames: Vec<PackFrame>,
}
impl PackHeader {
/// Create a new pack header.
pub fn new(frames: Vec<PackFrame>) -> Self {
Self {
magic: PACK_HEADER_MAGIC,
frames,
}
}
/// Verifies the header magic.
pub fn is_valid(&self) -> bool {
self.magic == PACK_HEADER_MAGIC
}
}
impl Default for PackHeader {
fn default() -> Self {
Self {
magic: PACK_HEADER_MAGIC,
frames: vec![],
}
}
}
/// Represents an pack file.
pub struct Pack {
/// The base filename ([`Path::file_stem`]) of the pack.
name: String,
/// The index for the pack.
index: PackIndex,
/// The header of the pack.
header: PackHeader,
/// PackReader instances for each frame in the.pack file.
frame_readers: Vec<PackReader>,
/// The file size of the pack (in bytes).
file_size: u64,
}
impl Pack {
/// Opens a pack file and its corresponding index.
///
/// # Arguments
///
/// * `pack_name` - The base filename ([`Path::file_stem`]) of the pack.
pub fn open<P>(repo: P, pack_name: &PackId) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let PackId::Pack(pack_name) = pack_name;
let mut packs_data = repo.as_ref().join(&*Repository::data_dir());
packs_data.push(PACKS_DIR);
let mut pack_index_path = packs_data.join(pack_name);
pack_index_path.set_extension(PACK_INDEX_EXTENSION);
let mut pack_path = packs_data.join(pack_name);
pack_path.set_extension(PACK_EXTENSION);
info!("Reading pack index {:?}...", pack_index_path);
let pack_index = PackIndex::load(&pack_index_path)?;
info!("Opening pack file {:?}...", pack_path);
let (file_size, header, frame_readers) =
Self::open_pack(&pack_path).or_else(|_| Self::open_pack_legacy(&pack_path))?;
Ok(Pack {
name: pack_name.to_owned(),
index: pack_index,
header,
frame_readers,
file_size,
})
}
/// Opens the pack file for reading.
fn open_pack(pack_path: &Path) -> Result<(u64, PackHeader, Vec<PackReader>), Error> {
let file = File::open(&pack_path)?;
let file_size = file.metadata()?.len();
let mut reader = io::BufReader::new(file);
let mut header = vec![];
let header_size = read_skippable_frame(&mut reader, &mut header)?;
let header: PackHeader =
rmp_serde::decode::from_read(&header[..]).map_err(|_| Error::CorruptPack)?;
drop(reader);
if!header.is_valid() {
return Err(Error::CorruptPack);
}
let frame_offsets = compute_frame_offsets(&header.frames);
let frame_readers = frame_offsets
.iter()
.map(|offset| -> Result<_, Error> {
let mut reader = File::open(&pack_path)?;
io::Seek::seek(&mut reader, io::SeekFrom::Start(header_size + offset))?;
let mut reader = Decoder::new(reader)?;
reader.set_parameter(DParameter::WindowLogMax(DEFAULT_WINDOW_LOG_MAX))?;
// Wrap in a `PackReader`.
let reader = PackReader::Compressed(reader);
Ok(reader)
})
.collect::<Result<Vec<_>, _>>()?;
Ok((file_size, header, frame_readers))
}
/// Backwards-compatible open_pack for the legacy pack format (no skippable frame/no header).
fn open_pack_legacy(pack_path: &Path) -> Result<(u64, PackHeader, Vec<PackReader>), Error> {
let file = File::open(&pack_path)?;
let file_size = file.metadata()?.len();
// This manufactured pack header works for the current implementation. We might
// change how/whether we support the legacy pack format in the future...
let header = PackHeader::new(vec![PackFrame {
frame_size: file_size,
decompressed_size: u64::MAX,
}]);
let mut reader = Decoder::new(file)?;
reader.set_parameter(DParameter::WindowLogMax(DEFAULT_WINDOW_LOG_MAX))?;
let frame_reader = PackReader::Compressed(reader);
Ok((file_size, header, vec![frame_reader]))
}
/// The base filename ([`Path::file_stem`]) of the pack.
pub fn name(&self) -> &str {
&self.name
}
/// A reference to the pack index.
pub fn index(&self) -> &PackIndex {
&self.index
}
/// The size of the pack in bytes.
pub fn file_size(&self) -> u64 {
self.file_size
}
/// Extracts the specified entries from the pack into the specified directory.
/// This operation consumes the pack, since [`Pack`] objects contain a unidirectional
/// data stream that becomes unusable after it is read.
///
/// # Arguments
///
/// * `entries` - The list of entries to extract. These *must* be entries contained in the pack index.
/// * `output_dir` - The directory relative to which the files will be extracted.
/// * `verify` - Enable/disable checksum verification.
#[allow(unused_mut)]
#[allow(clippy::needless_collect)]
pub(crate) fn extract_entries<P>(
mut self,
entries: &[FileEntry],
output_dir: P,
verify: bool,
num_workers: u32,
) -> Result<(), Error>
where
P: AsRef<Path> + Sync,
{
if entries.is_empty() {
return Ok(());
}
let num_frames = self.header.frames.len();
assert_ne!(0, num_workers);
assert_ne!(0, num_frames);
if num_frames < num_workers as usize {
info!(
"Requested {} workers, but there are only {} frames!",
num_workers, num_frames
);
}
let num_workers = std::cmp::min(num_workers, num_frames as u32);
// Assign entries to the frames they reside in.
// The resulting entries will have offsets relative to their containing frame.
let frame_to_entries = assign_to_frames(&self.header.frames, entries)?;
// Compute and log total amount of seeking and decompression needed.
let bytes_to_decompress = frame_to_entries
.iter()
.flat_map(|entries| {
entries
.iter()
.map(|e| e.metadata.offset + e.metadata.offset)
.max()
})
.sum::<u64>();
info!(
"Decompressing {:.3} MiB of data...",
bytes_to_decompress as f64 / 1024f64 / 1024f64
);
// Collect required for run_in_parallel ExactSizeIterator argument.
let tasks = self
.frame_readers
.into_iter()
.zip(frame_to_entries.into_iter())
// Skip empty frames.
.filter(|(_, entries)|!entries.is_empty())
.collect::<Vec<_>>();
// Record start time
let start_time = std::time::Instant::now();
let results = run_in_parallel(
num_workers as usize,
tasks.into_iter(),
|(frame_reader, entries)| extract_files(frame_reader, &entries, &output_dir, verify),
);
// Collect stats
let stats = results
.into_iter()
.sum::<Result<ExtractStats, Error>>()?
// Convert the statistics into fractions, since summing the time per thread doesn't make much sense.
.fractions();
// Log statistics about the decompression performance
let real_time = std::time::Instant::now() - start_time;
info!(
"Decompression statistics ({:?})\n\
\tSeeking: {:.1}%\n\
\tObject decompression: {:.1}%\n\
\tVerification: {:.1}%\n\
\tWriting to disk: {:.1}%\n\
\tOther: {:.1}%",
real_time,
stats.seek_time * 100f64,
stats.object_time * 100f64,
stats.verify_time * 100f64,
stats.write_time * 100f64,
stats.other_time() * 100f64,
);
Ok(())
}
}
/// Verifies that the object has the expected checksum.
fn verify_object(buf: &[u8], exp_checksum: &ObjectChecksum) -> Result<(), Error> {
// Verify checksum
let mut checksum = [0u8; 20];
let mut hasher = Sha1::new();
hasher.input(buf);
hasher.result(&mut checksum);
if &checksum!= exp_checksum {
return Err(PackError::ChecksumMismatch(*exp_checksum, checksum).into());
}
Ok(())
}
/// Writes the object to the specified path, taking care
/// of adjusting file permissions.
fn write_object(buf: &[u8], path: &Path) -> Result<(), Error> {
fs::create_dir_all(path.parent().unwrap())?;
let mut f = File::create(path)?;
f.write_all(buf)?;
Ok(())
}
/// Returns a list of the frame offsets, computed
/// using the order and sizes of the given frames.
fn compute_frame_offsets(frames: &[PackFrame]) -> Vec<u64> {
let mut frame_offsets: Vec<_> = vec![0; frames.len()];
for i in 1..frame_offsets.len() {
frame_offsets[i] = frames[i - 1].frame_size + frame_offsets[i - 1];
}
frame_offsets
}
/// Returns a list of the data offsets, computed using the order and
/// decompressed sizes of the given frames.
fn compute_frame_decompressed_offset(frames: &[PackFrame]) -> Vec<u64> {
let mut frame_decompressed_offset: Vec<_> = vec![0; frames.len()];
for i in 1..frame_decompressed_offset.len() {
frame_decompressed_offset[i] =
frames[i - 1].decompressed_size + frame_decompressed_offset[i - 1];
}
frame_decompressed_offset
}
/// Groups and transforms the list of [`FileEntry`]-s taken from a pack index
/// (and with absolute offsets into the decompressed stream) into sets of
/// entries per frame, with adjusted (relative) offsets to that corresponding
/// Zstandard frame. Objects are assumed to not be split across two frames.
fn assign_to_frames(
frames: &[PackFrame],
entries: &[FileEntry],
) -> Result<Vec<Vec<FileEntry>>, Error> {
let frame_decompressed_offset: Vec<_> = compute_frame_decompressed_offset(frames);
// Figure out frame belonging of the objects,
// using the frame offset and the object offset.
let mut frames: Vec<Vec<FileEntry>> = (0..frames.len()).map(|_| Vec::new()).collect();
for entry in entries {
let frame_index = frame_decompressed_offset
.iter()
// Find the index of the frame containing the object (objects are
// assumed to not be split across two frames)
.rposition(|&x| x <= entry.metadata.offset)
.ok_or(Error::CorruptPack)?;
// Compute the offset relative to that frame.
let local_offset = entry.metadata.offset - frame_decompressed_offset[frame_index];
let local_entry = FileEntry::new(
entry.path.clone(),
entry.checksum,
ObjectMetadata {
offset: local_offset, // Replace global offset -> local offset
size: entry.metadata.size,
},
);
frames[frame_index].push(local_entry);
}
Ok(frames)
}
/// Used for timing the different parts of the extraction process.
#[derive(Default)]
struct ExtractStats {
total_time: f64,
seek_time: f64,
object_time: f64,
verify_time: f64,
write_time: f64,
}
impl ExtractStats {
fn other_time(&self) -> f64 {
self.total_time - (self.seek_time + self.object_time + self.verify_time + self.write_time)
}
/// Convert the statistics into fractions, taken relative to `self.total_time`.
fn fractions(&self) -> Self {
let norm_factor = 1f64 / self.total_time;
Self {
total_time: norm_factor * self.total_time,
seek_time: norm_factor * self.seek_time,
object_time: norm_factor * self.object_time,
verify_time: norm_factor * self.verify_time,
write_time: norm_factor * self.write_time,
}
}
}
impl std::ops::Add for ExtractStats {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
total_time: self.total_time + other.total_time,
seek_time: self.seek_time + other.seek_time,
object_time: self.object_time + other.object_time,
verify_time: self.verify_time + other.verify_time,
write_time: self.write_time + other.write_time,
}
}
}
impl std::iter::Sum<ExtractStats> for ExtractStats {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = ExtractStats>,
{
let mut acc = ExtractStats::default();
for x in iter {
acc = acc + x;
}
acc
}
}
/// Extracts the given entries from the pack reader into the specified output directory.
/// Checksum verification can be toggled on/off.
fn extract_files(
mut reader: PackReader,
entries: &[FileEntry],
output_dir: impl AsRef<Path>,
verify: bool,
) -> Result<ExtractStats, Error> {
let mut entries: Vec<FileEntry> = entries.to_vec();
// Sort objects to allow for forward-only seeking
entries.sort_by(|x, y| {
let offset_x = x.metadata.offset;
let offset_y = y.metadata.offset;
offset_x.cmp(&offset_y)
});
// Used for timing
let mut stats = ExtractStats::default();
let total_time = measure_ok(|| -> Result<(), Error> {
// Decompression buffer
let mut buf = vec![];
let mut path_buf = PathBuf::new();
let mut pos = 0;
for entry in entries {
let metadata = &entry.metadata;
// Seek forward
let discard_bytes = metadata.offset - pos;
// Check if we need to read a new object.
// The current position in stream can be AFTER the object offset only
// if the previous and this object are the same. This is because the objects
// are sorted by offset, and the current position is set to the offset at the
// end of each object, after that object is consumed.
if pos <= metadata.offset {
stats.seek_time += measure_ok(|| reader.seek(discard_bytes))?.0.as_secs_f64();
// Resize buf
buf.resize(metadata.size as usize, 0);
// Read object
stats.object_time += measure_ok(|| reader.read_exact(&mut buf[..]))?
.0
.as_secs_f64();
pos = metadata.offset + metadata.size;
if verify {
stats.verify_time += measure_ok(|| verify_object(&buf[..], &entry.checksum))?
.0
.as_secs_f64();
}
}
// Output path
path_buf.clear();
path_buf.push(&output_dir);
path_buf.push(&entry.path);
stats.write_time += measure_ok(|| write_object(&buf[..], &path_buf))?
.0
.as_secs_f64();
}
Ok(())
})?
.0;
stats.total_time = total_time.as_secs_f64();
Ok(stats)
}
#[cfg(test)]
mod tests {
use super::*;
fn make_md(offset: u64, size: u64) -> ObjectMetadata {
ObjectMetadata { offset, size }
}
#[test]
fn pack_id_validation_works() {
// VALID
assert!(PackId::is_valid("ABCD"));
assert!(PackId::is_valid("abcd"));
assert!(PackId::is_valid("____"));
assert!(PackId::is_valid("----"));
assert!(PackId::is_valid("ABCD-132_TAG"));
// NOT VALID
// spaces | assert!(!PackId::is_valid("Some Text"));
// non-latin alphabets
assert!(!PackId::is_valid("това-е-тест")); | random_line_split |
|
mod.rs | //! This module is an attempt to provide a friendly, rust-esque interface to Apple's Audio Unit API.
//!
//! Learn more about the Audio Unit API [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40003278-CH1-SW2)
//! and [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html).
//!
//! TODO: The following are `kAudioUnitSubType`s (along with their const u32) generated by
//! rust-bindgen that we could not find any documentation on:
//!
//! - MIDISynth = 1836284270,
//! - RoundTripAAC = 1918984547,
//! - SpatialMixer = 862217581,
//! - SphericalHeadPanner = 1936746610,
//! - VectorPanner = 1986158963,
//! - SoundFieldPanner = 1634558569,
//! - HRTFPanner = 1752331366,
//! - NetReceive = 1852990326,
//!
//! If you can find documentation on these, please feel free to submit an issue or PR with the
//! fixes!
use crate::error::Error;
use std::mem;
use std::os::raw::{c_uint, c_void};
use std::ptr;
use sys;
| EffectType, FormatConverterType, GeneratorType, IOType, MixerType, MusicDeviceType, Type,
};
#[cfg(target_os = "macos")]
pub mod macos_helpers;
pub mod audio_format;
pub mod render_callback;
pub mod sample_format;
pub mod stream_format;
pub mod types;
/// The input and output **Scope**s.
///
/// More info [here](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnitPropertiesReference/index.html#//apple_ref/doc/constant_group/Audio_Unit_Scopes)
/// and [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html).
#[derive(Copy, Clone, Debug)]
pub enum Scope {
Global = 0,
Input = 1,
Output = 2,
Group = 3,
Part = 4,
Note = 5,
Layer = 6,
LayerItem = 7,
}
/// Represents the **Input** and **Output** **Element**s.
///
/// These are used when specifying which **Element** we're setting the properties of.
#[derive(Copy, Clone, Debug)]
pub enum Element {
Output = 0,
Input = 1,
}
/// A rust representation of the sys::AudioUnit, including a pointer to the current rendering callback.
///
/// Find the original Audio Unit Programming Guide [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html).
pub struct AudioUnit {
instance: sys::AudioUnit,
maybe_render_callback: Option<*mut render_callback::InputProcFnWrapper>,
maybe_input_callback: Option<InputCallback>,
}
struct InputCallback {
// The audio buffer list to which input data is rendered.
buffer_list: *mut sys::AudioBufferList,
callback: *mut render_callback::InputProcFnWrapper,
}
macro_rules! try_os_status {
($expr:expr) => {
Error::from_os_status($expr)?
};
}
impl AudioUnit {
/// Construct a new AudioUnit with any type that may be automatically converted into
/// [**Type**](./enum.Type).
///
/// Here is a list of compatible types:
///
/// - [**Type**](./types/enum.Type)
/// - [**IOType**](./types/enum.IOType)
/// - [**MusicDeviceType**](./types/enum.MusicDeviceType)
/// - [**GeneratorType**](./types/enum.GeneratorType)
/// - [**FormatConverterType**](./types/enum.FormatConverterType)
/// - [**EffectType**](./types/enum.EffectType)
/// - [**MixerType**](./types/enum.MixerType)
///
/// To construct the **AudioUnit** with some component flags, see
/// [**AudioUnit::new_with_flags**](./struct.AudioUnit#method.new_with_flags).
///
/// Note: the `AudioUnit` is constructed with the `kAudioUnitManufacturer_Apple` Manufacturer
/// Identifier, as this is the only Audio Unit Manufacturer Identifier documented by Apple in
/// the AudioUnit reference (see [here](https://developer.apple.com/library/prerelease/mac/documentation/AudioUnit/Reference/AUComponentServicesReference/index.html#//apple_ref/doc/constant_group/Audio_Unit_Manufacturer_Identifier)).
pub fn new<T>(ty: T) -> Result<AudioUnit, Error>
where
T: Into<Type>,
{
AudioUnit::new_with_flags(ty, 0, 0)
}
/// The same as [**AudioUnit::new**](./struct.AudioUnit#method.new) but with the given
/// component flags and mask.
pub fn new_with_flags<T>(ty: T, flags: u32, mask: u32) -> Result<AudioUnit, Error>
where
T: Into<Type>,
{
const MANUFACTURER_IDENTIFIER: u32 = sys::kAudioUnitManufacturer_Apple;
let au_type: Type = ty.into();
let sub_type_u32 = match au_type.as_subtype_u32() {
Some(u) => u,
None => return Err(Error::NoKnownSubtype),
};
// A description of the audio unit we desire.
let desc = sys::AudioComponentDescription {
componentType: au_type.as_u32() as c_uint,
componentSubType: sub_type_u32 as c_uint,
componentManufacturer: MANUFACTURER_IDENTIFIER,
componentFlags: flags,
componentFlagsMask: mask,
};
unsafe {
// Find the default audio unit for the description.
//
// From the "Audio Unit Hosting Guide for iOS":
//
// Passing NULL to the first parameter of AudioComponentFindNext tells this function to
// find the first system audio unit matching the description, using a system-defined
// ordering. If you instead pass a previously found audio unit reference in this
// parameter, the function locates the next audio unit matching the description.
let component = sys::AudioComponentFindNext(ptr::null_mut(), &desc as *const _);
if component.is_null() {
return Err(Error::NoMatchingDefaultAudioUnitFound);
}
// Create an instance of the default audio unit using the component.
let mut instance_uninit = mem::MaybeUninit::<sys::AudioUnit>::uninit();
try_os_status!(sys::AudioComponentInstanceNew(
component,
instance_uninit.as_mut_ptr() as *mut sys::AudioUnit
));
let instance: sys::AudioUnit = instance_uninit.assume_init();
// Initialise the audio unit!
try_os_status!(sys::AudioUnitInitialize(instance));
Ok(AudioUnit {
instance,
maybe_render_callback: None,
maybe_input_callback: None,
})
}
}
/// On successful initialization, the audio formats for input and output are valid
/// and the audio unit is ready to render. During initialization, an audio unit
/// allocates memory according to the maximum number of audio frames it can produce
/// in response to a single render call.
///
/// Usually, the state of an audio unit (such as its I/O formats and memory allocations)
/// cannot be changed while an audio unit is initialized.
pub fn initialize(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioUnitInitialize(self.instance));
}
Ok(())
}
/// Before you change an initialize audio unit’s processing characteristics,
/// such as its input or output audio data format or its sample rate, you must
/// first uninitialize it. Calling this function deallocates the audio unit’s resources.
///
/// After calling this function, you can reconfigure the audio unit and then call
/// AudioUnitInitialize to reinitialize it.
pub fn uninitialize(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioUnitUninitialize(self.instance));
}
Ok(())
}
/// Sets the value for some property of the **AudioUnit**.
///
/// To clear an audio unit property value, set the data paramater with `None::<()>`.
///
/// Clearing properties only works for those properties that do not have a default value.
///
/// For more on "properties" see [the reference](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnitPropertiesReference/index.html#//apple_ref/doc/uid/TP40007288).
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
/// - **maybe_data**: The value that you want to apply to the property.
pub fn set_property<T>(
&mut self,
id: u32,
scope: Scope,
elem: Element,
maybe_data: Option<&T>,
) -> Result<(), Error> {
set_property(self.instance, id, scope, elem, maybe_data)
}
/// Gets the value of an **AudioUnit** property.
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
pub fn get_property<T>(&self, id: u32, scope: Scope, elem: Element) -> Result<T, Error> {
get_property(self.instance, id, scope, elem)
}
/// Starts an I/O **AudioUnit**, which in turn starts the audio unit processing graph that it is
/// connected to.
///
/// **Available** in OS X v10.0 and later.
pub fn start(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioOutputUnitStart(self.instance));
}
Ok(())
}
/// Stops an I/O **AudioUnit**, which in turn stops the audio unit processing graph that it is
/// connected to.
///
/// **Available** in OS X v10.0 and later.
pub fn stop(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioOutputUnitStop(self.instance));
}
Ok(())
}
/// Set the **AudioUnit**'s sample rate.
///
/// **Available** in iOS 2.0 and later.
pub fn set_sample_rate(&mut self, sample_rate: f64) -> Result<(), Error> {
let id = sys::kAudioUnitProperty_SampleRate;
self.set_property(id, Scope::Input, Element::Output, Some(&sample_rate))
}
/// Get the **AudioUnit**'s sample rate.
pub fn sample_rate(&self) -> Result<f64, Error> {
let id = sys::kAudioUnitProperty_SampleRate;
self.get_property(id, Scope::Input, Element::Output)
}
/// Sets the current **StreamFormat** for the AudioUnit.
///
/// Core Audio uses slightly different defaults depending on the platform.
///
/// From the Core Audio Overview:
///
/// > The canonical formats in Core Audio are as follows:
/// >
/// > - iOS input and output: Linear PCM with 16-bit integer samples.
/// > - iOS audio units and other audio processing: Noninterleaved linear PCM with 8.24-bit
/// fixed-point samples
/// > - Mac input and output: Linear PCM with 32-bit floating point samples.
/// > - Mac audio units and other audio processing: Noninterleaved linear PCM with 32-bit
/// floating-point
pub fn set_stream_format(
&mut self,
stream_format: StreamFormat,
scope: Scope,
) -> Result<(), Error> {
let id = sys::kAudioUnitProperty_StreamFormat;
let asbd = stream_format.to_asbd();
self.set_property(id, scope, Element::Output, Some(&asbd))
}
/// Return the current Stream Format for the AudioUnit.
pub fn stream_format(&self, scope: Scope) -> Result<StreamFormat, Error> {
let id = sys::kAudioUnitProperty_StreamFormat;
let asbd = self.get_property(id, scope, Element::Output)?;
StreamFormat::from_asbd(asbd)
}
/// Return the current output Stream Format for the AudioUnit.
pub fn output_stream_format(&self) -> Result<StreamFormat, Error> {
self.stream_format(Scope::Output)
}
/// Return the current input Stream Format for the AudioUnit.
pub fn input_stream_format(&self) -> Result<StreamFormat, Error> {
self.stream_format(Scope::Input)
}
}
unsafe impl Send for AudioUnit {}
impl Drop for AudioUnit {
fn drop(&mut self) {
unsafe {
use crate::error;
// We don't want to panic in `drop`, so we'll ignore returned errors.
//
// A user should explicitly terminate the `AudioUnit` if they want to handle errors (we
// still need to provide a way to actually do that).
self.stop().ok();
error::Error::from_os_status(sys::AudioUnitUninitialize(self.instance)).ok();
self.free_render_callback();
self.free_input_callback();
error::Error::from_os_status(sys::AudioComponentInstanceDispose(self.instance)).ok();
}
}
}
/// Sets the value for some property of the **AudioUnit**.
///
/// To clear an audio unit property value, set the data paramater with `None::<()>`.
///
/// Clearing properties only works for those properties that do not have a default value.
///
/// For more on "properties" see [the reference](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnitPropertiesReference/index.html#//apple_ref/doc/uid/TP40007288).
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **au**: The AudioUnit instance.
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
/// - **maybe_data**: The value that you want to apply to the property.
pub fn set_property<T>(
au: sys::AudioUnit,
id: u32,
scope: Scope,
elem: Element,
maybe_data: Option<&T>,
) -> Result<(), Error> {
let (data_ptr, size) = maybe_data
.map(|data| {
let ptr = data as *const _ as *const c_void;
let size = ::std::mem::size_of::<T>() as u32;
(ptr, size)
})
.unwrap_or_else(|| (::std::ptr::null(), 0));
let scope = scope as c_uint;
let elem = elem as c_uint;
unsafe {
try_os_status!(sys::AudioUnitSetProperty(
au, id, scope, elem, data_ptr, size
))
}
Ok(())
}
/// Gets the value of an **AudioUnit** property.
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **au**: The AudioUnit instance.
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
pub fn get_property<T>(
au: sys::AudioUnit,
id: u32,
scope: Scope,
elem: Element,
) -> Result<T, Error> {
let scope = scope as c_uint;
let elem = elem as c_uint;
let mut size = ::std::mem::size_of::<T>() as u32;
unsafe {
let mut data_uninit = ::std::mem::MaybeUninit::<T>::uninit();
let data_ptr = data_uninit.as_mut_ptr() as *mut _ as *mut c_void;
let size_ptr = &mut size as *mut _;
try_os_status!(sys::AudioUnitGetProperty(
au, id, scope, elem, data_ptr, size_ptr
));
let data: T = data_uninit.assume_init();
Ok(data)
}
}
/// Gets the value of a specified audio session property.
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **id**: The identifier of the property.
#[cfg(target_os = "ios")]
pub fn audio_session_get_property<T>(id: u32) -> Result<T, Error> {
let mut size = ::std::mem::size_of::<T>() as u32;
unsafe {
let mut data_uninit = ::std::mem::MaybeUninit::<T>::uninit();
let data_ptr = data_uninit.as_mut_ptr() as *mut _ as *mut c_void;
let size_ptr = &mut size as *mut _;
try_os_status!(sys::AudioSessionGetProperty(id, size_ptr, data_ptr));
let data: T = data_uninit.assume_init();
Ok(data)
}
} | pub use self::audio_format::AudioFormat;
pub use self::sample_format::{Sample, SampleFormat};
pub use self::stream_format::StreamFormat;
pub use self::types::{ | random_line_split |
mod.rs | //! This module is an attempt to provide a friendly, rust-esque interface to Apple's Audio Unit API.
//!
//! Learn more about the Audio Unit API [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40003278-CH1-SW2)
//! and [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html).
//!
//! TODO: The following are `kAudioUnitSubType`s (along with their const u32) generated by
//! rust-bindgen that we could not find any documentation on:
//!
//! - MIDISynth = 1836284270,
//! - RoundTripAAC = 1918984547,
//! - SpatialMixer = 862217581,
//! - SphericalHeadPanner = 1936746610,
//! - VectorPanner = 1986158963,
//! - SoundFieldPanner = 1634558569,
//! - HRTFPanner = 1752331366,
//! - NetReceive = 1852990326,
//!
//! If you can find documentation on these, please feel free to submit an issue or PR with the
//! fixes!
use crate::error::Error;
use std::mem;
use std::os::raw::{c_uint, c_void};
use std::ptr;
use sys;
pub use self::audio_format::AudioFormat;
pub use self::sample_format::{Sample, SampleFormat};
pub use self::stream_format::StreamFormat;
pub use self::types::{
EffectType, FormatConverterType, GeneratorType, IOType, MixerType, MusicDeviceType, Type,
};
#[cfg(target_os = "macos")]
pub mod macos_helpers;
pub mod audio_format;
pub mod render_callback;
pub mod sample_format;
pub mod stream_format;
pub mod types;
/// The input and output **Scope**s.
///
/// More info [here](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnitPropertiesReference/index.html#//apple_ref/doc/constant_group/Audio_Unit_Scopes)
/// and [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html).
#[derive(Copy, Clone, Debug)]
pub enum Scope {
Global = 0,
Input = 1,
Output = 2,
Group = 3,
Part = 4,
Note = 5,
Layer = 6,
LayerItem = 7,
}
/// Represents the **Input** and **Output** **Element**s.
///
/// These are used when specifying which **Element** we're setting the properties of.
#[derive(Copy, Clone, Debug)]
pub enum Element {
Output = 0,
Input = 1,
}
/// A rust representation of the sys::AudioUnit, including a pointer to the current rendering callback.
///
/// Find the original Audio Unit Programming Guide [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html).
pub struct AudioUnit {
instance: sys::AudioUnit,
maybe_render_callback: Option<*mut render_callback::InputProcFnWrapper>,
maybe_input_callback: Option<InputCallback>,
}
struct | {
// The audio buffer list to which input data is rendered.
buffer_list: *mut sys::AudioBufferList,
callback: *mut render_callback::InputProcFnWrapper,
}
macro_rules! try_os_status {
($expr:expr) => {
Error::from_os_status($expr)?
};
}
impl AudioUnit {
/// Construct a new AudioUnit with any type that may be automatically converted into
/// [**Type**](./enum.Type).
///
/// Here is a list of compatible types:
///
/// - [**Type**](./types/enum.Type)
/// - [**IOType**](./types/enum.IOType)
/// - [**MusicDeviceType**](./types/enum.MusicDeviceType)
/// - [**GeneratorType**](./types/enum.GeneratorType)
/// - [**FormatConverterType**](./types/enum.FormatConverterType)
/// - [**EffectType**](./types/enum.EffectType)
/// - [**MixerType**](./types/enum.MixerType)
///
/// To construct the **AudioUnit** with some component flags, see
/// [**AudioUnit::new_with_flags**](./struct.AudioUnit#method.new_with_flags).
///
/// Note: the `AudioUnit` is constructed with the `kAudioUnitManufacturer_Apple` Manufacturer
/// Identifier, as this is the only Audio Unit Manufacturer Identifier documented by Apple in
/// the AudioUnit reference (see [here](https://developer.apple.com/library/prerelease/mac/documentation/AudioUnit/Reference/AUComponentServicesReference/index.html#//apple_ref/doc/constant_group/Audio_Unit_Manufacturer_Identifier)).
pub fn new<T>(ty: T) -> Result<AudioUnit, Error>
where
T: Into<Type>,
{
AudioUnit::new_with_flags(ty, 0, 0)
}
/// The same as [**AudioUnit::new**](./struct.AudioUnit#method.new) but with the given
/// component flags and mask.
pub fn new_with_flags<T>(ty: T, flags: u32, mask: u32) -> Result<AudioUnit, Error>
where
T: Into<Type>,
{
const MANUFACTURER_IDENTIFIER: u32 = sys::kAudioUnitManufacturer_Apple;
let au_type: Type = ty.into();
let sub_type_u32 = match au_type.as_subtype_u32() {
Some(u) => u,
None => return Err(Error::NoKnownSubtype),
};
// A description of the audio unit we desire.
let desc = sys::AudioComponentDescription {
componentType: au_type.as_u32() as c_uint,
componentSubType: sub_type_u32 as c_uint,
componentManufacturer: MANUFACTURER_IDENTIFIER,
componentFlags: flags,
componentFlagsMask: mask,
};
unsafe {
// Find the default audio unit for the description.
//
// From the "Audio Unit Hosting Guide for iOS":
//
// Passing NULL to the first parameter of AudioComponentFindNext tells this function to
// find the first system audio unit matching the description, using a system-defined
// ordering. If you instead pass a previously found audio unit reference in this
// parameter, the function locates the next audio unit matching the description.
let component = sys::AudioComponentFindNext(ptr::null_mut(), &desc as *const _);
if component.is_null() {
return Err(Error::NoMatchingDefaultAudioUnitFound);
}
// Create an instance of the default audio unit using the component.
let mut instance_uninit = mem::MaybeUninit::<sys::AudioUnit>::uninit();
try_os_status!(sys::AudioComponentInstanceNew(
component,
instance_uninit.as_mut_ptr() as *mut sys::AudioUnit
));
let instance: sys::AudioUnit = instance_uninit.assume_init();
// Initialise the audio unit!
try_os_status!(sys::AudioUnitInitialize(instance));
Ok(AudioUnit {
instance,
maybe_render_callback: None,
maybe_input_callback: None,
})
}
}
/// On successful initialization, the audio formats for input and output are valid
/// and the audio unit is ready to render. During initialization, an audio unit
/// allocates memory according to the maximum number of audio frames it can produce
/// in response to a single render call.
///
/// Usually, the state of an audio unit (such as its I/O formats and memory allocations)
/// cannot be changed while an audio unit is initialized.
pub fn initialize(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioUnitInitialize(self.instance));
}
Ok(())
}
/// Before you change an initialize audio unit’s processing characteristics,
/// such as its input or output audio data format or its sample rate, you must
/// first uninitialize it. Calling this function deallocates the audio unit’s resources.
///
/// After calling this function, you can reconfigure the audio unit and then call
/// AudioUnitInitialize to reinitialize it.
pub fn uninitialize(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioUnitUninitialize(self.instance));
}
Ok(())
}
/// Sets the value for some property of the **AudioUnit**.
///
/// To clear an audio unit property value, set the data paramater with `None::<()>`.
///
/// Clearing properties only works for those properties that do not have a default value.
///
/// For more on "properties" see [the reference](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnitPropertiesReference/index.html#//apple_ref/doc/uid/TP40007288).
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
/// - **maybe_data**: The value that you want to apply to the property.
pub fn set_property<T>(
&mut self,
id: u32,
scope: Scope,
elem: Element,
maybe_data: Option<&T>,
) -> Result<(), Error> {
set_property(self.instance, id, scope, elem, maybe_data)
}
/// Gets the value of an **AudioUnit** property.
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
pub fn get_property<T>(&self, id: u32, scope: Scope, elem: Element) -> Result<T, Error> {
get_property(self.instance, id, scope, elem)
}
/// Starts an I/O **AudioUnit**, which in turn starts the audio unit processing graph that it is
/// connected to.
///
/// **Available** in OS X v10.0 and later.
pub fn start(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioOutputUnitStart(self.instance));
}
Ok(())
}
/// Stops an I/O **AudioUnit**, which in turn stops the audio unit processing graph that it is
/// connected to.
///
/// **Available** in OS X v10.0 and later.
pub fn stop(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioOutputUnitStop(self.instance));
}
Ok(())
}
/// Set the **AudioUnit**'s sample rate.
///
/// **Available** in iOS 2.0 and later.
pub fn set_sample_rate(&mut self, sample_rate: f64) -> Result<(), Error> {
let id = sys::kAudioUnitProperty_SampleRate;
self.set_property(id, Scope::Input, Element::Output, Some(&sample_rate))
}
/// Get the **AudioUnit**'s sample rate.
pub fn sample_rate(&self) -> Result<f64, Error> {
let id = sys::kAudioUnitProperty_SampleRate;
self.get_property(id, Scope::Input, Element::Output)
}
/// Sets the current **StreamFormat** for the AudioUnit.
///
/// Core Audio uses slightly different defaults depending on the platform.
///
/// From the Core Audio Overview:
///
/// > The canonical formats in Core Audio are as follows:
/// >
/// > - iOS input and output: Linear PCM with 16-bit integer samples.
/// > - iOS audio units and other audio processing: Noninterleaved linear PCM with 8.24-bit
/// fixed-point samples
/// > - Mac input and output: Linear PCM with 32-bit floating point samples.
/// > - Mac audio units and other audio processing: Noninterleaved linear PCM with 32-bit
/// floating-point
pub fn set_stream_format(
&mut self,
stream_format: StreamFormat,
scope: Scope,
) -> Result<(), Error> {
let id = sys::kAudioUnitProperty_StreamFormat;
let asbd = stream_format.to_asbd();
self.set_property(id, scope, Element::Output, Some(&asbd))
}
/// Return the current Stream Format for the AudioUnit.
pub fn stream_format(&self, scope: Scope) -> Result<StreamFormat, Error> {
let id = sys::kAudioUnitProperty_StreamFormat;
let asbd = self.get_property(id, scope, Element::Output)?;
StreamFormat::from_asbd(asbd)
}
/// Return the current output Stream Format for the AudioUnit.
pub fn output_stream_format(&self) -> Result<StreamFormat, Error> {
self.stream_format(Scope::Output)
}
/// Return the current input Stream Format for the AudioUnit.
pub fn input_stream_format(&self) -> Result<StreamFormat, Error> {
self.stream_format(Scope::Input)
}
}
unsafe impl Send for AudioUnit {}
impl Drop for AudioUnit {
fn drop(&mut self) {
unsafe {
use crate::error;
// We don't want to panic in `drop`, so we'll ignore returned errors.
//
// A user should explicitly terminate the `AudioUnit` if they want to handle errors (we
// still need to provide a way to actually do that).
self.stop().ok();
error::Error::from_os_status(sys::AudioUnitUninitialize(self.instance)).ok();
self.free_render_callback();
self.free_input_callback();
error::Error::from_os_status(sys::AudioComponentInstanceDispose(self.instance)).ok();
}
}
}
/// Sets the value for some property of the **AudioUnit**.
///
/// To clear an audio unit property value, set the data paramater with `None::<()>`.
///
/// Clearing properties only works for those properties that do not have a default value.
///
/// For more on "properties" see [the reference](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnitPropertiesReference/index.html#//apple_ref/doc/uid/TP40007288).
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **au**: The AudioUnit instance.
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
/// - **maybe_data**: The value that you want to apply to the property.
pub fn set_property<T>(
au: sys::AudioUnit,
id: u32,
scope: Scope,
elem: Element,
maybe_data: Option<&T>,
) -> Result<(), Error> {
let (data_ptr, size) = maybe_data
.map(|data| {
let ptr = data as *const _ as *const c_void;
let size = ::std::mem::size_of::<T>() as u32;
(ptr, size)
})
.unwrap_or_else(|| (::std::ptr::null(), 0));
let scope = scope as c_uint;
let elem = elem as c_uint;
unsafe {
try_os_status!(sys::AudioUnitSetProperty(
au, id, scope, elem, data_ptr, size
))
}
Ok(())
}
/// Gets the value of an **AudioUnit** property.
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **au**: The AudioUnit instance.
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
pub fn get_property<T>(
au: sys::AudioUnit,
id: u32,
scope: Scope,
elem: Element,
) -> Result<T, Error> {
let scope = scope as c_uint;
let elem = elem as c_uint;
let mut size = ::std::mem::size_of::<T>() as u32;
unsafe {
let mut data_uninit = ::std::mem::MaybeUninit::<T>::uninit();
let data_ptr = data_uninit.as_mut_ptr() as *mut _ as *mut c_void;
let size_ptr = &mut size as *mut _;
try_os_status!(sys::AudioUnitGetProperty(
au, id, scope, elem, data_ptr, size_ptr
));
let data: T = data_uninit.assume_init();
Ok(data)
}
}
/// Gets the value of a specified audio session property.
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **id**: The identifier of the property.
#[cfg(target_os = "ios")]
pub fn audio_session_get_property<T>(id: u32) -> Result<T, Error> {
let mut size = ::std::mem::size_of::<T>() as u32;
unsafe {
let mut data_uninit = ::std::mem::MaybeUninit::<T>::uninit();
let data_ptr = data_uninit.as_mut_ptr() as *mut _ as *mut c_void;
let size_ptr = &mut size as *mut _;
try_os_status!(sys::AudioSessionGetProperty(id, size_ptr, data_ptr));
let data: T = data_uninit.assume_init();
Ok(data)
}
}
| InputCallback | identifier_name |
mod.rs | //! This module is an attempt to provide a friendly, rust-esque interface to Apple's Audio Unit API.
//!
//! Learn more about the Audio Unit API [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40003278-CH1-SW2)
//! and [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html).
//!
//! TODO: The following are `kAudioUnitSubType`s (along with their const u32) generated by
//! rust-bindgen that we could not find any documentation on:
//!
//! - MIDISynth = 1836284270,
//! - RoundTripAAC = 1918984547,
//! - SpatialMixer = 862217581,
//! - SphericalHeadPanner = 1936746610,
//! - VectorPanner = 1986158963,
//! - SoundFieldPanner = 1634558569,
//! - HRTFPanner = 1752331366,
//! - NetReceive = 1852990326,
//!
//! If you can find documentation on these, please feel free to submit an issue or PR with the
//! fixes!
use crate::error::Error;
use std::mem;
use std::os::raw::{c_uint, c_void};
use std::ptr;
use sys;
pub use self::audio_format::AudioFormat;
pub use self::sample_format::{Sample, SampleFormat};
pub use self::stream_format::StreamFormat;
pub use self::types::{
EffectType, FormatConverterType, GeneratorType, IOType, MixerType, MusicDeviceType, Type,
};
#[cfg(target_os = "macos")]
pub mod macos_helpers;
pub mod audio_format;
pub mod render_callback;
pub mod sample_format;
pub mod stream_format;
pub mod types;
/// The input and output **Scope**s.
///
/// More info [here](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnitPropertiesReference/index.html#//apple_ref/doc/constant_group/Audio_Unit_Scopes)
/// and [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html).
#[derive(Copy, Clone, Debug)]
pub enum Scope {
Global = 0,
Input = 1,
Output = 2,
Group = 3,
Part = 4,
Note = 5,
Layer = 6,
LayerItem = 7,
}
/// Represents the **Input** and **Output** **Element**s.
///
/// These are used when specifying which **Element** we're setting the properties of.
#[derive(Copy, Clone, Debug)]
pub enum Element {
Output = 0,
Input = 1,
}
/// A rust representation of the sys::AudioUnit, including a pointer to the current rendering callback.
///
/// Find the original Audio Unit Programming Guide [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/TheAudioUnit/TheAudioUnit.html).
pub struct AudioUnit {
instance: sys::AudioUnit,
maybe_render_callback: Option<*mut render_callback::InputProcFnWrapper>,
maybe_input_callback: Option<InputCallback>,
}
struct InputCallback {
// The audio buffer list to which input data is rendered.
buffer_list: *mut sys::AudioBufferList,
callback: *mut render_callback::InputProcFnWrapper,
}
macro_rules! try_os_status {
($expr:expr) => {
Error::from_os_status($expr)?
};
}
impl AudioUnit {
/// Construct a new AudioUnit with any type that may be automatically converted into
/// [**Type**](./enum.Type).
///
/// Here is a list of compatible types:
///
/// - [**Type**](./types/enum.Type)
/// - [**IOType**](./types/enum.IOType)
/// - [**MusicDeviceType**](./types/enum.MusicDeviceType)
/// - [**GeneratorType**](./types/enum.GeneratorType)
/// - [**FormatConverterType**](./types/enum.FormatConverterType)
/// - [**EffectType**](./types/enum.EffectType)
/// - [**MixerType**](./types/enum.MixerType)
///
/// To construct the **AudioUnit** with some component flags, see
/// [**AudioUnit::new_with_flags**](./struct.AudioUnit#method.new_with_flags).
///
/// Note: the `AudioUnit` is constructed with the `kAudioUnitManufacturer_Apple` Manufacturer
/// Identifier, as this is the only Audio Unit Manufacturer Identifier documented by Apple in
/// the AudioUnit reference (see [here](https://developer.apple.com/library/prerelease/mac/documentation/AudioUnit/Reference/AUComponentServicesReference/index.html#//apple_ref/doc/constant_group/Audio_Unit_Manufacturer_Identifier)).
pub fn new<T>(ty: T) -> Result<AudioUnit, Error>
where
T: Into<Type>,
{
AudioUnit::new_with_flags(ty, 0, 0)
}
/// The same as [**AudioUnit::new**](./struct.AudioUnit#method.new) but with the given
/// component flags and mask.
pub fn new_with_flags<T>(ty: T, flags: u32, mask: u32) -> Result<AudioUnit, Error>
where
T: Into<Type>,
{
const MANUFACTURER_IDENTIFIER: u32 = sys::kAudioUnitManufacturer_Apple;
let au_type: Type = ty.into();
let sub_type_u32 = match au_type.as_subtype_u32() {
Some(u) => u,
None => return Err(Error::NoKnownSubtype),
};
// A description of the audio unit we desire.
let desc = sys::AudioComponentDescription {
componentType: au_type.as_u32() as c_uint,
componentSubType: sub_type_u32 as c_uint,
componentManufacturer: MANUFACTURER_IDENTIFIER,
componentFlags: flags,
componentFlagsMask: mask,
};
unsafe {
// Find the default audio unit for the description.
//
// From the "Audio Unit Hosting Guide for iOS":
//
// Passing NULL to the first parameter of AudioComponentFindNext tells this function to
// find the first system audio unit matching the description, using a system-defined
// ordering. If you instead pass a previously found audio unit reference in this
// parameter, the function locates the next audio unit matching the description.
let component = sys::AudioComponentFindNext(ptr::null_mut(), &desc as *const _);
if component.is_null() {
return Err(Error::NoMatchingDefaultAudioUnitFound);
}
// Create an instance of the default audio unit using the component.
let mut instance_uninit = mem::MaybeUninit::<sys::AudioUnit>::uninit();
try_os_status!(sys::AudioComponentInstanceNew(
component,
instance_uninit.as_mut_ptr() as *mut sys::AudioUnit
));
let instance: sys::AudioUnit = instance_uninit.assume_init();
// Initialise the audio unit!
try_os_status!(sys::AudioUnitInitialize(instance));
Ok(AudioUnit {
instance,
maybe_render_callback: None,
maybe_input_callback: None,
})
}
}
/// On successful initialization, the audio formats for input and output are valid
/// and the audio unit is ready to render. During initialization, an audio unit
/// allocates memory according to the maximum number of audio frames it can produce
/// in response to a single render call.
///
/// Usually, the state of an audio unit (such as its I/O formats and memory allocations)
/// cannot be changed while an audio unit is initialized.
pub fn initialize(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioUnitInitialize(self.instance));
}
Ok(())
}
/// Before you change an initialize audio unit’s processing characteristics,
/// such as its input or output audio data format or its sample rate, you must
/// first uninitialize it. Calling this function deallocates the audio unit’s resources.
///
/// After calling this function, you can reconfigure the audio unit and then call
/// AudioUnitInitialize to reinitialize it.
pub fn uninitialize(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioUnitUninitialize(self.instance));
}
Ok(())
}
/// Sets the value for some property of the **AudioUnit**.
///
/// To clear an audio unit property value, set the data paramater with `None::<()>`.
///
/// Clearing properties only works for those properties that do not have a default value.
///
/// For more on "properties" see [the reference](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnitPropertiesReference/index.html#//apple_ref/doc/uid/TP40007288).
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
/// - **maybe_data**: The value that you want to apply to the property.
pub fn set_property<T>(
&mut self,
id: u32,
scope: Scope,
elem: Element,
maybe_data: Option<&T>,
) -> Result<(), Error> {
set_property(self.instance, id, scope, elem, maybe_data)
}
/// Gets the value of an **AudioUnit** property.
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
pub fn get_property<T>(&self, id: u32, scope: Scope, elem: Element) -> Result<T, Error> {
get_property(self.instance, id, scope, elem)
}
/// Starts an I/O **AudioUnit**, which in turn starts the audio unit processing graph that it is
/// connected to.
///
/// **Available** in OS X v10.0 and later.
pub fn start(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioOutputUnitStart(self.instance));
}
Ok(())
}
/// Stops an I/O **AudioUnit**, which in turn stops the audio unit processing graph that it is
/// connected to.
///
/// **Available** in OS X v10.0 and later.
pub fn stop(&mut self) -> Result<(), Error> {
unsafe {
try_os_status!(sys::AudioOutputUnitStop(self.instance));
}
Ok(())
}
/// Set the **AudioUnit**'s sample rate.
///
/// **Available** in iOS 2.0 and later.
pub fn set_sample_rate(&mut self, sample_rate: f64) -> Result<(), Error> {
let id = sys::kAudioUnitProperty_SampleRate;
self.set_property(id, Scope::Input, Element::Output, Some(&sample_rate))
}
/// Get the **AudioUnit**'s sample rate.
pub fn sample_rate(&self) -> Result<f64, Error> {
let id = sys::kAudioUnitProperty_SampleRate;
self.get_property(id, Scope::Input, Element::Output)
}
/// Sets the current **StreamFormat** for the AudioUnit.
///
/// Core Audio uses slightly different defaults depending on the platform.
///
/// From the Core Audio Overview:
///
/// > The canonical formats in Core Audio are as follows:
/// >
/// > - iOS input and output: Linear PCM with 16-bit integer samples.
/// > - iOS audio units and other audio processing: Noninterleaved linear PCM with 8.24-bit
/// fixed-point samples
/// > - Mac input and output: Linear PCM with 32-bit floating point samples.
/// > - Mac audio units and other audio processing: Noninterleaved linear PCM with 32-bit
/// floating-point
pub fn set_stream_format(
&mut self,
stream_format: StreamFormat,
scope: Scope,
) -> Result<(), Error> {
let id = sys::kAudioUnitProperty_StreamFormat;
let asbd = stream_format.to_asbd();
self.set_property(id, scope, Element::Output, Some(&asbd))
}
/// Return the current Stream Format for the AudioUnit.
pub fn stream_format(&self, scope: Scope) -> Result<StreamFormat, Error> {
let id = sys::kAudioUnitProperty_StreamFormat;
let asbd = self.get_property(id, scope, Element::Output)?;
StreamFormat::from_asbd(asbd)
}
/// Return the current output Stream Format for the AudioUnit.
pub fn output_stream_format(&self) -> Result<StreamFormat, Error> {
| /// Return the current input Stream Format for the AudioUnit.
pub fn input_stream_format(&self) -> Result<StreamFormat, Error> {
self.stream_format(Scope::Input)
}
}
unsafe impl Send for AudioUnit {}
impl Drop for AudioUnit {
fn drop(&mut self) {
unsafe {
use crate::error;
// We don't want to panic in `drop`, so we'll ignore returned errors.
//
// A user should explicitly terminate the `AudioUnit` if they want to handle errors (we
// still need to provide a way to actually do that).
self.stop().ok();
error::Error::from_os_status(sys::AudioUnitUninitialize(self.instance)).ok();
self.free_render_callback();
self.free_input_callback();
error::Error::from_os_status(sys::AudioComponentInstanceDispose(self.instance)).ok();
}
}
}
/// Sets the value for some property of the **AudioUnit**.
///
/// To clear an audio unit property value, set the data paramater with `None::<()>`.
///
/// Clearing properties only works for those properties that do not have a default value.
///
/// For more on "properties" see [the reference](https://developer.apple.com/library/ios/documentation/AudioUnit/Reference/AudioUnitPropertiesReference/index.html#//apple_ref/doc/uid/TP40007288).
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **au**: The AudioUnit instance.
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
/// - **maybe_data**: The value that you want to apply to the property.
pub fn set_property<T>(
au: sys::AudioUnit,
id: u32,
scope: Scope,
elem: Element,
maybe_data: Option<&T>,
) -> Result<(), Error> {
let (data_ptr, size) = maybe_data
.map(|data| {
let ptr = data as *const _ as *const c_void;
let size = ::std::mem::size_of::<T>() as u32;
(ptr, size)
})
.unwrap_or_else(|| (::std::ptr::null(), 0));
let scope = scope as c_uint;
let elem = elem as c_uint;
unsafe {
try_os_status!(sys::AudioUnitSetProperty(
au, id, scope, elem, data_ptr, size
))
}
Ok(())
}
/// Gets the value of an **AudioUnit** property.
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **au**: The AudioUnit instance.
/// - **id**: The identifier of the property.
/// - **scope**: The audio unit scope for the property.
/// - **elem**: The audio unit element for the property.
pub fn get_property<T>(
au: sys::AudioUnit,
id: u32,
scope: Scope,
elem: Element,
) -> Result<T, Error> {
let scope = scope as c_uint;
let elem = elem as c_uint;
let mut size = ::std::mem::size_of::<T>() as u32;
unsafe {
let mut data_uninit = ::std::mem::MaybeUninit::<T>::uninit();
let data_ptr = data_uninit.as_mut_ptr() as *mut _ as *mut c_void;
let size_ptr = &mut size as *mut _;
try_os_status!(sys::AudioUnitGetProperty(
au, id, scope, elem, data_ptr, size_ptr
));
let data: T = data_uninit.assume_init();
Ok(data)
}
}
/// Gets the value of a specified audio session property.
///
/// **Available** in iOS 2.0 and later.
///
/// Parameters
/// ----------
///
/// - **id**: The identifier of the property.
#[cfg(target_os = "ios")]
pub fn audio_session_get_property<T>(id: u32) -> Result<T, Error> {
let mut size = ::std::mem::size_of::<T>() as u32;
unsafe {
let mut data_uninit = ::std::mem::MaybeUninit::<T>::uninit();
let data_ptr = data_uninit.as_mut_ptr() as *mut _ as *mut c_void;
let size_ptr = &mut size as *mut _;
try_os_status!(sys::AudioSessionGetProperty(id, size_ptr, data_ptr));
let data: T = data_uninit.assume_init();
Ok(data)
}
}
| self.stream_format(Scope::Output)
}
| identifier_body |
diagnostics.rs | #![warn(
clippy::print_stdout,
clippy::unimplemented,
clippy::doc_markdown,
clippy::items_after_statements,
clippy::match_same_arms,
clippy::similar_names,
clippy::single_match_else,
clippy::use_self,
clippy::use_debug
)]
//! The diagnostics object controls the output of warnings and errors generated
//! by the compiler during the lexing, parsing and semantic analysis phases.
//! It also tracks the number of warnings and errors generated for flow control.
//!
//! This implementation is NOT thread-safe. Messages from different threads may
//! be interleaved.
use asciifile::{MaybeSpanned, Span, Spanned};
use failure::Error;
use std::{ascii::escape_default, cell::RefCell, collections::HashMap, fmt::Display};
use termcolor::{Color, WriteColor};
use utils::color::ColorOutput;
pub mod lint;
pub fn u8_to_printable_representation(byte: u8) -> String {
let bytes = escape_default(byte).collect::<Vec<u8>>();
let rep = unsafe { std::str::from_utf8_unchecked(&bytes) };
rep.to_owned()
}
/// This abstraction allows us to call the diagnostics API with pretty
/// much everything.
///
/// The following examples are all equivalent and will print a warning
/// without a source code snippet below the message:
///
/// ```rust,ignore
/// context.diagnostics.warning(&"Something went wrong");
/// context
/// .diagnostics
/// .warning(&WithoutSpan("Something went wrong"));
/// ```
///
/// The following examples will print a message with a source code
/// snippet. Note that all errors generated by the compiler are
/// a `Spanned<_, Fail>` and can therefore be directly passed to
/// the diagnostics API.
///
/// ```rust,ignore
/// // `lexer_error` is the `Err` returned by `Lexer::next`
/// context.diagnostics.error(&lexer_error);
/// // `span` is some `asciifile::Span`
/// context.diagnostics.error({
/// span: span,
/// data: "something went wrong"
/// });
/// ```
pub trait Printable<'a, 'b> {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display>;
}
// TODO: implementing on `str` (which is what you would like to do, to
// support calls with warning("aa") instead of warning(&"aa").
impl<'a, 'b> Printable<'a, 'b> for &'b str {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
MaybeSpanned::WithoutSpan(self)
}
}
impl<'a, 'b, T: Display + 'b> Printable<'a, 'b> for Spanned<'a, T> {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
MaybeSpanned::WithSpan(Spanned {
span: self.span,
data: &self.data,
})
}
}
impl<'a, 'b, T: Display + 'b> Printable<'a, 'b> for MaybeSpanned<'a, T> {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
match self {
MaybeSpanned::WithSpan(ref spanned) => MaybeSpanned::WithSpan(Spanned {
span: spanned.span,
data: &spanned.data,
}),
MaybeSpanned::WithoutSpan(ref data) => MaybeSpanned::WithoutSpan(data),
}
}
}
/// Width of tabs in error and warning messages
const TAB_WIDTH: usize = 4;
/// Color used for rendering line numbers, escape sequences
/// and others...
const HIGHLIGHT_COLOR: Option<Color> = Some(Color::Cyan);
// TODO reimplement line truncation
/// Instead of writing errors, warnings and lints generated in the different
/// compiler stages directly to stdout, they are collected in this object.
///
/// This has several advantages:
/// - the output level can be adapted by users.
/// - we have a single source responsible for formatting compiler messages.
pub struct Diagnostics {
message_count: RefCell<HashMap<MessageLevel, usize>>,
writer: RefCell<Box<dyn WriteColor>>,
}
impl Diagnostics {
pub fn new(writer: Box<dyn WriteColor>) -> Self {
Self {
writer: RefCell::new(writer),
message_count: RefCell::new(HashMap::new()),
}
}
/// True when an error message was emitted, false
/// if only warnings were emitted.
pub fn errored(&self) -> bool {
self.message_count
.borrow()
.get(&MessageLevel::Error)
.is_some()
}
pub fn count(&self, level: MessageLevel) -> usize {
self.message_count
.borrow()
.get(&level)
.cloned()
.unwrap_or(0)
}
pub fn write_statistics(&self) {
let mut writer = self.writer.borrow_mut();
let mut output = ColorOutput::new(&mut **writer);
output.set_bold(true);
if self.errored() {
output.set_color(MessageLevel::Error.color());
writeln!(
output.writer(),
"Compilation aborted due to {}",
match self.count(MessageLevel::Error) {
1 => "an error".to_string(),
n => format!("{} errors", n),
}
)
.ok();
} else {
output.set_color(Some(Color::Green));
writeln!(
output.writer(),
"Compilation finished successfully {}",
match self.count(MessageLevel::Warning) {
0 => "without warnings".to_string(),
1 => "with a warning".to_string(),
n => format!("with {} warnings", n),
}
)
.ok();
}
}
/// Generate an error or a warning that is printed to the
/// writer given in the `new` constructor. Most of the time
/// this will be stderr.
pub fn emit(&self, level: MessageLevel, kind: MaybeSpanned<'_, &dyn Display>) {
self.increment_level_count(level);
let mut writer = self.writer.borrow_mut();
let msg = Message { level, kind };
// `ok()` surpresses io error
msg.write(&mut **writer).ok();
}
#[allow(dead_code)]
pub fn warning<'a, 'b, T: Printable<'a, 'b> +?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Warning, kind.as_maybe_spanned())
}
#[allow(dead_code)]
pub fn error<'a, 'b, T: Printable<'a, 'b> +?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Error, kind.as_maybe_spanned())
}
#[allow(dead_code)]
pub fn info<'a, 'b, T: Printable<'a, 'b> +?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Info, kind.as_maybe_spanned())
}
fn increment_level_count(&self, level: MessageLevel) {
let mut message_count = self.message_count.borrow_mut();
let counter = message_count.entry(level).or_insert(0);
*counter += 1;
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum MessageLevel {
Error,
Warning,
Info,
Allow,
}
impl MessageLevel {
fn color(self) -> Option<Color> {
// Don't be confused by the return type.
// `None` means default color in the colorterm
// crate!
match self {
MessageLevel::Error => Some(Color::Red),
MessageLevel::Warning => Some(Color::Yellow),
MessageLevel::Info => Some(Color::Cyan),
MessageLevel::Allow => None,
}
}
fn name(&self) -> &str {
match self {
MessageLevel::Error => "error",
MessageLevel::Warning => "warning",
MessageLevel::Info => "info",
MessageLevel::Allow => "allow",
}
}
pub fn from_string(level: &str) -> Option<Self> {
match level {
"allow" => Some(MessageLevel::Allow),
"info" => Some(MessageLevel::Info),
"warning" => Some(MessageLevel::Warning),
"error" => Some(MessageLevel::Error),
_ => None,
}
}
}
pub struct Message<'file,'msg> {
pub level: MessageLevel,
pub kind: MaybeSpanned<'file, &'msg dyn Display>,
}
impl<'file,'msg> Message<'file,'msg> {
pub fn write(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
match &self.kind {
MaybeSpanned::WithoutSpan(_) => {
self.write_description(writer)?;
}
MaybeSpanned::WithSpan(spanned) => {
self.write_description(writer)?;
self.write_code(writer, &spanned.span)?;
}
}
writeln!(writer)?;
Ok(())
}
fn write_description(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
output.set_color(self.level.color());
output.set_bold(true);
write!(output.writer(), "{}: ", self.level.name())?;
output.set_color(None);
writeln!(output.writer(), "{}", *self.kind)?;
Ok(())
}
fn write_code(&self, writer: &mut dyn WriteColor, error: &Span<'_>) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
let num_fmt = LineNumberFormatter::new(error);
num_fmt.spaces(output.writer())?;
writeln!(output.writer())?;
for (line_number, line) in error.lines().numbered() {
let line_fmt = LineFormatter::new(&line);
num_fmt.number(output.writer(), line_number)?;
line_fmt.render(output.writer())?;
// currently, the span will always exist since we take the line from the error
// but future versions may print a line below and above for context that
// is not part of the error
if let Some(faulty_part_of_line) = Span::intersect(error, &line) {
// TODO: implement this without the following 3 assumptions:
// - start_pos - end_pos >= 0, guranteed by data structure invariant of Span
// - start_term_pos - end_term_pos >= 0, guranteed by monotony of columns (a
// Position.char() can only be rendered to 0 or more terminal characters) | let (start_term_pos, end_term_pos) =
line_fmt.actual_columns(&faulty_part_of_line).unwrap();
let term_width = end_term_pos - start_term_pos;
num_fmt.spaces(output.writer())?;
{
let mut output = ColorOutput::new(output.writer());
output.set_color(self.level.color());
output.set_bold(true);
writeln!(
output.writer(),
"{spaces}{underline}",
spaces = " ".repeat(start_term_pos),
underline = "^".repeat(term_width)
)?;
}
}
}
Ok(())
}
}
/// Helper that prints a range of numbers with the correct
/// amount of padding
struct LineNumberFormatter {
width: usize,
}
impl LineNumberFormatter {
pub fn new(span: &Span<'_>) -> Self {
Self {
width: span.end_position().line_number().to_string().len(),
}
}
pub fn spaces(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
output.set_color(HIGHLIGHT_COLOR);
output.set_bold(true);
write!(output.writer(), " {} | ", " ".repeat(self.width))?;
Ok(())
}
pub fn number(&self, writer: &mut dyn WriteColor, line_number: usize) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
output.set_color(HIGHLIGHT_COLOR);
output.set_bold(true);
let padded_number = pad_left(&line_number.to_string(), self.width);
write!(output.writer(), " {} | ", padded_number)?;
Ok(())
}
}
pub fn pad_left(s: &str, pad: usize) -> String {
pad_left_with_char(s, pad,'')
}
pub fn pad_left_with_char(s: &str, pad: usize, chr: char) -> String {
format!(
"{padding}{string}",
padding = chr
.to_string()
.repeat(pad.checked_sub(s.len()).unwrap_or(0)),
string = s
)
}
/// Writes a user-supplied input line in a safe manner by replacing
/// control-characters with escape sequences.
struct LineFormatter<'span, 'file> {
line: &'span Span<'file>,
}
impl<'span, 'file> LineFormatter<'span, 'file> {
fn new(line: &'span Span<'file>) -> Self {
Self { line }
}
fn render(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
// TODO: implement an iterator
let chars = self.line.start_position().iter();
for position in chars {
let (text, color) = self.render_char(position.chr());
output.set_color(color);
write!(output.writer(), "{}", text)?;
if position == self.line.end_position() {
break;
}
}
writeln!(output.writer())?;
Ok(())
}
/// Map terminal columns to `Position` columns. Returns a inclusive
/// lower bound, and an exclusive upper bound.
///
/// Each printed character does not actually take up monospace grid cell.
/// For example a TAB character may be represented by 4 spaces. This
/// function will return the actual number of'monospace grid cells'
/// rendered before the given
/// position.
///
/// Returns `None` if the column is out of bounds.
fn actual_columns(&self, span: &Span<'_>) -> Option<(usize, usize)> {
let lower = self.len_printed_before(span.start_position().column());
let upper = self.len_printed_before(span.end_position().column());
match (lower, upper) {
(Some(lower), Some(upper)) => {
let last_char_width = self.render_char(span.end_position().chr()).0.len();
Some((lower, upper + last_char_width))
}
_ => None,
}
}
fn len_printed_before(&self, col: usize) -> Option<usize> {
// TODO: get rid of this nonsense
// NOTE: it would actually be nice to condition the Position on the Line
// instead of AsciiFile. Thinking of this, we could actually just do
// `AsciiFile::new((span.as_str().as_bytes()))`. Meaning AsciiFile is
// not a file, but a View
// that restricts the
// linked lists in Positions and Spans to a subset of the file.
// TODO: implement an iterator on span, or
// span.to_view().iter()/.to_ascii_file().iter() this method is
// inherintly unsafe
// because we do not have
// a way to restrict
// positions in a type safe manner.
if self.line.len() < col {
return None;
}
let chars = self.line.start_position().iter();
let mut actual_column = 0;
for position in chars {
if position.column() == col {
break;
}
actual_column += self.render_char(position.chr()).0.len();
}
Some(actual_column)
}
fn render_char(&self, chr: char) -> (String, Option<Color>) {
match chr {
'\t' => (" ".repeat(TAB_WIDTH), None),
'\r' | '\n' => ("".to_string(), None),
chr if chr.is_control() => (
format!("{{{}}}", u8_to_printable_representation(chr as u8)),
HIGHLIGHT_COLOR,
),
_ => (chr.to_string(), None),
}
}
}
#[cfg(test)]
#[allow(clippy::print_stdout, clippy::use_debug)]
mod tests {
use super::*;
#[test]
fn test_pad_left() {
let tests = vec![("a", " a"), ("", " "), ("a", "a"), ("", "")];
for (input, expected) in tests {
println!("Testing: {:?} => {:?}", input, expected);
assert_eq!(expected, pad_left(input, expected.len()));
}
// not enough padding does not truncate string
assert_eq!("a", pad_left("a", 0));
}
} | // - unwrap(.): both positions are guranteed to exist in the line since we just
// got them from the faulty line, which is a subset of the whole error line | random_line_split |
diagnostics.rs | #![warn(
clippy::print_stdout,
clippy::unimplemented,
clippy::doc_markdown,
clippy::items_after_statements,
clippy::match_same_arms,
clippy::similar_names,
clippy::single_match_else,
clippy::use_self,
clippy::use_debug
)]
//! The diagnostics object controls the output of warnings and errors generated
//! by the compiler during the lexing, parsing and semantic analysis phases.
//! It also tracks the number of warnings and errors generated for flow control.
//!
//! This implementation is NOT thread-safe. Messages from different threads may
//! be interleaved.
use asciifile::{MaybeSpanned, Span, Spanned};
use failure::Error;
use std::{ascii::escape_default, cell::RefCell, collections::HashMap, fmt::Display};
use termcolor::{Color, WriteColor};
use utils::color::ColorOutput;
pub mod lint;
pub fn u8_to_printable_representation(byte: u8) -> String {
let bytes = escape_default(byte).collect::<Vec<u8>>();
let rep = unsafe { std::str::from_utf8_unchecked(&bytes) };
rep.to_owned()
}
/// This abstraction allows us to call the diagnostics API with pretty
/// much everything.
///
/// The following examples are all equivalent and will print a warning
/// without a source code snippet below the message:
///
/// ```rust,ignore
/// context.diagnostics.warning(&"Something went wrong");
/// context
/// .diagnostics
/// .warning(&WithoutSpan("Something went wrong"));
/// ```
///
/// The following examples will print a message with a source code
/// snippet. Note that all errors generated by the compiler are
/// a `Spanned<_, Fail>` and can therefore be directly passed to
/// the diagnostics API.
///
/// ```rust,ignore
/// // `lexer_error` is the `Err` returned by `Lexer::next`
/// context.diagnostics.error(&lexer_error);
/// // `span` is some `asciifile::Span`
/// context.diagnostics.error({
/// span: span,
/// data: "something went wrong"
/// });
/// ```
pub trait Printable<'a, 'b> {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display>;
}
// TODO: implementing on `str` (which is what you would like to do, to
// support calls with warning("aa") instead of warning(&"aa").
impl<'a, 'b> Printable<'a, 'b> for &'b str {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
MaybeSpanned::WithoutSpan(self)
}
}
impl<'a, 'b, T: Display + 'b> Printable<'a, 'b> for Spanned<'a, T> {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
MaybeSpanned::WithSpan(Spanned {
span: self.span,
data: &self.data,
})
}
}
impl<'a, 'b, T: Display + 'b> Printable<'a, 'b> for MaybeSpanned<'a, T> {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
match self {
MaybeSpanned::WithSpan(ref spanned) => MaybeSpanned::WithSpan(Spanned {
span: spanned.span,
data: &spanned.data,
}),
MaybeSpanned::WithoutSpan(ref data) => MaybeSpanned::WithoutSpan(data),
}
}
}
/// Width of tabs in error and warning messages
const TAB_WIDTH: usize = 4;
/// Color used for rendering line numbers, escape sequences
/// and others...
const HIGHLIGHT_COLOR: Option<Color> = Some(Color::Cyan);
// TODO reimplement line truncation
/// Instead of writing errors, warnings and lints generated in the different
/// compiler stages directly to stdout, they are collected in this object.
///
/// This has several advantages:
/// - the output level can be adapted by users.
/// - we have a single source responsible for formatting compiler messages.
pub struct Diagnostics {
message_count: RefCell<HashMap<MessageLevel, usize>>,
writer: RefCell<Box<dyn WriteColor>>,
}
impl Diagnostics {
pub fn new(writer: Box<dyn WriteColor>) -> Self {
Self {
writer: RefCell::new(writer),
message_count: RefCell::new(HashMap::new()),
}
}
/// True when an error message was emitted, false
/// if only warnings were emitted.
pub fn errored(&self) -> bool {
self.message_count
.borrow()
.get(&MessageLevel::Error)
.is_some()
}
pub fn count(&self, level: MessageLevel) -> usize {
self.message_count
.borrow()
.get(&level)
.cloned()
.unwrap_or(0)
}
pub fn write_statistics(&self) {
let mut writer = self.writer.borrow_mut();
let mut output = ColorOutput::new(&mut **writer);
output.set_bold(true);
if self.errored() {
output.set_color(MessageLevel::Error.color());
writeln!(
output.writer(),
"Compilation aborted due to {}",
match self.count(MessageLevel::Error) {
1 => "an error".to_string(),
n => format!("{} errors", n),
}
)
.ok();
} else {
output.set_color(Some(Color::Green));
writeln!(
output.writer(),
"Compilation finished successfully {}",
match self.count(MessageLevel::Warning) {
0 => "without warnings".to_string(),
1 => "with a warning".to_string(),
n => format!("with {} warnings", n),
}
)
.ok();
}
}
/// Generate an error or a warning that is printed to the
/// writer given in the `new` constructor. Most of the time
/// this will be stderr.
pub fn emit(&self, level: MessageLevel, kind: MaybeSpanned<'_, &dyn Display>) {
self.increment_level_count(level);
let mut writer = self.writer.borrow_mut();
let msg = Message { level, kind };
// `ok()` surpresses io error
msg.write(&mut **writer).ok();
}
#[allow(dead_code)]
pub fn warning<'a, 'b, T: Printable<'a, 'b> +?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Warning, kind.as_maybe_spanned())
}
#[allow(dead_code)]
pub fn error<'a, 'b, T: Printable<'a, 'b> +?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Error, kind.as_maybe_spanned())
}
#[allow(dead_code)]
pub fn info<'a, 'b, T: Printable<'a, 'b> +?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Info, kind.as_maybe_spanned())
}
fn increment_level_count(&self, level: MessageLevel) {
let mut message_count = self.message_count.borrow_mut();
let counter = message_count.entry(level).or_insert(0);
*counter += 1;
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum MessageLevel {
Error,
Warning,
Info,
Allow,
}
impl MessageLevel {
fn color(self) -> Option<Color> {
// Don't be confused by the return type.
// `None` means default color in the colorterm
// crate!
match self {
MessageLevel::Error => Some(Color::Red),
MessageLevel::Warning => Some(Color::Yellow),
MessageLevel::Info => Some(Color::Cyan),
MessageLevel::Allow => None,
}
}
fn name(&self) -> &str {
match self {
MessageLevel::Error => "error",
MessageLevel::Warning => "warning",
MessageLevel::Info => "info",
MessageLevel::Allow => "allow",
}
}
pub fn from_string(level: &str) -> Option<Self> {
match level {
"allow" => Some(MessageLevel::Allow),
"info" => Some(MessageLevel::Info),
"warning" => Some(MessageLevel::Warning),
"error" => Some(MessageLevel::Error),
_ => None,
}
}
}
pub struct Message<'file,'msg> {
pub level: MessageLevel,
pub kind: MaybeSpanned<'file, &'msg dyn Display>,
}
impl<'file,'msg> Message<'file,'msg> {
pub fn write(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
match &self.kind {
MaybeSpanned::WithoutSpan(_) => {
self.write_description(writer)?;
}
MaybeSpanned::WithSpan(spanned) => {
self.write_description(writer)?;
self.write_code(writer, &spanned.span)?;
}
}
writeln!(writer)?;
Ok(())
}
fn write_description(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
output.set_color(self.level.color());
output.set_bold(true);
write!(output.writer(), "{}: ", self.level.name())?;
output.set_color(None);
writeln!(output.writer(), "{}", *self.kind)?;
Ok(())
}
fn write_code(&self, writer: &mut dyn WriteColor, error: &Span<'_>) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
let num_fmt = LineNumberFormatter::new(error);
num_fmt.spaces(output.writer())?;
writeln!(output.writer())?;
for (line_number, line) in error.lines().numbered() {
let line_fmt = LineFormatter::new(&line);
num_fmt.number(output.writer(), line_number)?;
line_fmt.render(output.writer())?;
// currently, the span will always exist since we take the line from the error
// but future versions may print a line below and above for context that
// is not part of the error
if let Some(faulty_part_of_line) = Span::intersect(error, &line) {
// TODO: implement this without the following 3 assumptions:
// - start_pos - end_pos >= 0, guranteed by data structure invariant of Span
// - start_term_pos - end_term_pos >= 0, guranteed by monotony of columns (a
// Position.char() can only be rendered to 0 or more terminal characters)
// - unwrap(.): both positions are guranteed to exist in the line since we just
// got them from the faulty line, which is a subset of the whole error line
let (start_term_pos, end_term_pos) =
line_fmt.actual_columns(&faulty_part_of_line).unwrap();
let term_width = end_term_pos - start_term_pos;
num_fmt.spaces(output.writer())?;
{
let mut output = ColorOutput::new(output.writer());
output.set_color(self.level.color());
output.set_bold(true);
writeln!(
output.writer(),
"{spaces}{underline}",
spaces = " ".repeat(start_term_pos),
underline = "^".repeat(term_width)
)?;
}
}
}
Ok(())
}
}
/// Helper that prints a range of numbers with the correct
/// amount of padding
struct LineNumberFormatter {
width: usize,
}
impl LineNumberFormatter {
pub fn new(span: &Span<'_>) -> Self {
Self {
width: span.end_position().line_number().to_string().len(),
}
}
pub fn spaces(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
output.set_color(HIGHLIGHT_COLOR);
output.set_bold(true);
write!(output.writer(), " {} | ", " ".repeat(self.width))?;
Ok(())
}
pub fn number(&self, writer: &mut dyn WriteColor, line_number: usize) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
output.set_color(HIGHLIGHT_COLOR);
output.set_bold(true);
let padded_number = pad_left(&line_number.to_string(), self.width);
write!(output.writer(), " {} | ", padded_number)?;
Ok(())
}
}
pub fn pad_left(s: &str, pad: usize) -> String {
pad_left_with_char(s, pad,'')
}
pub fn pad_left_with_char(s: &str, pad: usize, chr: char) -> String {
format!(
"{padding}{string}",
padding = chr
.to_string()
.repeat(pad.checked_sub(s.len()).unwrap_or(0)),
string = s
)
}
/// Writes a user-supplied input line in a safe manner by replacing
/// control-characters with escape sequences.
struct LineFormatter<'span, 'file> {
line: &'span Span<'file>,
}
impl<'span, 'file> LineFormatter<'span, 'file> {
fn | (line: &'span Span<'file>) -> Self {
Self { line }
}
fn render(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
// TODO: implement an iterator
let chars = self.line.start_position().iter();
for position in chars {
let (text, color) = self.render_char(position.chr());
output.set_color(color);
write!(output.writer(), "{}", text)?;
if position == self.line.end_position() {
break;
}
}
writeln!(output.writer())?;
Ok(())
}
/// Map terminal columns to `Position` columns. Returns a inclusive
/// lower bound, and an exclusive upper bound.
///
/// Each printed character does not actually take up monospace grid cell.
/// For example a TAB character may be represented by 4 spaces. This
/// function will return the actual number of'monospace grid cells'
/// rendered before the given
/// position.
///
/// Returns `None` if the column is out of bounds.
fn actual_columns(&self, span: &Span<'_>) -> Option<(usize, usize)> {
let lower = self.len_printed_before(span.start_position().column());
let upper = self.len_printed_before(span.end_position().column());
match (lower, upper) {
(Some(lower), Some(upper)) => {
let last_char_width = self.render_char(span.end_position().chr()).0.len();
Some((lower, upper + last_char_width))
}
_ => None,
}
}
fn len_printed_before(&self, col: usize) -> Option<usize> {
// TODO: get rid of this nonsense
// NOTE: it would actually be nice to condition the Position on the Line
// instead of AsciiFile. Thinking of this, we could actually just do
// `AsciiFile::new((span.as_str().as_bytes()))`. Meaning AsciiFile is
// not a file, but a View
// that restricts the
// linked lists in Positions and Spans to a subset of the file.
// TODO: implement an iterator on span, or
// span.to_view().iter()/.to_ascii_file().iter() this method is
// inherintly unsafe
// because we do not have
// a way to restrict
// positions in a type safe manner.
if self.line.len() < col {
return None;
}
let chars = self.line.start_position().iter();
let mut actual_column = 0;
for position in chars {
if position.column() == col {
break;
}
actual_column += self.render_char(position.chr()).0.len();
}
Some(actual_column)
}
fn render_char(&self, chr: char) -> (String, Option<Color>) {
match chr {
'\t' => (" ".repeat(TAB_WIDTH), None),
'\r' | '\n' => ("".to_string(), None),
chr if chr.is_control() => (
format!("{{{}}}", u8_to_printable_representation(chr as u8)),
HIGHLIGHT_COLOR,
),
_ => (chr.to_string(), None),
}
}
}
#[cfg(test)]
#[allow(clippy::print_stdout, clippy::use_debug)]
mod tests {
use super::*;
#[test]
fn test_pad_left() {
let tests = vec![("a", " a"), ("", " "), ("a", "a"), ("", "")];
for (input, expected) in tests {
println!("Testing: {:?} => {:?}", input, expected);
assert_eq!(expected, pad_left(input, expected.len()));
}
// not enough padding does not truncate string
assert_eq!("a", pad_left("a", 0));
}
}
| new | identifier_name |
diagnostics.rs | #![warn(
clippy::print_stdout,
clippy::unimplemented,
clippy::doc_markdown,
clippy::items_after_statements,
clippy::match_same_arms,
clippy::similar_names,
clippy::single_match_else,
clippy::use_self,
clippy::use_debug
)]
//! The diagnostics object controls the output of warnings and errors generated
//! by the compiler during the lexing, parsing and semantic analysis phases.
//! It also tracks the number of warnings and errors generated for flow control.
//!
//! This implementation is NOT thread-safe. Messages from different threads may
//! be interleaved.
use asciifile::{MaybeSpanned, Span, Spanned};
use failure::Error;
use std::{ascii::escape_default, cell::RefCell, collections::HashMap, fmt::Display};
use termcolor::{Color, WriteColor};
use utils::color::ColorOutput;
pub mod lint;
pub fn u8_to_printable_representation(byte: u8) -> String {
let bytes = escape_default(byte).collect::<Vec<u8>>();
let rep = unsafe { std::str::from_utf8_unchecked(&bytes) };
rep.to_owned()
}
/// This abstraction allows us to call the diagnostics API with pretty
/// much everything.
///
/// The following examples are all equivalent and will print a warning
/// without a source code snippet below the message:
///
/// ```rust,ignore
/// context.diagnostics.warning(&"Something went wrong");
/// context
/// .diagnostics
/// .warning(&WithoutSpan("Something went wrong"));
/// ```
///
/// The following examples will print a message with a source code
/// snippet. Note that all errors generated by the compiler are
/// a `Spanned<_, Fail>` and can therefore be directly passed to
/// the diagnostics API.
///
/// ```rust,ignore
/// // `lexer_error` is the `Err` returned by `Lexer::next`
/// context.diagnostics.error(&lexer_error);
/// // `span` is some `asciifile::Span`
/// context.diagnostics.error({
/// span: span,
/// data: "something went wrong"
/// });
/// ```
pub trait Printable<'a, 'b> {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display>;
}
// TODO: implementing on `str` (which is what you would like to do, to
// support calls with warning("aa") instead of warning(&"aa").
impl<'a, 'b> Printable<'a, 'b> for &'b str {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
MaybeSpanned::WithoutSpan(self)
}
}
impl<'a, 'b, T: Display + 'b> Printable<'a, 'b> for Spanned<'a, T> {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
MaybeSpanned::WithSpan(Spanned {
span: self.span,
data: &self.data,
})
}
}
impl<'a, 'b, T: Display + 'b> Printable<'a, 'b> for MaybeSpanned<'a, T> {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
match self {
MaybeSpanned::WithSpan(ref spanned) => MaybeSpanned::WithSpan(Spanned {
span: spanned.span,
data: &spanned.data,
}),
MaybeSpanned::WithoutSpan(ref data) => MaybeSpanned::WithoutSpan(data),
}
}
}
/// Width of tabs in error and warning messages
const TAB_WIDTH: usize = 4;
/// Color used for rendering line numbers, escape sequences
/// and others...
const HIGHLIGHT_COLOR: Option<Color> = Some(Color::Cyan);
// TODO reimplement line truncation
/// Instead of writing errors, warnings and lints generated in the different
/// compiler stages directly to stdout, they are collected in this object.
///
/// This has several advantages:
/// - the output level can be adapted by users.
/// - we have a single source responsible for formatting compiler messages.
pub struct Diagnostics {
message_count: RefCell<HashMap<MessageLevel, usize>>,
writer: RefCell<Box<dyn WriteColor>>,
}
impl Diagnostics {
pub fn new(writer: Box<dyn WriteColor>) -> Self {
Self {
writer: RefCell::new(writer),
message_count: RefCell::new(HashMap::new()),
}
}
/// True when an error message was emitted, false
/// if only warnings were emitted.
pub fn errored(&self) -> bool {
self.message_count
.borrow()
.get(&MessageLevel::Error)
.is_some()
}
pub fn count(&self, level: MessageLevel) -> usize {
self.message_count
.borrow()
.get(&level)
.cloned()
.unwrap_or(0)
}
pub fn write_statistics(&self) {
let mut writer = self.writer.borrow_mut();
let mut output = ColorOutput::new(&mut **writer);
output.set_bold(true);
if self.errored() {
output.set_color(MessageLevel::Error.color());
writeln!(
output.writer(),
"Compilation aborted due to {}",
match self.count(MessageLevel::Error) {
1 => "an error".to_string(),
n => format!("{} errors", n),
}
)
.ok();
} else {
output.set_color(Some(Color::Green));
writeln!(
output.writer(),
"Compilation finished successfully {}",
match self.count(MessageLevel::Warning) {
0 => "without warnings".to_string(),
1 => "with a warning".to_string(),
n => format!("with {} warnings", n),
}
)
.ok();
}
}
/// Generate an error or a warning that is printed to the
/// writer given in the `new` constructor. Most of the time
/// this will be stderr.
pub fn emit(&self, level: MessageLevel, kind: MaybeSpanned<'_, &dyn Display>) {
self.increment_level_count(level);
let mut writer = self.writer.borrow_mut();
let msg = Message { level, kind };
// `ok()` surpresses io error
msg.write(&mut **writer).ok();
}
#[allow(dead_code)]
pub fn warning<'a, 'b, T: Printable<'a, 'b> +?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Warning, kind.as_maybe_spanned())
}
#[allow(dead_code)]
pub fn error<'a, 'b, T: Printable<'a, 'b> +?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Error, kind.as_maybe_spanned())
}
#[allow(dead_code)]
pub fn info<'a, 'b, T: Printable<'a, 'b> +?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Info, kind.as_maybe_spanned())
}
fn increment_level_count(&self, level: MessageLevel) {
let mut message_count = self.message_count.borrow_mut();
let counter = message_count.entry(level).or_insert(0);
*counter += 1;
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum MessageLevel {
Error,
Warning,
Info,
Allow,
}
impl MessageLevel {
fn color(self) -> Option<Color> {
// Don't be confused by the return type.
// `None` means default color in the colorterm
// crate!
match self {
MessageLevel::Error => Some(Color::Red),
MessageLevel::Warning => Some(Color::Yellow),
MessageLevel::Info => Some(Color::Cyan),
MessageLevel::Allow => None,
}
}
fn name(&self) -> &str {
match self {
MessageLevel::Error => "error",
MessageLevel::Warning => "warning",
MessageLevel::Info => "info",
MessageLevel::Allow => "allow",
}
}
pub fn from_string(level: &str) -> Option<Self> {
match level {
"allow" => Some(MessageLevel::Allow),
"info" => Some(MessageLevel::Info),
"warning" => Some(MessageLevel::Warning),
"error" => Some(MessageLevel::Error),
_ => None,
}
}
}
pub struct Message<'file,'msg> {
pub level: MessageLevel,
pub kind: MaybeSpanned<'file, &'msg dyn Display>,
}
impl<'file,'msg> Message<'file,'msg> {
pub fn write(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
match &self.kind {
MaybeSpanned::WithoutSpan(_) => {
self.write_description(writer)?;
}
MaybeSpanned::WithSpan(spanned) => {
self.write_description(writer)?;
self.write_code(writer, &spanned.span)?;
}
}
writeln!(writer)?;
Ok(())
}
fn write_description(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
output.set_color(self.level.color());
output.set_bold(true);
write!(output.writer(), "{}: ", self.level.name())?;
output.set_color(None);
writeln!(output.writer(), "{}", *self.kind)?;
Ok(())
}
fn write_code(&self, writer: &mut dyn WriteColor, error: &Span<'_>) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
let num_fmt = LineNumberFormatter::new(error);
num_fmt.spaces(output.writer())?;
writeln!(output.writer())?;
for (line_number, line) in error.lines().numbered() {
let line_fmt = LineFormatter::new(&line);
num_fmt.number(output.writer(), line_number)?;
line_fmt.render(output.writer())?;
// currently, the span will always exist since we take the line from the error
// but future versions may print a line below and above for context that
// is not part of the error
if let Some(faulty_part_of_line) = Span::intersect(error, &line) {
// TODO: implement this without the following 3 assumptions:
// - start_pos - end_pos >= 0, guranteed by data structure invariant of Span
// - start_term_pos - end_term_pos >= 0, guranteed by monotony of columns (a
// Position.char() can only be rendered to 0 or more terminal characters)
// - unwrap(.): both positions are guranteed to exist in the line since we just
// got them from the faulty line, which is a subset of the whole error line
let (start_term_pos, end_term_pos) =
line_fmt.actual_columns(&faulty_part_of_line).unwrap();
let term_width = end_term_pos - start_term_pos;
num_fmt.spaces(output.writer())?;
{
let mut output = ColorOutput::new(output.writer());
output.set_color(self.level.color());
output.set_bold(true);
writeln!(
output.writer(),
"{spaces}{underline}",
spaces = " ".repeat(start_term_pos),
underline = "^".repeat(term_width)
)?;
}
}
}
Ok(())
}
}
/// Helper that prints a range of numbers with the correct
/// amount of padding
struct LineNumberFormatter {
width: usize,
}
impl LineNumberFormatter {
pub fn new(span: &Span<'_>) -> Self {
Self {
width: span.end_position().line_number().to_string().len(),
}
}
pub fn spaces(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
output.set_color(HIGHLIGHT_COLOR);
output.set_bold(true);
write!(output.writer(), " {} | ", " ".repeat(self.width))?;
Ok(())
}
pub fn number(&self, writer: &mut dyn WriteColor, line_number: usize) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
output.set_color(HIGHLIGHT_COLOR);
output.set_bold(true);
let padded_number = pad_left(&line_number.to_string(), self.width);
write!(output.writer(), " {} | ", padded_number)?;
Ok(())
}
}
pub fn pad_left(s: &str, pad: usize) -> String {
pad_left_with_char(s, pad,'')
}
pub fn pad_left_with_char(s: &str, pad: usize, chr: char) -> String {
format!(
"{padding}{string}",
padding = chr
.to_string()
.repeat(pad.checked_sub(s.len()).unwrap_or(0)),
string = s
)
}
/// Writes a user-supplied input line in a safe manner by replacing
/// control-characters with escape sequences.
struct LineFormatter<'span, 'file> {
line: &'span Span<'file>,
}
impl<'span, 'file> LineFormatter<'span, 'file> {
fn new(line: &'span Span<'file>) -> Self {
Self { line }
}
fn render(&self, writer: &mut dyn WriteColor) -> Result<(), Error> {
let mut output = ColorOutput::new(writer);
// TODO: implement an iterator
let chars = self.line.start_position().iter();
for position in chars {
let (text, color) = self.render_char(position.chr());
output.set_color(color);
write!(output.writer(), "{}", text)?;
if position == self.line.end_position() {
break;
}
}
writeln!(output.writer())?;
Ok(())
}
/// Map terminal columns to `Position` columns. Returns a inclusive
/// lower bound, and an exclusive upper bound.
///
/// Each printed character does not actually take up monospace grid cell.
/// For example a TAB character may be represented by 4 spaces. This
/// function will return the actual number of'monospace grid cells'
/// rendered before the given
/// position.
///
/// Returns `None` if the column is out of bounds.
fn actual_columns(&self, span: &Span<'_>) -> Option<(usize, usize)> {
let lower = self.len_printed_before(span.start_position().column());
let upper = self.len_printed_before(span.end_position().column());
match (lower, upper) {
(Some(lower), Some(upper)) => {
let last_char_width = self.render_char(span.end_position().chr()).0.len();
Some((lower, upper + last_char_width))
}
_ => None,
}
}
fn len_printed_before(&self, col: usize) -> Option<usize> | let mut actual_column = 0;
for position in chars {
if position.column() == col {
break;
}
actual_column += self.render_char(position.chr()).0.len();
}
Some(actual_column)
}
fn render_char(&self, chr: char) -> (String, Option<Color>) {
match chr {
'\t' => (" ".repeat(TAB_WIDTH), None),
'\r' | '\n' => ("".to_string(), None),
chr if chr.is_control() => (
format!("{{{}}}", u8_to_printable_representation(chr as u8)),
HIGHLIGHT_COLOR,
),
_ => (chr.to_string(), None),
}
}
}
#[cfg(test)]
#[allow(clippy::print_stdout, clippy::use_debug)]
mod tests {
use super::*;
#[test]
fn test_pad_left() {
let tests = vec![("a", " a"), ("", " "), ("a", "a"), ("", "")];
for (input, expected) in tests {
println!("Testing: {:?} => {:?}", input, expected);
assert_eq!(expected, pad_left(input, expected.len()));
}
// not enough padding does not truncate string
assert_eq!("a", pad_left("a", 0));
}
}
| {
// TODO: get rid of this nonsense
// NOTE: it would actually be nice to condition the Position on the Line
// instead of AsciiFile. Thinking of this, we could actually just do
// `AsciiFile::new((span.as_str().as_bytes()))`. Meaning AsciiFile is
// not a file, but a View
// that restricts the
// linked lists in Positions and Spans to a subset of the file.
// TODO: implement an iterator on span, or
// span.to_view().iter()/.to_ascii_file().iter() this method is
// inherintly unsafe
// because we do not have
// a way to restrict
// positions in a type safe manner.
if self.line.len() < col {
return None;
}
let chars = self.line.start_position().iter();
| identifier_body |
tags.rs | //! Constants for commonly used tags in TIFF files, baseline
//! or extended.
//!
//! Check the [Tiff Tag Reference](https://www.awaresystems.be/imaging/tiff/tifftags.html)
//! for more information on each tag.
#![allow(non_upper_case_globals)]
/// 16-bit identifier of a field entry.
pub type FieldTag = u16;
// pub const NewSubfileType: u16 = 0x00FE;
// pub const ImageWidth: u16 = 0x0100;
// pub const ImageLength: u16 = 0x0101;
// pub const BitsPerSample: u16 = 0x0102;
// pub const Compression: u16 = 0x0103;
// pub const PhotometricInterpretation: u16 = 0x0106;
// pub const FillOrder: u16 = 0x010A;
// pub const ImageDescription: u16 = 0x010E;
// pub const Make: u16 = 0x010F;
// pub const Model: u16 = 0x0110;
// pub const StripOffsets: u16 = 0x0111;
// pub const Orientation: u16 = 0x0112;
// pub const SamplesPerPixel: u16 = 0x0115;
// pub const RowsPerStrip: u16 = 0x0116;
// pub const StripByteCounts: u16 = 0x0117;
// pub const XResolution: u16 = 0x011A;
// pub const YResolution: u16 = 0x011B;
// pub const PlanarConfiguration: u16 = 0x011C;
// pub const ResolutionUnit: u16 = 0x0128;
// pub const Software: u16 = 0x0131;
// pub const DateTime: u16 = 0x0132;
// pub const Artist: u16 = 0x013B;
// pub const TileWidth: u16 = 0x0142;
// pub const TileLength: u16 = 0x0143;
// pub const TileOffsets: u16 = 0x0144;
// pub const TileByteCounts: u16 = 0x0145;
// pub const Copyright: u16 = 0x8298;
pub const SubfileType: u16 = 0x00FF;
pub const Threshholding: u16 = 0x0107;
pub const CellWidth: u16 = 0x0108;
pub const CellLength: u16 = 0x0109;
pub const DocumentName: u16 = 0x010D;
pub const MinSampleValue: u16 = 0x0118;
pub const MaxSampleValue: u16 = 0x0119;
pub const PageName: u16 = 0x011D;
pub const XPosition: u16 = 0x011E;
pub const YPosition: u16 = 0x011F;
pub const FreeOffsets: u16 = 0x0120;
pub const FreeByteCounts: u16 = 0x0121;
pub const GrayResponseUnit: u16 = 0x0122;
pub const GrayResponseCurve: u16 = 0x0123;
pub const T4Options: u16 = 0x0124;
pub const T6Options: u16 = 0x0125;
pub const PageNumber: u16 = 0x0129;
pub const TransferFunction: u16 = 0x012D;
pub const HostComputer: u16 = 0x013C;
pub const Predictor: u16 = 0x013D;
pub const WhitePoint: u16 = 0x013E;
pub const PrimaryChromaticities: u16 = 0x013F;
pub const ColorMap: u16 = 0x0140;
pub const HalftoneHints: u16 = 0x0141;
pub const BadFaxLines: u16 = 0x0146;
pub const CleanFaxData: u16 = 0x0147;
pub const ConsecutiveBadFaxLines: u16 = 0x0148;
pub const SubIFDs: u16 = 0x014A;
pub const InkSet: u16 = 0x014C;
pub const InkNames: u16 = 0x014D;
pub const NumberOfInks: u16 = 0x014E;
pub const DotRange: u16 = 0x0150;
pub const TargetPrinter: u16 = 0x0151;
pub const ExtraSamples: u16 = 0x0152;
pub const SampleFormat: u16 = 0x0153;
pub const SMinSampleValue: u16 = 0x0154;
pub const SMaxSampleValue: u16 = 0x0155;
pub const TransferRange: u16 = 0x0156;
pub const ClipPath: u16 = 0x0157;
pub const XClipPathUnits: u16 = 0x0158;
pub const YClipPathUnits: u16 = 0x0159;
pub const Indexed: u16 = 0x015A;
pub const JPEGTables: u16 = 0x015B;
pub const OPIProxy: u16 = 0x015F;
pub const GlobalParametersIFD: u16 = 0x0190;
pub const ProfileType: u16 = 0x0191;
pub const FaxProfile: u16 = 0x0192;
pub const CodingMethods: u16 = 0x0193;
pub const VersionYear: u16 = 0x0194;
pub const ModeNumber: u16 = 0x0195;
pub const Decode: u16 = 0x01B1;
pub const DefaultImageColor: u16 = 0x01B2;
pub const JPEGProc: u16 = 0x0200;
pub const JPEGInterchangeFormat: u16 = 0x0201;
pub const JPEGInterchangeFormatLength: u16 = 0x0202;
pub const JPEGRestartInterval: u16 = 0x0203;
pub const JPEGLosslessPredictors: u16 = 0x0205;
pub const JPEGPointTransforms: u16 = 0x0206;
pub const JPEGQTables: u16 = 0x0207;
pub const JPEGDCTables: u16 = 0x0208;
pub const JPEGACTables: u16 = 0x0209;
pub const YCbCrCoefficients: u16 = 0x0211;
pub const YCbCrSubSampling: u16 = 0x0212;
pub const YCbCrPositioning: u16 = 0x0213;
pub const ReferenceBlackWhite: u16 = 0x0214;
pub const StripRowCounts: u16 = 0x022F;
pub const XMP: u16 = 0x02BC;
pub const ImageID: u16 = 0x800D;
pub const ImageLayer: u16 = 0x87AC;
// extracted from https://github.com/schoolpost/PyDNG/raw/master/pydng.py
// cat /tmp/tiffs.txt | tr "(),=" \ | awk '{print "printf \"pub const "$1": u16 = 0x%04x; //"$3"\\n\" "$2}'| bash
pub const NewSubfileType: u16 = 0x00fe; //Type.Long
pub const ImageWidth: u16 = 0x0100; //Type.Long
pub const ImageLength: u16 = 0x0101; //Type.Long
pub const BitsPerSample: u16 = 0x0102; //Type.Short
pub const Compression: u16 = 0x0103; //Type.Short
pub const PhotometricInterpretation: u16 = 0x0106; //Type.Short
pub const FillOrder: u16 = 0x010a; //Type.Short
pub const ImageDescription: u16 = 0x010e; //Type.Ascii
pub const Make: u16 = 0x010f; //Type.Ascii
pub const Model: u16 = 0x0110; //Type.Ascii
pub const StripOffsets: u16 = 0x0111; //Type.Long
pub const Orientation: u16 = 0x0112; //Type.Short
pub const SamplesPerPixel: u16 = 0x0115; //Type.Short
pub const RowsPerStrip: u16 = 0x0116; //Type.Short
pub const StripByteCounts: u16 = 0x0117; //Type.Long
pub const XResolution: u16 = 0x011a; //Type.Rational
pub const YResolution: u16 = 0x011b; //Type.Rational
pub const PlanarConfiguration: u16 = 0x011c; //Type.Short
pub const ResolutionUnit: u16 = 0x0128; //Type.Short
pub const Software: u16 = 0x0131; //Type.Ascii
pub const DateTime: u16 = 0x0132; //Type.Ascii
pub const Artist: u16 = 0x013b; //Type.Ascii
pub const TileWidth: u16 = 0x0142; //Type.Short
pub const TileLength: u16 = 0x0143; //Type.Short
pub const TileOffsets: u16 = 0x0144; //Type.Long
pub const TileByteCounts: u16 = 0x0145; //Type.Long
pub const Copyright: u16 = 0x8298; //Type.Ascii
pub const SubIFD: u16 = 0x014a; //Type.IFD
pub const XMP_Metadata: u16 = 0x02bc; //Type.Undefined
pub const CFARepeatPatternDim: u16 = 0x828d; //Type.Short
pub const CFAPattern: u16 = 0x828e; //Type.Byte
pub const ExposureTime: u16 = 0x829a; //Type.Rational
pub const FNumber: u16 = 0x829d; //Type.Rational
pub const EXIF_IFD: u16 = 0x8769; //Type.IFD
pub const ExposureProgram: u16 = 0x8822; //Type.Short
pub const PhotographicSensitivity: u16 = 0x8827; //Type.Short
pub const SensitivityType: u16 = 0x8830; //Type.Short
pub const ExifVersion: u16 = 0x9000; //Type.Undefined
pub const DateTimeOriginal: u16 = 0x9003; //Type.Ascii
pub const ShutterSpeedValue: u16 = 0x9201; //Type.Srational
pub const ApertureValue: u16 = 0x9202; //Type.Rational
pub const ExposureBiasValue: u16 = 0x9204; //Type.Srational
pub const MaxApertureValue: u16 = 0x9205; //Type.Rational
pub const SubjectDistance: u16 = 0x9206; //Type.Rational
pub const MeteringMode: u16 = 0x9207; //Type.Short
pub const Flash: u16 = 0x9209; //Type.Short
pub const FocalLength: u16 = 0x920a; //Type.Rational
pub const TIFF_EP_StandardID: u16 = 0x9216; //Type.Byte
pub const SubsecTime: u16 = 0x9290; //Type.Ascii | pub const FocalPlaneResolutionUnit: u16 = 0xa210; //Type.Short
pub const FocalLengthIn35mmFilm: u16 = 0xa405; //Type.Short
pub const EXIFPhotoBodySerialNumber: u16 = 0xa431; //Type.Ascii
pub const EXIFPhotoLensModel: u16 = 0xa434; //Type.Ascii
pub const DNGVersion: u16 = 0xc612; //Type.Byte
pub const DNGBackwardVersion: u16 = 0xc613; //Type.Byte
pub const UniqueCameraModel: u16 = 0xc614; //Type.Ascii
pub const CFAPlaneColor: u16 = 0xc616; //Type.Byte
pub const CFALayout: u16 = 0xc617; //Type.Short
pub const LinearizationTable: u16 = 0xc618; //Type.Short
pub const BlackLevelRepeatDim: u16 = 0xc619; //Type.Short
pub const BlackLevel: u16 = 0xc61a; //Type.Short
pub const WhiteLevel: u16 = 0xc61d; //Type.Short
pub const DefaultScale: u16 = 0xc61e; //Type.Rational
pub const DefaultCropOrigin: u16 = 0xc61f; //Type.Long
pub const DefaultCropSize: u16 = 0xc620; //Type.Long
pub const ColorMatrix1: u16 = 0xc621; //Type.Srational
pub const ColorMatrix2: u16 = 0xc622; //Type.Srational
pub const CameraCalibration1: u16 = 0xc623; //Type.Srational
pub const CameraCalibration2: u16 = 0xc624; //Type.Srational
pub const AnalogBalance: u16 = 0xc627; //Type.Rational
pub const AsShotNeutral: u16 = 0xc628; //Type.Rational
pub const BaselineExposure: u16 = 0xc62a; //Type.Srational
pub const BaselineNoise: u16 = 0xc62b; //Type.Rational
pub const BaselineSharpness: u16 = 0xc62c; //Type.Rational
pub const BayerGreenSplit: u16 = 0xc62d; //Type.Long
pub const LinearResponseLimit: u16 = 0xc62e; //Type.Rational
pub const CameraSerialNumber: u16 = 0xc62f; //Type.Ascii
pub const AntiAliasStrength: u16 = 0xc632; //Type.Rational
pub const ShadowScale: u16 = 0xc633; //Type.Rational
pub const DNGPrivateData: u16 = 0xc634; //Type.Byte
pub const MakerNoteSafety: u16 = 0xc635; //Type.Short
pub const CalibrationIlluminant1: u16 = 0xc65a; //Type.Short
pub const CalibrationIlluminant2: u16 = 0xc65b; //Type.Short
pub const BestQualityScale: u16 = 0xc65c; //Type.Rational
pub const RawDataUniqueID: u16 = 0xc65d; //Type.Byte
pub const ActiveArea: u16 = 0xc68d; //Type.Long
pub const CameraCalibrationSignature: u16 = 0xc6f3; //Type.Ascii
pub const ProfileCalibrationSignature: u16 = 0xc6f4; //Type.Ascii
pub const NoiseReductionApplied: u16 = 0xc6f7; //Type.Rational
pub const ProfileName: u16 = 0xc6f8; //Type.Ascii
pub const ProfileHueSatMapDims: u16 = 0xc6f9; //Type.Long
pub const ProfileHueSatMapData1: u16 = 0xc6fa; //Type.Float
pub const ProfileHueSatMapData2: u16 = 0xc6fb; //Type.Float
pub const ProfileEmbedPolicy: u16 = 0xc6fd; //Type.Long
pub const PreviewApplicationName: u16 = 0xc716; //Type.Ascii
pub const PreviewApplicationVersion: u16 = 0xc717; //Type.Ascii
pub const PreviewSettingsDigest: u16 = 0xc719; //Type.Byte
pub const PreviewColorSpace: u16 = 0xc71a; //Type.Long
pub const PreviewDateTime: u16 = 0xc71b; //Type.Ascii
pub const NoiseProfile: u16 = 0xc761; //Type.Double
pub const TimeCodes: u16 = 0xc763; //Type.Byte
pub const FrameRate: u16 = 0xc764; //Type.Srational
pub const OpcodeList1: u16 = 0xc740; //Type.Undefined
pub const OpcodeList2: u16 = 0xc741; //Type.Undefined
pub const ReelName: u16 = 0xc789; //Type.Ascii
pub const BaselineExposureOffset: u16 = 0xc7a5; //Type.Srational
pub const NewRawImageDigest: u16 = 0xc7a7; //Type.Byte
// extracted from file
// exiv2 -P nxy 20191226_170725.dng | grep -v "No XMP" | awk '{print "let "$2": u16 = "$1"; // "$3}'
pub const ExifTag: u16 = 0x8769; // Long
pub const ISOSpeedRatings: u16 = 0x8827; // Short
pub const TIFFEPStandardID: u16 = 0x9216; // Byte
pub const ForwardMatrix1: u16 = 0xc714; // SRational
pub const ForwardMatrix2: u16 = 0xc715; // SRational | pub const SubsecTimeOriginal: u16 = 0x9291; //Type.Ascii
pub const FocalPlaneXResolution: u16 = 0xa20e; //Type.Rational
pub const FocalPlaneYResolution: u16 = 0xa20f; //Type.Rational | random_line_split |
root_mod_trait.rs | use super::*;
use crate::{prefix_type::PrefixRefTrait, utils::leak_value};
/// The root module of a dynamic library,
/// which may contain other modules,function pointers,and static references.
///
///
/// # Examples
///
/// For a more in-context example of a type implementing this trait you can look
/// at either the example in the readme for this crate,
/// or the `example/example_*_interface` crates in this crates' repository.
///
/// ### Basic
///
/// ```rust
/// use abi_stable::{library::RootModule, sabi_types::VersionStrings, StableAbi};
///
/// #[repr(C)]
/// #[derive(StableAbi)]
/// #[sabi(kind(Prefix(prefix_ref = Module_Ref, prefix_fields = Module_Prefix)))]
/// pub struct Module {
/// pub first: u8,
/// // The `#[sabi(last_prefix_field)]` attribute here means that this is
/// // the last field in this module that was defined in the
/// // first compatible version of the library,
/// #[sabi(last_prefix_field)]
/// pub second: u16,
/// pub third: u32,
/// }
/// impl RootModule for Module_Ref {
/// abi_stable::declare_root_module_statics! {Module_Ref}
/// const BASE_NAME: &'static str = "example_root_module";
/// const NAME: &'static str = "example_root_module";
/// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!();
/// }
///
/// # fn main(){}
/// ```
pub trait RootModule: Sized + StableAbi + PrefixRefTrait +'static {
/// The name of the dynamic library,which is the same on all platforms.
/// This is generally the name of the `implementation crate`.
const BASE_NAME: &'static str;
/// The name of the library used in error messages.
const NAME: &'static str;
/// The version number of the library that this is a root module of.
///
/// Initialize this with
/// [`package_version_strings!()`](../macro.package_version_strings.html)
const VERSION_STRINGS: VersionStrings;
/// All the constants of this trait and supertraits.
///
/// It can safely be used as a proxy for the associated constants of this trait.
const CONSTANTS: RootModuleConsts = RootModuleConsts {
base_name: RStr::from_str(Self::BASE_NAME),
name: RStr::from_str(Self::NAME),
version_strings: Self::VERSION_STRINGS,
layout: IsLayoutChecked::Yes(<Self as StableAbi>::LAYOUT),
c_abi_testing_fns: crate::library::c_abi_testing::C_ABI_TESTING_FNS,
_priv: (),
};
/// Like `Self::CONSTANTS`,
/// except without including the type layout constant for the root module.
const CONSTANTS_NO_ABI_INFO: RootModuleConsts = RootModuleConsts {
layout: IsLayoutChecked::No,
..Self::CONSTANTS
};
/// Gets the statics for Self.
///
/// To define this associated function use:
/// [`abi_stable::declare_root_module_statics!{TypeOfSelf}`
/// ](../macro.declare_root_module_statics.html).
/// Passing `Self` instead of `TypeOfSelf` won't work.
/// | fn root_module_statics() -> &'static RootModuleStatics<Self>;
/// Gets the root module,returning None if the module is not yet loaded.
#[inline]
fn get_module() -> Option<Self> {
Self::root_module_statics().root_mod.get()
}
/// Gets the RawLibrary of the module,
/// returning None if the dynamic library failed to load
/// (it doesn't exist or layout checking failed).
///
/// Note that if the root module is initialized using `Self::load_module_with`,
/// this will return None even though `Self::get_module` does not.
///
#[inline]
fn get_raw_library() -> Option<&'static RawLibrary> {
Self::root_module_statics().raw_lib.get()
}
/// Returns the path the library would be loaded from,given a directory(folder).
fn get_library_path(directory: &Path) -> PathBuf {
let base_name = Self::BASE_NAME;
RawLibrary::path_in_directory(directory, base_name, LibrarySuffix::NoSuffix)
}
/// Loads the root module,with a closure which either
/// returns the root module or an error.
///
/// If the root module was already loaded,
/// this will return the already loaded root module,
/// without calling the closure.
fn load_module_with<F, E>(f: F) -> Result<Self, E>
where
F: FnOnce() -> Result<Self, E>,
{
Self::root_module_statics().root_mod.try_init(f)
}
/// Loads this module from the path specified by `where_`,
/// first loading the dynamic library if it wasn't already loaded.
///
/// Once the root module is loaded,
/// this will return the already loaded root module.
///
/// # Warning
///
/// If this function is called within a dynamic library,
/// it must be called either within the root module loader function or
/// after that function has been called.
///
/// **DO NOT** call this in the static initializer of a dynamic library,
/// since this library relies on setting up its global state before
/// calling the root module loader.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::OpenError`:
/// If the dynamic library itself could not be loaded.
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable version used by the library is not compatible.
///
/// - `LibraryError::ParseVersionError`:
/// If the version strings in the library can't be parsed as version numbers,
/// this can only happen if the version strings are manually constructed.
///
/// - `LibraryError::IncompatibleVersionNumber`:
/// If the version number of the library is incompatible.
///
/// - `LibraryError::AbiInstability`:
/// If the layout of the root module is not the expected one.
///
/// - `LibraryError::RootModule` :
/// If the root module initializer returned an error or panicked.
///
fn load_from(where_: LibraryPath<'_>) -> Result<Self, LibraryError> {
let statics = Self::root_module_statics();
statics.root_mod.try_init(|| {
let lib = statics.raw_lib.try_init(|| -> Result<_, LibraryError> {
let raw_library = load_raw_library::<Self>(where_)?;
// if the library isn't leaked
// it would cause any use of the module to be a use after free.
//
// By leaking the library
// this allows the root module loader to do anything that'd prevent
// sound library unloading.
Ok(leak_value(raw_library))
})?;
let items = unsafe { lib_header_from_raw_library(lib)? };
items.ensure_layout::<Self>()?;
// safety: the layout was checked in the code above,
unsafe {
items
.init_root_module_with_unchecked_layout::<Self>()?
.initialization()
}
})
}
/// Loads this module from the directory specified by `where_`,
/// first loading the dynamic library if it wasn't already loaded.
///
/// Once the root module is loaded,
/// this will return the already loaded root module.
///
/// Warnings and Errors are detailed in [`load_from`](#method.load_from),
///
fn load_from_directory(where_: &Path) -> Result<Self, LibraryError> {
Self::load_from(LibraryPath::Directory(where_))
}
/// Loads this module from the file at `path_`,
/// first loading the dynamic library if it wasn't already loaded.
///
/// Once the root module is loaded,
/// this will return the already loaded root module.
///
/// Warnings and Errors are detailed in [`load_from`](#method.load_from),
///
fn load_from_file(path_: &Path) -> Result<Self, LibraryError> {
Self::load_from(LibraryPath::FullPath(path_))
}
/// Defines behavior that happens once the module is loaded.
///
/// This is ran in the `RootModule::load*` associated functions
/// after the root module has succesfully been loaded.
///
/// The default implementation does nothing.
fn initialization(self) -> Result<Self, LibraryError> {
Ok(self)
}
}
/// Loads the raw library at `where_`
fn load_raw_library<M>(where_: LibraryPath<'_>) -> Result<RawLibrary, LibraryError>
where
M: RootModule,
{
let path = match where_ {
LibraryPath::Directory(directory) => M::get_library_path(directory),
LibraryPath::FullPath(full_path) => full_path.to_owned(),
};
RawLibrary::load_at(&path)
}
/// Gets the LibHeader of a library.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable used by the library is not compatible.
///
/// # Safety
///
/// The LibHeader is implicitly tied to the lifetime of the library,
/// it will contain dangling `'static` references if the library is dropped before it does.
///
///
pub unsafe fn lib_header_from_raw_library(
raw_library: &RawLibrary,
) -> Result<&'static LibHeader, LibraryError> {
unsafe { abi_header_from_raw_library(raw_library)?.upgrade() }
}
/// Gets the AbiHeaderRef of a library.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// # Safety
///
/// The AbiHeaderRef is implicitly tied to the lifetime of the library,
/// it will contain dangling `'static` references if the library is dropped before it does.
///
///
pub unsafe fn abi_header_from_raw_library(
raw_library: &RawLibrary,
) -> Result<AbiHeaderRef, LibraryError> {
let mangled = ROOT_MODULE_LOADER_NAME_WITH_NUL;
let header: AbiHeaderRef = unsafe { *raw_library.get::<AbiHeaderRef>(mangled.as_bytes())? };
Ok(header)
}
/// Gets the LibHeader of the library at the path.
///
/// This leaks the underlying dynamic library,
/// if you need to do this without leaking you'll need to use
/// `lib_header_from_raw_library` instead.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::OpenError`:
/// If the dynamic library itself could not be loaded.
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable version used by the library is not compatible.
///
///
pub fn lib_header_from_path(path: &Path) -> Result<&'static LibHeader, LibraryError> {
let raw_lib = RawLibrary::load_at(path)?;
let library_getter = unsafe { lib_header_from_raw_library(&raw_lib)? };
mem::forget(raw_lib);
Ok(library_getter)
}
/// Gets the AbiHeaderRef of the library at the path.
///
/// This leaks the underlying dynamic library,
/// if you need to do this without leaking you'll need to use
/// `lib_header_from_raw_library` instead.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::OpenError`:
/// If the dynamic library itself could not be loaded.
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
///
pub fn abi_header_from_path(path: &Path) -> Result<AbiHeaderRef, LibraryError> {
let raw_lib = RawLibrary::load_at(path)?;
let library_getter = unsafe { abi_header_from_raw_library(&raw_lib)? };
mem::forget(raw_lib);
Ok(library_getter)
}
//////////////////////////////////////////////////////////////////////
macro_rules! declare_root_module_consts {
(
fields=[
$(
$(#[$field_meta:meta])*
method_docs=$method_docs:expr,
$field:ident : $field_ty:ty
),* $(,)*
]
) => (
/// All the constants of the [`RootModule`] trait for some erased type.
///
/// [`RootModule`]:./trait.RootModule.html
#[repr(C)]
#[derive(StableAbi,Copy,Clone)]
pub struct RootModuleConsts{
$(
$(#[$field_meta])*
$field : $field_ty,
)*
_priv:(),
}
impl RootModuleConsts{
$(
#[doc=$method_docs]
pub const fn $field(&self)->$field_ty{
self.$field
}
)*
}
)
}
declare_root_module_consts! {
fields=[
method_docs="
The name of the dynamic library,which is the same on all platforms.
This is generally the name of the implementation crate.",
base_name: RStr<'static>,
method_docs="The name of the library used in error messages.",
name: RStr<'static>,
method_docs="The version number of the library this was created from.",
version_strings: VersionStrings,
method_docs="The (optional) type layout constant of the root module.",
layout: IsLayoutChecked,
method_docs="\
Functions used to test that the C abi is the same in both the library
and the loader\
",
c_abi_testing_fns:&'static CAbiTestingFns,
]
} | random_line_split |
|
root_mod_trait.rs | use super::*;
use crate::{prefix_type::PrefixRefTrait, utils::leak_value};
/// The root module of a dynamic library,
/// which may contain other modules,function pointers,and static references.
///
///
/// # Examples
///
/// For a more in-context example of a type implementing this trait you can look
/// at either the example in the readme for this crate,
/// or the `example/example_*_interface` crates in this crates' repository.
///
/// ### Basic
///
/// ```rust
/// use abi_stable::{library::RootModule, sabi_types::VersionStrings, StableAbi};
///
/// #[repr(C)]
/// #[derive(StableAbi)]
/// #[sabi(kind(Prefix(prefix_ref = Module_Ref, prefix_fields = Module_Prefix)))]
/// pub struct Module {
/// pub first: u8,
/// // The `#[sabi(last_prefix_field)]` attribute here means that this is
/// // the last field in this module that was defined in the
/// // first compatible version of the library,
/// #[sabi(last_prefix_field)]
/// pub second: u16,
/// pub third: u32,
/// }
/// impl RootModule for Module_Ref {
/// abi_stable::declare_root_module_statics! {Module_Ref}
/// const BASE_NAME: &'static str = "example_root_module";
/// const NAME: &'static str = "example_root_module";
/// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!();
/// }
///
/// # fn main(){}
/// ```
pub trait RootModule: Sized + StableAbi + PrefixRefTrait +'static {
/// The name of the dynamic library,which is the same on all platforms.
/// This is generally the name of the `implementation crate`.
const BASE_NAME: &'static str;
/// The name of the library used in error messages.
const NAME: &'static str;
/// The version number of the library that this is a root module of.
///
/// Initialize this with
/// [`package_version_strings!()`](../macro.package_version_strings.html)
const VERSION_STRINGS: VersionStrings;
/// All the constants of this trait and supertraits.
///
/// It can safely be used as a proxy for the associated constants of this trait.
const CONSTANTS: RootModuleConsts = RootModuleConsts {
base_name: RStr::from_str(Self::BASE_NAME),
name: RStr::from_str(Self::NAME),
version_strings: Self::VERSION_STRINGS,
layout: IsLayoutChecked::Yes(<Self as StableAbi>::LAYOUT),
c_abi_testing_fns: crate::library::c_abi_testing::C_ABI_TESTING_FNS,
_priv: (),
};
/// Like `Self::CONSTANTS`,
/// except without including the type layout constant for the root module.
const CONSTANTS_NO_ABI_INFO: RootModuleConsts = RootModuleConsts {
layout: IsLayoutChecked::No,
..Self::CONSTANTS
};
/// Gets the statics for Self.
///
/// To define this associated function use:
/// [`abi_stable::declare_root_module_statics!{TypeOfSelf}`
/// ](../macro.declare_root_module_statics.html).
/// Passing `Self` instead of `TypeOfSelf` won't work.
///
fn root_module_statics() -> &'static RootModuleStatics<Self>;
/// Gets the root module,returning None if the module is not yet loaded.
#[inline]
fn get_module() -> Option<Self> {
Self::root_module_statics().root_mod.get()
}
/// Gets the RawLibrary of the module,
/// returning None if the dynamic library failed to load
/// (it doesn't exist or layout checking failed).
///
/// Note that if the root module is initialized using `Self::load_module_with`,
/// this will return None even though `Self::get_module` does not.
///
#[inline]
fn get_raw_library() -> Option<&'static RawLibrary> {
Self::root_module_statics().raw_lib.get()
}
/// Returns the path the library would be loaded from,given a directory(folder).
fn get_library_path(directory: &Path) -> PathBuf {
let base_name = Self::BASE_NAME;
RawLibrary::path_in_directory(directory, base_name, LibrarySuffix::NoSuffix)
}
/// Loads the root module,with a closure which either
/// returns the root module or an error.
///
/// If the root module was already loaded,
/// this will return the already loaded root module,
/// without calling the closure.
fn load_module_with<F, E>(f: F) -> Result<Self, E>
where
F: FnOnce() -> Result<Self, E>,
{
Self::root_module_statics().root_mod.try_init(f)
}
/// Loads this module from the path specified by `where_`,
/// first loading the dynamic library if it wasn't already loaded.
///
/// Once the root module is loaded,
/// this will return the already loaded root module.
///
/// # Warning
///
/// If this function is called within a dynamic library,
/// it must be called either within the root module loader function or
/// after that function has been called.
///
/// **DO NOT** call this in the static initializer of a dynamic library,
/// since this library relies on setting up its global state before
/// calling the root module loader.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::OpenError`:
/// If the dynamic library itself could not be loaded.
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable version used by the library is not compatible.
///
/// - `LibraryError::ParseVersionError`:
/// If the version strings in the library can't be parsed as version numbers,
/// this can only happen if the version strings are manually constructed.
///
/// - `LibraryError::IncompatibleVersionNumber`:
/// If the version number of the library is incompatible.
///
/// - `LibraryError::AbiInstability`:
/// If the layout of the root module is not the expected one.
///
/// - `LibraryError::RootModule` :
/// If the root module initializer returned an error or panicked.
///
fn load_from(where_: LibraryPath<'_>) -> Result<Self, LibraryError> {
let statics = Self::root_module_statics();
statics.root_mod.try_init(|| {
let lib = statics.raw_lib.try_init(|| -> Result<_, LibraryError> {
let raw_library = load_raw_library::<Self>(where_)?;
// if the library isn't leaked
// it would cause any use of the module to be a use after free.
//
// By leaking the library
// this allows the root module loader to do anything that'd prevent
// sound library unloading.
Ok(leak_value(raw_library))
})?;
let items = unsafe { lib_header_from_raw_library(lib)? };
items.ensure_layout::<Self>()?;
// safety: the layout was checked in the code above,
unsafe {
items
.init_root_module_with_unchecked_layout::<Self>()?
.initialization()
}
})
}
/// Loads this module from the directory specified by `where_`,
/// first loading the dynamic library if it wasn't already loaded.
///
/// Once the root module is loaded,
/// this will return the already loaded root module.
///
/// Warnings and Errors are detailed in [`load_from`](#method.load_from),
///
fn load_from_directory(where_: &Path) -> Result<Self, LibraryError> {
Self::load_from(LibraryPath::Directory(where_))
}
/// Loads this module from the file at `path_`,
/// first loading the dynamic library if it wasn't already loaded.
///
/// Once the root module is loaded,
/// this will return the already loaded root module.
///
/// Warnings and Errors are detailed in [`load_from`](#method.load_from),
///
fn load_from_file(path_: &Path) -> Result<Self, LibraryError> {
Self::load_from(LibraryPath::FullPath(path_))
}
/// Defines behavior that happens once the module is loaded.
///
/// This is ran in the `RootModule::load*` associated functions
/// after the root module has succesfully been loaded.
///
/// The default implementation does nothing.
fn initialization(self) -> Result<Self, LibraryError> {
Ok(self)
}
}
/// Loads the raw library at `where_`
fn load_raw_library<M>(where_: LibraryPath<'_>) -> Result<RawLibrary, LibraryError>
where
M: RootModule,
|
/// Gets the LibHeader of a library.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable used by the library is not compatible.
///
/// # Safety
///
/// The LibHeader is implicitly tied to the lifetime of the library,
/// it will contain dangling `'static` references if the library is dropped before it does.
///
///
pub unsafe fn lib_header_from_raw_library(
raw_library: &RawLibrary,
) -> Result<&'static LibHeader, LibraryError> {
unsafe { abi_header_from_raw_library(raw_library)?.upgrade() }
}
/// Gets the AbiHeaderRef of a library.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// # Safety
///
/// The AbiHeaderRef is implicitly tied to the lifetime of the library,
/// it will contain dangling `'static` references if the library is dropped before it does.
///
///
pub unsafe fn abi_header_from_raw_library(
raw_library: &RawLibrary,
) -> Result<AbiHeaderRef, LibraryError> {
let mangled = ROOT_MODULE_LOADER_NAME_WITH_NUL;
let header: AbiHeaderRef = unsafe { *raw_library.get::<AbiHeaderRef>(mangled.as_bytes())? };
Ok(header)
}
/// Gets the LibHeader of the library at the path.
///
/// This leaks the underlying dynamic library,
/// if you need to do this without leaking you'll need to use
/// `lib_header_from_raw_library` instead.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::OpenError`:
/// If the dynamic library itself could not be loaded.
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable version used by the library is not compatible.
///
///
pub fn lib_header_from_path(path: &Path) -> Result<&'static LibHeader, LibraryError> {
let raw_lib = RawLibrary::load_at(path)?;
let library_getter = unsafe { lib_header_from_raw_library(&raw_lib)? };
mem::forget(raw_lib);
Ok(library_getter)
}
/// Gets the AbiHeaderRef of the library at the path.
///
/// This leaks the underlying dynamic library,
/// if you need to do this without leaking you'll need to use
/// `lib_header_from_raw_library` instead.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::OpenError`:
/// If the dynamic library itself could not be loaded.
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
///
pub fn abi_header_from_path(path: &Path) -> Result<AbiHeaderRef, LibraryError> {
let raw_lib = RawLibrary::load_at(path)?;
let library_getter = unsafe { abi_header_from_raw_library(&raw_lib)? };
mem::forget(raw_lib);
Ok(library_getter)
}
//////////////////////////////////////////////////////////////////////
macro_rules! declare_root_module_consts {
(
fields=[
$(
$(#[$field_meta:meta])*
method_docs=$method_docs:expr,
$field:ident : $field_ty:ty
),* $(,)*
]
) => (
/// All the constants of the [`RootModule`] trait for some erased type.
///
/// [`RootModule`]:./trait.RootModule.html
#[repr(C)]
#[derive(StableAbi,Copy,Clone)]
pub struct RootModuleConsts{
$(
$(#[$field_meta])*
$field : $field_ty,
)*
_priv:(),
}
impl RootModuleConsts{
$(
#[doc=$method_docs]
pub const fn $field(&self)->$field_ty{
self.$field
}
)*
}
)
}
declare_root_module_consts! {
fields=[
method_docs="
The name of the dynamic library,which is the same on all platforms.
This is generally the name of the implementation crate.",
base_name: RStr<'static>,
method_docs="The name of the library used in error messages.",
name: RStr<'static>,
method_docs="The version number of the library this was created from.",
version_strings: VersionStrings,
method_docs="The (optional) type layout constant of the root module.",
layout: IsLayoutChecked,
method_docs="\
Functions used to test that the C abi is the same in both the library
and the loader\
",
c_abi_testing_fns:&'static CAbiTestingFns,
]
}
| {
let path = match where_ {
LibraryPath::Directory(directory) => M::get_library_path(directory),
LibraryPath::FullPath(full_path) => full_path.to_owned(),
};
RawLibrary::load_at(&path)
} | identifier_body |
root_mod_trait.rs | use super::*;
use crate::{prefix_type::PrefixRefTrait, utils::leak_value};
/// The root module of a dynamic library,
/// which may contain other modules,function pointers,and static references.
///
///
/// # Examples
///
/// For a more in-context example of a type implementing this trait you can look
/// at either the example in the readme for this crate,
/// or the `example/example_*_interface` crates in this crates' repository.
///
/// ### Basic
///
/// ```rust
/// use abi_stable::{library::RootModule, sabi_types::VersionStrings, StableAbi};
///
/// #[repr(C)]
/// #[derive(StableAbi)]
/// #[sabi(kind(Prefix(prefix_ref = Module_Ref, prefix_fields = Module_Prefix)))]
/// pub struct Module {
/// pub first: u8,
/// // The `#[sabi(last_prefix_field)]` attribute here means that this is
/// // the last field in this module that was defined in the
/// // first compatible version of the library,
/// #[sabi(last_prefix_field)]
/// pub second: u16,
/// pub third: u32,
/// }
/// impl RootModule for Module_Ref {
/// abi_stable::declare_root_module_statics! {Module_Ref}
/// const BASE_NAME: &'static str = "example_root_module";
/// const NAME: &'static str = "example_root_module";
/// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!();
/// }
///
/// # fn main(){}
/// ```
pub trait RootModule: Sized + StableAbi + PrefixRefTrait +'static {
/// The name of the dynamic library,which is the same on all platforms.
/// This is generally the name of the `implementation crate`.
const BASE_NAME: &'static str;
/// The name of the library used in error messages.
const NAME: &'static str;
/// The version number of the library that this is a root module of.
///
/// Initialize this with
/// [`package_version_strings!()`](../macro.package_version_strings.html)
const VERSION_STRINGS: VersionStrings;
/// All the constants of this trait and supertraits.
///
/// It can safely be used as a proxy for the associated constants of this trait.
const CONSTANTS: RootModuleConsts = RootModuleConsts {
base_name: RStr::from_str(Self::BASE_NAME),
name: RStr::from_str(Self::NAME),
version_strings: Self::VERSION_STRINGS,
layout: IsLayoutChecked::Yes(<Self as StableAbi>::LAYOUT),
c_abi_testing_fns: crate::library::c_abi_testing::C_ABI_TESTING_FNS,
_priv: (),
};
/// Like `Self::CONSTANTS`,
/// except without including the type layout constant for the root module.
const CONSTANTS_NO_ABI_INFO: RootModuleConsts = RootModuleConsts {
layout: IsLayoutChecked::No,
..Self::CONSTANTS
};
/// Gets the statics for Self.
///
/// To define this associated function use:
/// [`abi_stable::declare_root_module_statics!{TypeOfSelf}`
/// ](../macro.declare_root_module_statics.html).
/// Passing `Self` instead of `TypeOfSelf` won't work.
///
fn root_module_statics() -> &'static RootModuleStatics<Self>;
/// Gets the root module,returning None if the module is not yet loaded.
#[inline]
fn get_module() -> Option<Self> {
Self::root_module_statics().root_mod.get()
}
/// Gets the RawLibrary of the module,
/// returning None if the dynamic library failed to load
/// (it doesn't exist or layout checking failed).
///
/// Note that if the root module is initialized using `Self::load_module_with`,
/// this will return None even though `Self::get_module` does not.
///
#[inline]
fn get_raw_library() -> Option<&'static RawLibrary> {
Self::root_module_statics().raw_lib.get()
}
/// Returns the path the library would be loaded from,given a directory(folder).
fn get_library_path(directory: &Path) -> PathBuf {
let base_name = Self::BASE_NAME;
RawLibrary::path_in_directory(directory, base_name, LibrarySuffix::NoSuffix)
}
/// Loads the root module,with a closure which either
/// returns the root module or an error.
///
/// If the root module was already loaded,
/// this will return the already loaded root module,
/// without calling the closure.
fn load_module_with<F, E>(f: F) -> Result<Self, E>
where
F: FnOnce() -> Result<Self, E>,
{
Self::root_module_statics().root_mod.try_init(f)
}
/// Loads this module from the path specified by `where_`,
/// first loading the dynamic library if it wasn't already loaded.
///
/// Once the root module is loaded,
/// this will return the already loaded root module.
///
/// # Warning
///
/// If this function is called within a dynamic library,
/// it must be called either within the root module loader function or
/// after that function has been called.
///
/// **DO NOT** call this in the static initializer of a dynamic library,
/// since this library relies on setting up its global state before
/// calling the root module loader.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::OpenError`:
/// If the dynamic library itself could not be loaded.
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable version used by the library is not compatible.
///
/// - `LibraryError::ParseVersionError`:
/// If the version strings in the library can't be parsed as version numbers,
/// this can only happen if the version strings are manually constructed.
///
/// - `LibraryError::IncompatibleVersionNumber`:
/// If the version number of the library is incompatible.
///
/// - `LibraryError::AbiInstability`:
/// If the layout of the root module is not the expected one.
///
/// - `LibraryError::RootModule` :
/// If the root module initializer returned an error or panicked.
///
fn load_from(where_: LibraryPath<'_>) -> Result<Self, LibraryError> {
let statics = Self::root_module_statics();
statics.root_mod.try_init(|| {
let lib = statics.raw_lib.try_init(|| -> Result<_, LibraryError> {
let raw_library = load_raw_library::<Self>(where_)?;
// if the library isn't leaked
// it would cause any use of the module to be a use after free.
//
// By leaking the library
// this allows the root module loader to do anything that'd prevent
// sound library unloading.
Ok(leak_value(raw_library))
})?;
let items = unsafe { lib_header_from_raw_library(lib)? };
items.ensure_layout::<Self>()?;
// safety: the layout was checked in the code above,
unsafe {
items
.init_root_module_with_unchecked_layout::<Self>()?
.initialization()
}
})
}
/// Loads this module from the directory specified by `where_`,
/// first loading the dynamic library if it wasn't already loaded.
///
/// Once the root module is loaded,
/// this will return the already loaded root module.
///
/// Warnings and Errors are detailed in [`load_from`](#method.load_from),
///
fn load_from_directory(where_: &Path) -> Result<Self, LibraryError> {
Self::load_from(LibraryPath::Directory(where_))
}
/// Loads this module from the file at `path_`,
/// first loading the dynamic library if it wasn't already loaded.
///
/// Once the root module is loaded,
/// this will return the already loaded root module.
///
/// Warnings and Errors are detailed in [`load_from`](#method.load_from),
///
fn load_from_file(path_: &Path) -> Result<Self, LibraryError> {
Self::load_from(LibraryPath::FullPath(path_))
}
/// Defines behavior that happens once the module is loaded.
///
/// This is ran in the `RootModule::load*` associated functions
/// after the root module has succesfully been loaded.
///
/// The default implementation does nothing.
fn initialization(self) -> Result<Self, LibraryError> {
Ok(self)
}
}
/// Loads the raw library at `where_`
fn load_raw_library<M>(where_: LibraryPath<'_>) -> Result<RawLibrary, LibraryError>
where
M: RootModule,
{
let path = match where_ {
LibraryPath::Directory(directory) => M::get_library_path(directory),
LibraryPath::FullPath(full_path) => full_path.to_owned(),
};
RawLibrary::load_at(&path)
}
/// Gets the LibHeader of a library.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable used by the library is not compatible.
///
/// # Safety
///
/// The LibHeader is implicitly tied to the lifetime of the library,
/// it will contain dangling `'static` references if the library is dropped before it does.
///
///
pub unsafe fn lib_header_from_raw_library(
raw_library: &RawLibrary,
) -> Result<&'static LibHeader, LibraryError> {
unsafe { abi_header_from_raw_library(raw_library)?.upgrade() }
}
/// Gets the AbiHeaderRef of a library.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// # Safety
///
/// The AbiHeaderRef is implicitly tied to the lifetime of the library,
/// it will contain dangling `'static` references if the library is dropped before it does.
///
///
pub unsafe fn | (
raw_library: &RawLibrary,
) -> Result<AbiHeaderRef, LibraryError> {
let mangled = ROOT_MODULE_LOADER_NAME_WITH_NUL;
let header: AbiHeaderRef = unsafe { *raw_library.get::<AbiHeaderRef>(mangled.as_bytes())? };
Ok(header)
}
/// Gets the LibHeader of the library at the path.
///
/// This leaks the underlying dynamic library,
/// if you need to do this without leaking you'll need to use
/// `lib_header_from_raw_library` instead.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::OpenError`:
/// If the dynamic library itself could not be loaded.
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable version used by the library is not compatible.
///
///
pub fn lib_header_from_path(path: &Path) -> Result<&'static LibHeader, LibraryError> {
let raw_lib = RawLibrary::load_at(path)?;
let library_getter = unsafe { lib_header_from_raw_library(&raw_lib)? };
mem::forget(raw_lib);
Ok(library_getter)
}
/// Gets the AbiHeaderRef of the library at the path.
///
/// This leaks the underlying dynamic library,
/// if you need to do this without leaking you'll need to use
/// `lib_header_from_raw_library` instead.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::OpenError`:
/// If the dynamic library itself could not be loaded.
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
///
pub fn abi_header_from_path(path: &Path) -> Result<AbiHeaderRef, LibraryError> {
let raw_lib = RawLibrary::load_at(path)?;
let library_getter = unsafe { abi_header_from_raw_library(&raw_lib)? };
mem::forget(raw_lib);
Ok(library_getter)
}
//////////////////////////////////////////////////////////////////////
macro_rules! declare_root_module_consts {
(
fields=[
$(
$(#[$field_meta:meta])*
method_docs=$method_docs:expr,
$field:ident : $field_ty:ty
),* $(,)*
]
) => (
/// All the constants of the [`RootModule`] trait for some erased type.
///
/// [`RootModule`]:./trait.RootModule.html
#[repr(C)]
#[derive(StableAbi,Copy,Clone)]
pub struct RootModuleConsts{
$(
$(#[$field_meta])*
$field : $field_ty,
)*
_priv:(),
}
impl RootModuleConsts{
$(
#[doc=$method_docs]
pub const fn $field(&self)->$field_ty{
self.$field
}
)*
}
)
}
declare_root_module_consts! {
fields=[
method_docs="
The name of the dynamic library,which is the same on all platforms.
This is generally the name of the implementation crate.",
base_name: RStr<'static>,
method_docs="The name of the library used in error messages.",
name: RStr<'static>,
method_docs="The version number of the library this was created from.",
version_strings: VersionStrings,
method_docs="The (optional) type layout constant of the root module.",
layout: IsLayoutChecked,
method_docs="\
Functions used to test that the C abi is the same in both the library
and the loader\
",
c_abi_testing_fns:&'static CAbiTestingFns,
]
}
| abi_header_from_raw_library | identifier_name |
server.rs | //! Processes requests from clients & peer nodes
//!
//! # Overview
//!
//! The MinDB server is a peer in the MiniDB cluster. It is initialized with a
//! port to bind to and a list of peers to replicate to. The server then
//! processes requests send from both clients and peers.
//!
//! # Peers
//!
//! On process start, the cluster topology is read from a config file
//! (`etc/nodes.toml`). The node represented by the current server process is
//! extracted this topology, leaving the list of peers.
//!
//! After the server starts, connections will be established to all the peers.
//! If a peer cannot be reached, the connection will be retried until the peer
//! becomes reachable.
//!
//! # Replication
//!
//! When the server receives a mutation request from a client, the mutation is
//! processed on the server itself. Once the mutation succeeds, the server
//! state is replicated to all the peers. Replication involves sending the
//! entire data set to all the peers. This is not the most efficient strategy,
//! but we aren't trying to build Riak (or even MongoDB).
//!
//! In the event that replication is unable to keep up with the mutation rate,
//! replication messages are dropped in favor of ensuring that the final
//! replication message is delivered. This works because every replication
//! message includes the entire state at that point. The CRDT ensures that no
//! matter what state the peers are at, it is able to converge with the final
//! replication message (assuming no bugs in the CRDT implementation);
use config;
use dt::{Set, ActorId};
use peer::Peer;
use proto::{self, Request, Response, Transport};
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpListener;
use tokio_service::Service;
use tokio_proto::easy::multiplex;
use tokio_timer::Timer;
use futures::{self, Future, Async};
use futures::stream::{Stream};
use rand::{self, Rng};
use std::io;
use std::cell::RefCell;
use std::rc::Rc;
// The in-memory MinDB state. Stored in a ref-counted cell and shared across
// all open server connections. Whenever a socket connects, a `RequestHandler`
// instance will be initialized with a pointer to this.
struct Server {
// The DB data. This is the CRDT Set. When the server process starts, this
// is initialized to an empty set.
data: Set<String>,
// The server's ActorId. This ActorID value **MUST** be unique across the
// cluster and should never be reused by another node.
//
// In theory, if the data was persisted to disk, the ActorId would be
// stored withe persisted state. However, since the state is initialized
// each time the process starts, the ActorId must be unique.
//
// To handle this, the ActorId is randomly generated.
actor_id: ActorId,
// Handle to the cluster peers. The `Peer` type manages the socket
// connection, including initial connect as well as reconnecting when the
// connection fails.
//
// Whenever the set is mutated by a client, it is replicated to the list of
// peers.
peers: Vec<Peer>,
}
// Handles MiniDB client requests. Implements `Service`
struct RequestHandler {
server_state: Rc<RefCell<Server>>,
}
/// Run a server node.
///
/// The function initializes new server state, including an empty CRDT set,
/// then it will bind to the requested port and start processing connections.
/// Connections will be made from both clients and other peers.
///
/// The function will block while the server is running.
pub fn run(config: config::Node) -> io::Result<()> {
// Create the tokio-core reactor
let mut core = try!(Core::new());
// Get a handle to the reactor
let handle = core.handle();
// Bind the Tcp listener, listening on the requested socket address.
let listener = try!(TcpListener::bind(config.local_addr(), &handle));
// `Core::run` runs the reactor. This call will block until the future
// provided as the argument completes. In this case, the given future
// processes the inbound TCP connections.
core.run(futures::lazy(move || {
// Initialize the server state
let server_state = Rc::new(RefCell::new(Server::new(&config, &handle)));
// `listener.incoming()` provides a `Stream` of inbound TCP connections
listener.incoming().for_each(move |(sock, _)| {
debug!("server accepted socket");
// Create client handle. This implements `tokio_service::Service`.
let client_handler = RequestHandler {
server_state: server_state.clone(),
};
// Initialize the transport implementation backed by the Tcp
// socket.
let transport = Transport::new(sock);
// Use `tokio_proto` to handle the details of multiplexing.
// `EasyServer` takes the transport, which is basically a stream of
// frames as they are read off the socket and manages mapping the
// frames to request / response pairs.
let connection_task = multiplex::EasyServer::new(client_handler, transport);
// Spawn a new reactor task to process the connection. A task is a
// light-weight unit of work. Tasks are generally used for managing
// resources, in this case the resource is the socket.
handle.spawn(connection_task);
Ok(())
})
}))
}
impl Server {
// Initialize the server state using the supplied config. This function
// will also establish connections to the peers, which is why `&Handle` is
// needed.
fn new(config: &config::Node, handle: &Handle) -> Server {
// Initialize a timer, this timer will be passed to all peers.
let timer = Timer::default();
// Connect the peers
let peers = config.routes().into_iter()
.map(|route| Peer::connect(route, handle, &timer))
.collect();
// Randomly assign an `ActorId` to the current process. It is
// imperative that the `ActorId` is unique in the cluster and is not
// reused across server restarts (since the state is reset).
let mut rng = rand::thread_rng();
let actor_id: ActorId = rng.next_u64().into();
debug!("server actor-id={:?}", actor_id);
// Return the new server state with an empty data set
Server {
data: Set::new(),
actor_id: actor_id,
peers: peers,
}
}
// Replicate the current data set to the list of peers.
fn | (&self) {
// Iterate all the peers sending a clone of the data. This operation
// performs a deep clone for each peer, which is not going to be super
// efficient as the data set grows, but improving this is out of scope
// for MiniDB.
for peer in &self.peers {
peer.send(self.data.clone());
}
}
}
// Service implementation for `RequestHandler`
//
// `Service` is the Tokio abstraction for asynchronous request / response
// handling. This is where we will process all requests sent by clients and
// peers.
//
// Instead of mixing a single service to handle both clients and peers, a
// better strategy would probably be to have two separate TCP listeners on
// different ports to handle the client and the peers.
impl Service for RequestHandler {
// The Request and Response types live in `proto`
type Request = Request;
type Response = Response;
type Error = io::Error;
// For greates flexibility, a Box<Future> is used. This has the downside of
// requiring an allocation and dynamic dispatch. Currently, the service
// only responds with `futures::Done`, so the type could be changed.
//
// If the service respond with different futures depending on a conditional
// branch, then returning Box or implementing a custom future is required.
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, request: Self::Request) -> Self::Future {
match request {
Request::Get(_) => {
info!("[COMMAND] Get");
// Clone the current state and respond with the set
//
let data = self.server_state.borrow().data.clone();
let resp = Response::Value(data);
Box::new(futures::done(Ok(resp)))
}
Request::Insert(cmd) => {
info!("[COMMAND] Insert {:?}", cmd.value());
// Insert the new value, initiate a replication to all peers,
// and respond with Success
//
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
state.data.insert(actor_id, cmd.value());
// Replicate the new state to all peers
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Remove(cmd) => {
info!("[COMMAND] Remove {:?}", cmd.value());
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
// If the request includes a version vector, this indicates
// that a causal remove is requested. A causal remove implies
// removing the value from the set at the state represented by
// the version vector and leaving any insertions that are
// either concurrent or successors to the supplied version
// vector.
match cmd.causality() {
Some(version_vec) => {
state.data.causal_remove(actor_id, version_vec, cmd.value());
}
None => {
state.data.remove(actor_id, cmd.value());
}
}
// Replicate the new state to all peers
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Clear(_) => {
info!("[COMMAND] Clear");
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
state.data.clear(actor_id);
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Join(other) => {
info!("[COMMAND] Join");
// A Join request is issued by a peer during replication and
// provides the peer's latest state.
//
// The join request is handled by joining the provided state
// into the node's current state.
let mut state = self.server_state.borrow_mut();
state.data.join(&other);
if log_enabled!(::log::LogLevel::Debug) {
for elem in state.data.iter() {
debug!(" - {:?}", elem);
}
}
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
}
}
fn poll_ready(&self) -> Async<()> {
Async::Ready(())
}
}
| replicate | identifier_name |
server.rs | //! Processes requests from clients & peer nodes
//!
//! # Overview
//!
//! The MinDB server is a peer in the MiniDB cluster. It is initialized with a
//! port to bind to and a list of peers to replicate to. The server then
//! processes requests send from both clients and peers.
//!
//! # Peers
//!
//! On process start, the cluster topology is read from a config file
//! (`etc/nodes.toml`). The node represented by the current server process is
//! extracted this topology, leaving the list of peers.
//!
//! After the server starts, connections will be established to all the peers.
//! If a peer cannot be reached, the connection will be retried until the peer
//! becomes reachable.
//!
//! # Replication
//!
//! When the server receives a mutation request from a client, the mutation is
//! processed on the server itself. Once the mutation succeeds, the server
//! state is replicated to all the peers. Replication involves sending the
//! entire data set to all the peers. This is not the most efficient strategy,
//! but we aren't trying to build Riak (or even MongoDB).
//!
//! In the event that replication is unable to keep up with the mutation rate,
//! replication messages are dropped in favor of ensuring that the final
//! replication message is delivered. This works because every replication
//! message includes the entire state at that point. The CRDT ensures that no
//! matter what state the peers are at, it is able to converge with the final
//! replication message (assuming no bugs in the CRDT implementation);
use config;
use dt::{Set, ActorId};
use peer::Peer;
use proto::{self, Request, Response, Transport};
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpListener;
use tokio_service::Service;
use tokio_proto::easy::multiplex;
use tokio_timer::Timer;
use futures::{self, Future, Async};
use futures::stream::{Stream};
use rand::{self, Rng};
use std::io;
use std::cell::RefCell;
use std::rc::Rc;
// The in-memory MinDB state. Stored in a ref-counted cell and shared across
// all open server connections. Whenever a socket connects, a `RequestHandler`
// instance will be initialized with a pointer to this.
struct Server {
// The DB data. This is the CRDT Set. When the server process starts, this
// is initialized to an empty set.
data: Set<String>,
// The server's ActorId. This ActorID value **MUST** be unique across the
// cluster and should never be reused by another node.
//
// In theory, if the data was persisted to disk, the ActorId would be
// stored withe persisted state. However, since the state is initialized
// each time the process starts, the ActorId must be unique.
//
// To handle this, the ActorId is randomly generated.
actor_id: ActorId,
// Handle to the cluster peers. The `Peer` type manages the socket
// connection, including initial connect as well as reconnecting when the
// connection fails.
//
// Whenever the set is mutated by a client, it is replicated to the list of
// peers.
peers: Vec<Peer>,
}
// Handles MiniDB client requests. Implements `Service`
struct RequestHandler {
server_state: Rc<RefCell<Server>>,
}
/// Run a server node.
///
/// The function initializes new server state, including an empty CRDT set,
/// then it will bind to the requested port and start processing connections.
/// Connections will be made from both clients and other peers.
///
/// The function will block while the server is running.
pub fn run(config: config::Node) -> io::Result<()> {
// Create the tokio-core reactor
let mut core = try!(Core::new());
// Get a handle to the reactor
let handle = core.handle();
// Bind the Tcp listener, listening on the requested socket address.
let listener = try!(TcpListener::bind(config.local_addr(), &handle));
// `Core::run` runs the reactor. This call will block until the future
// provided as the argument completes. In this case, the given future
// processes the inbound TCP connections.
core.run(futures::lazy(move || {
// Initialize the server state
let server_state = Rc::new(RefCell::new(Server::new(&config, &handle)));
// `listener.incoming()` provides a `Stream` of inbound TCP connections
listener.incoming().for_each(move |(sock, _)| {
debug!("server accepted socket");
// Create client handle. This implements `tokio_service::Service`.
let client_handler = RequestHandler {
server_state: server_state.clone(),
};
// Initialize the transport implementation backed by the Tcp
// socket.
let transport = Transport::new(sock);
// Use `tokio_proto` to handle the details of multiplexing.
// `EasyServer` takes the transport, which is basically a stream of
// frames as they are read off the socket and manages mapping the
// frames to request / response pairs.
let connection_task = multiplex::EasyServer::new(client_handler, transport);
// Spawn a new reactor task to process the connection. A task is a
// light-weight unit of work. Tasks are generally used for managing
// resources, in this case the resource is the socket.
handle.spawn(connection_task);
Ok(())
})
}))
}
impl Server {
// Initialize the server state using the supplied config. This function
// will also establish connections to the peers, which is why `&Handle` is
// needed.
fn new(config: &config::Node, handle: &Handle) -> Server {
// Initialize a timer, this timer will be passed to all peers.
let timer = Timer::default();
// Connect the peers
let peers = config.routes().into_iter()
.map(|route| Peer::connect(route, handle, &timer))
.collect();
// Randomly assign an `ActorId` to the current process. It is
// imperative that the `ActorId` is unique in the cluster and is not
// reused across server restarts (since the state is reset).
let mut rng = rand::thread_rng();
let actor_id: ActorId = rng.next_u64().into();
debug!("server actor-id={:?}", actor_id);
// Return the new server state with an empty data set
Server {
data: Set::new(),
actor_id: actor_id,
peers: peers,
}
}
// Replicate the current data set to the list of peers.
fn replicate(&self) {
// Iterate all the peers sending a clone of the data. This operation
// performs a deep clone for each peer, which is not going to be super
// efficient as the data set grows, but improving this is out of scope
// for MiniDB.
for peer in &self.peers {
peer.send(self.data.clone());
}
}
}
// Service implementation for `RequestHandler`
//
// `Service` is the Tokio abstraction for asynchronous request / response
// handling. This is where we will process all requests sent by clients and
// peers.
//
// Instead of mixing a single service to handle both clients and peers, a
// better strategy would probably be to have two separate TCP listeners on
// different ports to handle the client and the peers.
impl Service for RequestHandler {
// The Request and Response types live in `proto`
type Request = Request;
type Response = Response;
type Error = io::Error;
// For greates flexibility, a Box<Future> is used. This has the downside of
// requiring an allocation and dynamic dispatch. Currently, the service
// only responds with `futures::Done`, so the type could be changed.
//
// If the service respond with different futures depending on a conditional
// branch, then returning Box or implementing a custom future is required.
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, request: Self::Request) -> Self::Future {
match request {
Request::Get(_) => {
info!("[COMMAND] Get");
// Clone the current state and respond with the set
//
let data = self.server_state.borrow().data.clone();
let resp = Response::Value(data);
Box::new(futures::done(Ok(resp)))
}
Request::Insert(cmd) => {
info!("[COMMAND] Insert {:?}", cmd.value());
// Insert the new value, initiate a replication to all peers, | //
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
state.data.insert(actor_id, cmd.value());
// Replicate the new state to all peers
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Remove(cmd) => {
info!("[COMMAND] Remove {:?}", cmd.value());
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
// If the request includes a version vector, this indicates
// that a causal remove is requested. A causal remove implies
// removing the value from the set at the state represented by
// the version vector and leaving any insertions that are
// either concurrent or successors to the supplied version
// vector.
match cmd.causality() {
Some(version_vec) => {
state.data.causal_remove(actor_id, version_vec, cmd.value());
}
None => {
state.data.remove(actor_id, cmd.value());
}
}
// Replicate the new state to all peers
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Clear(_) => {
info!("[COMMAND] Clear");
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
state.data.clear(actor_id);
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Join(other) => {
info!("[COMMAND] Join");
// A Join request is issued by a peer during replication and
// provides the peer's latest state.
//
// The join request is handled by joining the provided state
// into the node's current state.
let mut state = self.server_state.borrow_mut();
state.data.join(&other);
if log_enabled!(::log::LogLevel::Debug) {
for elem in state.data.iter() {
debug!(" - {:?}", elem);
}
}
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
}
}
fn poll_ready(&self) -> Async<()> {
Async::Ready(())
}
} | // and respond with Success | random_line_split |
server.rs | //! Processes requests from clients & peer nodes
//!
//! # Overview
//!
//! The MinDB server is a peer in the MiniDB cluster. It is initialized with a
//! port to bind to and a list of peers to replicate to. The server then
//! processes requests send from both clients and peers.
//!
//! # Peers
//!
//! On process start, the cluster topology is read from a config file
//! (`etc/nodes.toml`). The node represented by the current server process is
//! extracted this topology, leaving the list of peers.
//!
//! After the server starts, connections will be established to all the peers.
//! If a peer cannot be reached, the connection will be retried until the peer
//! becomes reachable.
//!
//! # Replication
//!
//! When the server receives a mutation request from a client, the mutation is
//! processed on the server itself. Once the mutation succeeds, the server
//! state is replicated to all the peers. Replication involves sending the
//! entire data set to all the peers. This is not the most efficient strategy,
//! but we aren't trying to build Riak (or even MongoDB).
//!
//! In the event that replication is unable to keep up with the mutation rate,
//! replication messages are dropped in favor of ensuring that the final
//! replication message is delivered. This works because every replication
//! message includes the entire state at that point. The CRDT ensures that no
//! matter what state the peers are at, it is able to converge with the final
//! replication message (assuming no bugs in the CRDT implementation);
use config;
use dt::{Set, ActorId};
use peer::Peer;
use proto::{self, Request, Response, Transport};
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpListener;
use tokio_service::Service;
use tokio_proto::easy::multiplex;
use tokio_timer::Timer;
use futures::{self, Future, Async};
use futures::stream::{Stream};
use rand::{self, Rng};
use std::io;
use std::cell::RefCell;
use std::rc::Rc;
// The in-memory MinDB state. Stored in a ref-counted cell and shared across
// all open server connections. Whenever a socket connects, a `RequestHandler`
// instance will be initialized with a pointer to this.
struct Server {
// The DB data. This is the CRDT Set. When the server process starts, this
// is initialized to an empty set.
data: Set<String>,
// The server's ActorId. This ActorID value **MUST** be unique across the
// cluster and should never be reused by another node.
//
// In theory, if the data was persisted to disk, the ActorId would be
// stored withe persisted state. However, since the state is initialized
// each time the process starts, the ActorId must be unique.
//
// To handle this, the ActorId is randomly generated.
actor_id: ActorId,
// Handle to the cluster peers. The `Peer` type manages the socket
// connection, including initial connect as well as reconnecting when the
// connection fails.
//
// Whenever the set is mutated by a client, it is replicated to the list of
// peers.
peers: Vec<Peer>,
}
// Handles MiniDB client requests. Implements `Service`
struct RequestHandler {
server_state: Rc<RefCell<Server>>,
}
/// Run a server node.
///
/// The function initializes new server state, including an empty CRDT set,
/// then it will bind to the requested port and start processing connections.
/// Connections will be made from both clients and other peers.
///
/// The function will block while the server is running.
pub fn run(config: config::Node) -> io::Result<()> {
// Create the tokio-core reactor
let mut core = try!(Core::new());
// Get a handle to the reactor
let handle = core.handle();
// Bind the Tcp listener, listening on the requested socket address.
let listener = try!(TcpListener::bind(config.local_addr(), &handle));
// `Core::run` runs the reactor. This call will block until the future
// provided as the argument completes. In this case, the given future
// processes the inbound TCP connections.
core.run(futures::lazy(move || {
// Initialize the server state
let server_state = Rc::new(RefCell::new(Server::new(&config, &handle)));
// `listener.incoming()` provides a `Stream` of inbound TCP connections
listener.incoming().for_each(move |(sock, _)| {
debug!("server accepted socket");
// Create client handle. This implements `tokio_service::Service`.
let client_handler = RequestHandler {
server_state: server_state.clone(),
};
// Initialize the transport implementation backed by the Tcp
// socket.
let transport = Transport::new(sock);
// Use `tokio_proto` to handle the details of multiplexing.
// `EasyServer` takes the transport, which is basically a stream of
// frames as they are read off the socket and manages mapping the
// frames to request / response pairs.
let connection_task = multiplex::EasyServer::new(client_handler, transport);
// Spawn a new reactor task to process the connection. A task is a
// light-weight unit of work. Tasks are generally used for managing
// resources, in this case the resource is the socket.
handle.spawn(connection_task);
Ok(())
})
}))
}
impl Server {
// Initialize the server state using the supplied config. This function
// will also establish connections to the peers, which is why `&Handle` is
// needed.
fn new(config: &config::Node, handle: &Handle) -> Server {
// Initialize a timer, this timer will be passed to all peers.
let timer = Timer::default();
// Connect the peers
let peers = config.routes().into_iter()
.map(|route| Peer::connect(route, handle, &timer))
.collect();
// Randomly assign an `ActorId` to the current process. It is
// imperative that the `ActorId` is unique in the cluster and is not
// reused across server restarts (since the state is reset).
let mut rng = rand::thread_rng();
let actor_id: ActorId = rng.next_u64().into();
debug!("server actor-id={:?}", actor_id);
// Return the new server state with an empty data set
Server {
data: Set::new(),
actor_id: actor_id,
peers: peers,
}
}
// Replicate the current data set to the list of peers.
fn replicate(&self) {
// Iterate all the peers sending a clone of the data. This operation
// performs a deep clone for each peer, which is not going to be super
// efficient as the data set grows, but improving this is out of scope
// for MiniDB.
for peer in &self.peers {
peer.send(self.data.clone());
}
}
}
// Service implementation for `RequestHandler`
//
// `Service` is the Tokio abstraction for asynchronous request / response
// handling. This is where we will process all requests sent by clients and
// peers.
//
// Instead of mixing a single service to handle both clients and peers, a
// better strategy would probably be to have two separate TCP listeners on
// different ports to handle the client and the peers.
impl Service for RequestHandler {
// The Request and Response types live in `proto`
type Request = Request;
type Response = Response;
type Error = io::Error;
// For greates flexibility, a Box<Future> is used. This has the downside of
// requiring an allocation and dynamic dispatch. Currently, the service
// only responds with `futures::Done`, so the type could be changed.
//
// If the service respond with different futures depending on a conditional
// branch, then returning Box or implementing a custom future is required.
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, request: Self::Request) -> Self::Future {
match request {
Request::Get(_) => {
info!("[COMMAND] Get");
// Clone the current state and respond with the set
//
let data = self.server_state.borrow().data.clone();
let resp = Response::Value(data);
Box::new(futures::done(Ok(resp)))
}
Request::Insert(cmd) => {
info!("[COMMAND] Insert {:?}", cmd.value());
// Insert the new value, initiate a replication to all peers,
// and respond with Success
//
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
state.data.insert(actor_id, cmd.value());
// Replicate the new state to all peers
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Remove(cmd) => {
info!("[COMMAND] Remove {:?}", cmd.value());
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
// If the request includes a version vector, this indicates
// that a causal remove is requested. A causal remove implies
// removing the value from the set at the state represented by
// the version vector and leaving any insertions that are
// either concurrent or successors to the supplied version
// vector.
match cmd.causality() {
Some(version_vec) => {
state.data.causal_remove(actor_id, version_vec, cmd.value());
}
None => {
state.data.remove(actor_id, cmd.value());
}
}
// Replicate the new state to all peers
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Clear(_) => |
Request::Join(other) => {
info!("[COMMAND] Join");
// A Join request is issued by a peer during replication and
// provides the peer's latest state.
//
// The join request is handled by joining the provided state
// into the node's current state.
let mut state = self.server_state.borrow_mut();
state.data.join(&other);
if log_enabled!(::log::LogLevel::Debug) {
for elem in state.data.iter() {
debug!(" - {:?}", elem);
}
}
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
}
}
fn poll_ready(&self) -> Async<()> {
Async::Ready(())
}
}
| {
info!("[COMMAND] Clear");
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
state.data.clear(actor_id);
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
} | conditional_block |
server.rs | //! Processes requests from clients & peer nodes
//!
//! # Overview
//!
//! The MinDB server is a peer in the MiniDB cluster. It is initialized with a
//! port to bind to and a list of peers to replicate to. The server then
//! processes requests send from both clients and peers.
//!
//! # Peers
//!
//! On process start, the cluster topology is read from a config file
//! (`etc/nodes.toml`). The node represented by the current server process is
//! extracted this topology, leaving the list of peers.
//!
//! After the server starts, connections will be established to all the peers.
//! If a peer cannot be reached, the connection will be retried until the peer
//! becomes reachable.
//!
//! # Replication
//!
//! When the server receives a mutation request from a client, the mutation is
//! processed on the server itself. Once the mutation succeeds, the server
//! state is replicated to all the peers. Replication involves sending the
//! entire data set to all the peers. This is not the most efficient strategy,
//! but we aren't trying to build Riak (or even MongoDB).
//!
//! In the event that replication is unable to keep up with the mutation rate,
//! replication messages are dropped in favor of ensuring that the final
//! replication message is delivered. This works because every replication
//! message includes the entire state at that point. The CRDT ensures that no
//! matter what state the peers are at, it is able to converge with the final
//! replication message (assuming no bugs in the CRDT implementation);
use config;
use dt::{Set, ActorId};
use peer::Peer;
use proto::{self, Request, Response, Transport};
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpListener;
use tokio_service::Service;
use tokio_proto::easy::multiplex;
use tokio_timer::Timer;
use futures::{self, Future, Async};
use futures::stream::{Stream};
use rand::{self, Rng};
use std::io;
use std::cell::RefCell;
use std::rc::Rc;
// The in-memory MinDB state. Stored in a ref-counted cell and shared across
// all open server connections. Whenever a socket connects, a `RequestHandler`
// instance will be initialized with a pointer to this.
struct Server {
// The DB data. This is the CRDT Set. When the server process starts, this
// is initialized to an empty set.
data: Set<String>,
// The server's ActorId. This ActorID value **MUST** be unique across the
// cluster and should never be reused by another node.
//
// In theory, if the data was persisted to disk, the ActorId would be
// stored withe persisted state. However, since the state is initialized
// each time the process starts, the ActorId must be unique.
//
// To handle this, the ActorId is randomly generated.
actor_id: ActorId,
// Handle to the cluster peers. The `Peer` type manages the socket
// connection, including initial connect as well as reconnecting when the
// connection fails.
//
// Whenever the set is mutated by a client, it is replicated to the list of
// peers.
peers: Vec<Peer>,
}
// Handles MiniDB client requests. Implements `Service`
struct RequestHandler {
server_state: Rc<RefCell<Server>>,
}
/// Run a server node.
///
/// The function initializes new server state, including an empty CRDT set,
/// then it will bind to the requested port and start processing connections.
/// Connections will be made from both clients and other peers.
///
/// The function will block while the server is running.
pub fn run(config: config::Node) -> io::Result<()> {
// Create the tokio-core reactor
let mut core = try!(Core::new());
// Get a handle to the reactor
let handle = core.handle();
// Bind the Tcp listener, listening on the requested socket address.
let listener = try!(TcpListener::bind(config.local_addr(), &handle));
// `Core::run` runs the reactor. This call will block until the future
// provided as the argument completes. In this case, the given future
// processes the inbound TCP connections.
core.run(futures::lazy(move || {
// Initialize the server state
let server_state = Rc::new(RefCell::new(Server::new(&config, &handle)));
// `listener.incoming()` provides a `Stream` of inbound TCP connections
listener.incoming().for_each(move |(sock, _)| {
debug!("server accepted socket");
// Create client handle. This implements `tokio_service::Service`.
let client_handler = RequestHandler {
server_state: server_state.clone(),
};
// Initialize the transport implementation backed by the Tcp
// socket.
let transport = Transport::new(sock);
// Use `tokio_proto` to handle the details of multiplexing.
// `EasyServer` takes the transport, which is basically a stream of
// frames as they are read off the socket and manages mapping the
// frames to request / response pairs.
let connection_task = multiplex::EasyServer::new(client_handler, transport);
// Spawn a new reactor task to process the connection. A task is a
// light-weight unit of work. Tasks are generally used for managing
// resources, in this case the resource is the socket.
handle.spawn(connection_task);
Ok(())
})
}))
}
impl Server {
// Initialize the server state using the supplied config. This function
// will also establish connections to the peers, which is why `&Handle` is
// needed.
fn new(config: &config::Node, handle: &Handle) -> Server {
// Initialize a timer, this timer will be passed to all peers.
let timer = Timer::default();
// Connect the peers
let peers = config.routes().into_iter()
.map(|route| Peer::connect(route, handle, &timer))
.collect();
// Randomly assign an `ActorId` to the current process. It is
// imperative that the `ActorId` is unique in the cluster and is not
// reused across server restarts (since the state is reset).
let mut rng = rand::thread_rng();
let actor_id: ActorId = rng.next_u64().into();
debug!("server actor-id={:?}", actor_id);
// Return the new server state with an empty data set
Server {
data: Set::new(),
actor_id: actor_id,
peers: peers,
}
}
// Replicate the current data set to the list of peers.
fn replicate(&self) {
// Iterate all the peers sending a clone of the data. This operation
// performs a deep clone for each peer, which is not going to be super
// efficient as the data set grows, but improving this is out of scope
// for MiniDB.
for peer in &self.peers {
peer.send(self.data.clone());
}
}
}
// Service implementation for `RequestHandler`
//
// `Service` is the Tokio abstraction for asynchronous request / response
// handling. This is where we will process all requests sent by clients and
// peers.
//
// Instead of mixing a single service to handle both clients and peers, a
// better strategy would probably be to have two separate TCP listeners on
// different ports to handle the client and the peers.
impl Service for RequestHandler {
// The Request and Response types live in `proto`
type Request = Request;
type Response = Response;
type Error = io::Error;
// For greates flexibility, a Box<Future> is used. This has the downside of
// requiring an allocation and dynamic dispatch. Currently, the service
// only responds with `futures::Done`, so the type could be changed.
//
// If the service respond with different futures depending on a conditional
// branch, then returning Box or implementing a custom future is required.
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, request: Self::Request) -> Self::Future | state.data.insert(actor_id, cmd.value());
// Replicate the new state to all peers
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Remove(cmd) => {
info!("[COMMAND] Remove {:?}", cmd.value());
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
// If the request includes a version vector, this indicates
// that a causal remove is requested. A causal remove implies
// removing the value from the set at the state represented by
// the version vector and leaving any insertions that are
// either concurrent or successors to the supplied version
// vector.
match cmd.causality() {
Some(version_vec) => {
state.data.causal_remove(actor_id, version_vec, cmd.value());
}
None => {
state.data.remove(actor_id, cmd.value());
}
}
// Replicate the new state to all peers
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Clear(_) => {
info!("[COMMAND] Clear");
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
state.data.clear(actor_id);
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Join(other) => {
info!("[COMMAND] Join");
// A Join request is issued by a peer during replication and
// provides the peer's latest state.
//
// The join request is handled by joining the provided state
// into the node's current state.
let mut state = self.server_state.borrow_mut();
state.data.join(&other);
if log_enabled!(::log::LogLevel::Debug) {
for elem in state.data.iter() {
debug!(" - {:?}", elem);
}
}
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
}
}
fn poll_ready(&self) -> Async<()> {
Async::Ready(())
}
}
| {
match request {
Request::Get(_) => {
info!("[COMMAND] Get");
// Clone the current state and respond with the set
//
let data = self.server_state.borrow().data.clone();
let resp = Response::Value(data);
Box::new(futures::done(Ok(resp)))
}
Request::Insert(cmd) => {
info!("[COMMAND] Insert {:?}", cmd.value());
// Insert the new value, initiate a replication to all peers,
// and respond with Success
//
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id; | identifier_body |
heap.rs | /// Implements a heap data structure (a.k.a. a priority queue).
///
/// In this implementation, heap is "top-heavy" meaning that the root node is
/// the node with the highest value in the heap. The relative priority of
/// two nodes is determined via the `cmp` function defined over type of the
/// heap's elements (i.e. the generic type `T`).
///
/// The allocated memory used to store the elements of the heap grows (and
/// shrinks) as necessary.
///
/// Method naming conventions generally follow those found in `std::vec::Vec`.
///
/// The heap can contain more than one element with the same priority. No
/// guarantees are made about the order in which elements with equivalent
/// priorities are popped from the queue.
///
/// The data sturcture can be output in Graphviz `.dot` format.
// This data structure is implemented as a vector-backed binary heap. (The
// parent-child relationships are therefore not stored via pointers between
// nodes, but using logical connections between NodeIdx values.
//
// See [Wikipedia](http://en.wikipedia.org/wiki/Heap_%28data_structure%29)
// for overview of this implementation strategy.
//
// A simple C implementation of a binary heap is available from
// [here](https://github.com/dale48/levawc). This code is adapted from Chapter
// 10 of O'Reilly book *Mastering Algorithms with C*. This chapter also served
// as a guide while implementing this module.
extern crate graphviz;
extern crate core;
use std;
use std::ptr;
use std::fmt;
use std::fmt::Debug;
use self::core::borrow::IntoCow;
pub type NodeIdx = usize;
pub struct Heap<T: Ord> {
store: Vec<T>,
}
#[derive(Debug)]
enum ChildType {
Left,
Right
}
fn left_child(i: NodeIdx) -> NodeIdx {
2 * i + 1
}
fn right_child(i: NodeIdx) -> NodeIdx {
2 * i + 2
}
impl<T: Ord> Heap<T> {
/// Creates a new empty heap.
pub fn new() -> Heap<T> {
Heap { store: Vec::new() }
}
/// Creates a new empty heap which has initially allocated enough memory
/// for the given number of elements.
pub fn with_capacity(capacity: usize) -> Heap<T> {
Heap { store: Vec::with_capacity(capacity) }
}
/// Adds the given element to the heap.
pub fn push(&mut self, elem: T) {
let len = self.store.len();
self.store.push(elem);
let insert_idx: NodeIdx = len as NodeIdx;
self.percolate_up(insert_idx);
}
/// Removes from the heap an element with the largest priority of all in
/// the heap. This element is then returned wrapped returns it wrapped in
/// an `Option<T>`. If there are no elements in the heap, then `None` is
/// returned.
pub fn pop(&mut self) -> Option<T> {
match self.store.len() {
0 => None,
1 => self.store.pop(),
_ => {
let rv = self.store.swap_remove(0);
self.percolate_down(0);
Some(rv)
}
}
}
/// Returns the number of elements in the heap.
pub fn len(&self) -> usize {
self.store.len()
}
/// Returns `true` iff there are no elements in the heap.
pub fn empty(&self) -> bool {
self.len() == 0
}
/// Takes the index of a node and returns the index of its parent. Returns
/// `None` if the given node has no such parent (i.e. the given node is
/// the root.
///
/// The function panics if the given index is not valid.
fn parent(&self, idx: NodeIdx) -> Option<NodeIdx> {
if self.is_valid(idx) {
if idx == 0 { None } else { Some((idx - 1) / 2) }
} else {
panic!("Heap.parent({}): given `idx` not in the heap.", idx)
}
}
fn left_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
self.child(ChildType::Left, parent)
}
fn right_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
self.child(ChildType::Right, parent)
}
/// Takes the index of a node and returns the index of indicated child.
/// Returns `None` if the given node has no such child.
///
/// The function panics if the given index is not valid.
fn child(&self, ct: ChildType, parent: NodeIdx) -> Option<NodeIdx> {
if self.is_valid(parent) {
let child: NodeIdx = match ct {
ChildType::Left => left_child(parent),
ChildType::Right => right_child(parent)
};
if child < self.store.len() {
Some(child) }
else {
None
}
} else {
panic!("Heap.child({:?}, {:?}): the given `idx` is not in `Heap`.",
ct, parent)
}
}
/// Starting from the given `NodeIdx`, recursively move an element up the
/// heap until the heap property has been restored all along this node's
/// ancestor path.
fn percolate_up(&mut self, child: NodeIdx) {
let maybe_parent = self.parent(child);
match maybe_parent {
None => {
// Do nothing: The given `child` has no parent because it is
// the root node.
return
},
Some(parent) => {
if self.is_violating(parent, child) {
self.swap(parent, child);
self.percolate_up(parent)
} else {
// Do nothing: the two nodes are already ordered correctly.
return
}
}
}
}
/// Starting from the given `NodeIdx`, recursively move an element down
/// the heap until the heap property has been restored in the entire
/// sub-heap.
///
/// (For the heap property to be restored to the entire sub-heap being
/// re-heapified, the only element which may be violating the heap-property
/// is the node indicated by the given `NodeIdx`.)
fn percolate_down(&mut self, parent: NodeIdx) {
match (self.left_child(parent), self.right_child(parent)) {
(None, None) => return,
(None, Some(right)) => panic!("Heap can't only have right child."),
(Some(left), None) => {
if self.is_violating(parent, left) {
self.swap_down(parent, left)
}
},
(Some(left), Some(right)) => {
match (self.is_violating(parent, left),
self.is_violating(parent, right)) {
(false, false) => return,
(false, true) => self.swap_down(parent, right),
(true, false) => self.swap_down(parent, left),
(true, true) => {
// Since both of the parent's children are violating
// the heap property, choose which child should be
// swapped with the parent, such that the heap property
// will not be violated after the swap. (That is, the
// greater of the two will need to become the parent of
// the other.)
if self.store[left] >= self.store[right] {
self.swap_down(parent, left)
} else {
self.swap_down(parent, right)
}
}
}
}
}
}
/// Helper function for `percolate_down()`.
fn swap_down(&mut self, parent: NodeIdx, child: NodeIdx) {
self.swap(parent, child);
self.percolate_down(child);
}
/// Checks to see whether the given parent-child nodes are violating the
/// heap property.
///
/// Panics if either index is out of bounds. Panics if the given parent is
/// not actually the parent of the given child.
fn is_violating(&self, parent: NodeIdx, child: NodeIdx) -> bool{
if parent == self.parent(child).unwrap() {
self.store[parent] < self.store[child]
} else {
panic!("Given parent is not actually the parent of this child.")
}
}
fn is_valid(&self, idx: NodeIdx) -> bool {
idx < self.store.len()
}
/// Swaps the data stored at the two inciated heap nodes.
///
/// Does nothing if the two indices are the same. Panics if either index is
/// invalid.
fn swap(&mut self, a: NodeIdx, b: NodeIdx) {
if a!= b {
unsafe {
let pa: *mut T = &mut self.store[a];
let pb: *mut T = &mut self.store[b];
ptr::swap(pa, pb);
}
}
}
}
pub type Edge = (NodeIdx, NodeIdx);
impl<'a, T: Ord + 'a> graphviz::GraphWalk<'a, NodeIdx, Edge> for Heap<T> {
fn nodes(&self) -> graphviz::Nodes<'a, NodeIdx> {
let mut v: Vec<NodeIdx> = Vec::new();
for node_idx in (0..self.len()) {
v.push(node_idx);
}
v.into_cow()
}
fn edges(&'a self) -> graphviz::Edges<'a, Edge> {
let mut v: Vec<Edge> = Vec::with_capacity(2 * self.len());
// Add an edge for each parent-child relationship in the heap.
for idx in (0..self.len()) {
match self.left_child(idx) {
Some(l) => v.push((idx, l)),
None => ()
};
match self.right_child(idx) {
Some(r) => v.push((idx, r)),
None => ()
};
}
v.into_cow()
}
fn source(&self, edge: &Edge) -> NodeIdx {
let &(s, _) = edge;
s
}
fn target(&self, edge: &Edge) -> NodeIdx {
let &(_, t) = edge;
t
}
}
impl<'a, T: 'a + Ord + fmt::Debug> graphviz::Labeller<'a, NodeIdx, Edge> for Heap<T> {
fn graph_id(&'a self) -> graphviz::Id<'a> {
graphviz::Id::new("Heap").unwrap()
}
fn node_id(&'a self, n: &NodeIdx) -> graphviz::Id<'a> {
graphviz::Id::new(format!("n{}", n)).unwrap()
}
fn node_label(&'a self, n: &NodeIdx) -> graphviz::LabelText<'a> |
}
| {
let label = format!("{:?}", self.store[*n]);
graphviz::LabelText::LabelStr(label.into_cow())
} | identifier_body |
heap.rs | /// Implements a heap data structure (a.k.a. a priority queue).
///
/// In this implementation, heap is "top-heavy" meaning that the root node is
/// the node with the highest value in the heap. The relative priority of
/// two nodes is determined via the `cmp` function defined over type of the
/// heap's elements (i.e. the generic type `T`).
///
/// The allocated memory used to store the elements of the heap grows (and
/// shrinks) as necessary.
///
/// Method naming conventions generally follow those found in `std::vec::Vec`.
///
/// The heap can contain more than one element with the same priority. No
/// guarantees are made about the order in which elements with equivalent
/// priorities are popped from the queue.
///
/// The data sturcture can be output in Graphviz `.dot` format.
// This data structure is implemented as a vector-backed binary heap. (The
// parent-child relationships are therefore not stored via pointers between
// nodes, but using logical connections between NodeIdx values.
//
// See [Wikipedia](http://en.wikipedia.org/wiki/Heap_%28data_structure%29)
// for overview of this implementation strategy.
//
// A simple C implementation of a binary heap is available from
// [here](https://github.com/dale48/levawc). This code is adapted from Chapter
// 10 of O'Reilly book *Mastering Algorithms with C*. This chapter also served
// as a guide while implementing this module.
extern crate graphviz;
extern crate core;
use std;
use std::ptr;
use std::fmt;
use std::fmt::Debug; | store: Vec<T>,
}
#[derive(Debug)]
enum ChildType {
Left,
Right
}
fn left_child(i: NodeIdx) -> NodeIdx {
2 * i + 1
}
fn right_child(i: NodeIdx) -> NodeIdx {
2 * i + 2
}
impl<T: Ord> Heap<T> {
/// Creates a new empty heap.
pub fn new() -> Heap<T> {
Heap { store: Vec::new() }
}
/// Creates a new empty heap which has initially allocated enough memory
/// for the given number of elements.
pub fn with_capacity(capacity: usize) -> Heap<T> {
Heap { store: Vec::with_capacity(capacity) }
}
/// Adds the given element to the heap.
pub fn push(&mut self, elem: T) {
let len = self.store.len();
self.store.push(elem);
let insert_idx: NodeIdx = len as NodeIdx;
self.percolate_up(insert_idx);
}
/// Removes from the heap an element with the largest priority of all in
/// the heap. This element is then returned wrapped returns it wrapped in
/// an `Option<T>`. If there are no elements in the heap, then `None` is
/// returned.
pub fn pop(&mut self) -> Option<T> {
match self.store.len() {
0 => None,
1 => self.store.pop(),
_ => {
let rv = self.store.swap_remove(0);
self.percolate_down(0);
Some(rv)
}
}
}
/// Returns the number of elements in the heap.
pub fn len(&self) -> usize {
self.store.len()
}
/// Returns `true` iff there are no elements in the heap.
pub fn empty(&self) -> bool {
self.len() == 0
}
/// Takes the index of a node and returns the index of its parent. Returns
/// `None` if the given node has no such parent (i.e. the given node is
/// the root.
///
/// The function panics if the given index is not valid.
fn parent(&self, idx: NodeIdx) -> Option<NodeIdx> {
if self.is_valid(idx) {
if idx == 0 { None } else { Some((idx - 1) / 2) }
} else {
panic!("Heap.parent({}): given `idx` not in the heap.", idx)
}
}
fn left_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
self.child(ChildType::Left, parent)
}
fn right_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
self.child(ChildType::Right, parent)
}
/// Takes the index of a node and returns the index of indicated child.
/// Returns `None` if the given node has no such child.
///
/// The function panics if the given index is not valid.
fn child(&self, ct: ChildType, parent: NodeIdx) -> Option<NodeIdx> {
if self.is_valid(parent) {
let child: NodeIdx = match ct {
ChildType::Left => left_child(parent),
ChildType::Right => right_child(parent)
};
if child < self.store.len() {
Some(child) }
else {
None
}
} else {
panic!("Heap.child({:?}, {:?}): the given `idx` is not in `Heap`.",
ct, parent)
}
}
/// Starting from the given `NodeIdx`, recursively move an element up the
/// heap until the heap property has been restored all along this node's
/// ancestor path.
fn percolate_up(&mut self, child: NodeIdx) {
let maybe_parent = self.parent(child);
match maybe_parent {
None => {
// Do nothing: The given `child` has no parent because it is
// the root node.
return
},
Some(parent) => {
if self.is_violating(parent, child) {
self.swap(parent, child);
self.percolate_up(parent)
} else {
// Do nothing: the two nodes are already ordered correctly.
return
}
}
}
}
/// Starting from the given `NodeIdx`, recursively move an element down
/// the heap until the heap property has been restored in the entire
/// sub-heap.
///
/// (For the heap property to be restored to the entire sub-heap being
/// re-heapified, the only element which may be violating the heap-property
/// is the node indicated by the given `NodeIdx`.)
fn percolate_down(&mut self, parent: NodeIdx) {
match (self.left_child(parent), self.right_child(parent)) {
(None, None) => return,
(None, Some(right)) => panic!("Heap can't only have right child."),
(Some(left), None) => {
if self.is_violating(parent, left) {
self.swap_down(parent, left)
}
},
(Some(left), Some(right)) => {
match (self.is_violating(parent, left),
self.is_violating(parent, right)) {
(false, false) => return,
(false, true) => self.swap_down(parent, right),
(true, false) => self.swap_down(parent, left),
(true, true) => {
// Since both of the parent's children are violating
// the heap property, choose which child should be
// swapped with the parent, such that the heap property
// will not be violated after the swap. (That is, the
// greater of the two will need to become the parent of
// the other.)
if self.store[left] >= self.store[right] {
self.swap_down(parent, left)
} else {
self.swap_down(parent, right)
}
}
}
}
}
}
/// Helper function for `percolate_down()`.
fn swap_down(&mut self, parent: NodeIdx, child: NodeIdx) {
self.swap(parent, child);
self.percolate_down(child);
}
/// Checks to see whether the given parent-child nodes are violating the
/// heap property.
///
/// Panics if either index is out of bounds. Panics if the given parent is
/// not actually the parent of the given child.
fn is_violating(&self, parent: NodeIdx, child: NodeIdx) -> bool{
if parent == self.parent(child).unwrap() {
self.store[parent] < self.store[child]
} else {
panic!("Given parent is not actually the parent of this child.")
}
}
fn is_valid(&self, idx: NodeIdx) -> bool {
idx < self.store.len()
}
/// Swaps the data stored at the two inciated heap nodes.
///
/// Does nothing if the two indices are the same. Panics if either index is
/// invalid.
fn swap(&mut self, a: NodeIdx, b: NodeIdx) {
if a!= b {
unsafe {
let pa: *mut T = &mut self.store[a];
let pb: *mut T = &mut self.store[b];
ptr::swap(pa, pb);
}
}
}
}
pub type Edge = (NodeIdx, NodeIdx);
impl<'a, T: Ord + 'a> graphviz::GraphWalk<'a, NodeIdx, Edge> for Heap<T> {
fn nodes(&self) -> graphviz::Nodes<'a, NodeIdx> {
let mut v: Vec<NodeIdx> = Vec::new();
for node_idx in (0..self.len()) {
v.push(node_idx);
}
v.into_cow()
}
fn edges(&'a self) -> graphviz::Edges<'a, Edge> {
let mut v: Vec<Edge> = Vec::with_capacity(2 * self.len());
// Add an edge for each parent-child relationship in the heap.
for idx in (0..self.len()) {
match self.left_child(idx) {
Some(l) => v.push((idx, l)),
None => ()
};
match self.right_child(idx) {
Some(r) => v.push((idx, r)),
None => ()
};
}
v.into_cow()
}
fn source(&self, edge: &Edge) -> NodeIdx {
let &(s, _) = edge;
s
}
fn target(&self, edge: &Edge) -> NodeIdx {
let &(_, t) = edge;
t
}
}
impl<'a, T: 'a + Ord + fmt::Debug> graphviz::Labeller<'a, NodeIdx, Edge> for Heap<T> {
fn graph_id(&'a self) -> graphviz::Id<'a> {
graphviz::Id::new("Heap").unwrap()
}
fn node_id(&'a self, n: &NodeIdx) -> graphviz::Id<'a> {
graphviz::Id::new(format!("n{}", n)).unwrap()
}
fn node_label(&'a self, n: &NodeIdx) -> graphviz::LabelText<'a> {
let label = format!("{:?}", self.store[*n]);
graphviz::LabelText::LabelStr(label.into_cow())
}
} | use self::core::borrow::IntoCow;
pub type NodeIdx = usize;
pub struct Heap<T: Ord> { | random_line_split |
heap.rs | /// Implements a heap data structure (a.k.a. a priority queue).
///
/// In this implementation, heap is "top-heavy" meaning that the root node is
/// the node with the highest value in the heap. The relative priority of
/// two nodes is determined via the `cmp` function defined over type of the
/// heap's elements (i.e. the generic type `T`).
///
/// The allocated memory used to store the elements of the heap grows (and
/// shrinks) as necessary.
///
/// Method naming conventions generally follow those found in `std::vec::Vec`.
///
/// The heap can contain more than one element with the same priority. No
/// guarantees are made about the order in which elements with equivalent
/// priorities are popped from the queue.
///
/// The data sturcture can be output in Graphviz `.dot` format.
// This data structure is implemented as a vector-backed binary heap. (The
// parent-child relationships are therefore not stored via pointers between
// nodes, but using logical connections between NodeIdx values.
//
// See [Wikipedia](http://en.wikipedia.org/wiki/Heap_%28data_structure%29)
// for overview of this implementation strategy.
//
// A simple C implementation of a binary heap is available from
// [here](https://github.com/dale48/levawc). This code is adapted from Chapter
// 10 of O'Reilly book *Mastering Algorithms with C*. This chapter also served
// as a guide while implementing this module.
extern crate graphviz;
extern crate core;
use std;
use std::ptr;
use std::fmt;
use std::fmt::Debug;
use self::core::borrow::IntoCow;
pub type NodeIdx = usize;
pub struct Heap<T: Ord> {
store: Vec<T>,
}
#[derive(Debug)]
enum ChildType {
Left,
Right
}
fn left_child(i: NodeIdx) -> NodeIdx {
2 * i + 1
}
fn right_child(i: NodeIdx) -> NodeIdx {
2 * i + 2
}
impl<T: Ord> Heap<T> {
/// Creates a new empty heap.
pub fn new() -> Heap<T> {
Heap { store: Vec::new() }
}
/// Creates a new empty heap which has initially allocated enough memory
/// for the given number of elements.
pub fn with_capacity(capacity: usize) -> Heap<T> {
Heap { store: Vec::with_capacity(capacity) }
}
/// Adds the given element to the heap.
pub fn push(&mut self, elem: T) {
let len = self.store.len();
self.store.push(elem);
let insert_idx: NodeIdx = len as NodeIdx;
self.percolate_up(insert_idx);
}
/// Removes from the heap an element with the largest priority of all in
/// the heap. This element is then returned wrapped returns it wrapped in
/// an `Option<T>`. If there are no elements in the heap, then `None` is
/// returned.
pub fn pop(&mut self) -> Option<T> {
match self.store.len() {
0 => None,
1 => self.store.pop(),
_ => {
let rv = self.store.swap_remove(0);
self.percolate_down(0);
Some(rv)
}
}
}
/// Returns the number of elements in the heap.
pub fn len(&self) -> usize {
self.store.len()
}
/// Returns `true` iff there are no elements in the heap.
pub fn empty(&self) -> bool {
self.len() == 0
}
/// Takes the index of a node and returns the index of its parent. Returns
/// `None` if the given node has no such parent (i.e. the given node is
/// the root.
///
/// The function panics if the given index is not valid.
fn parent(&self, idx: NodeIdx) -> Option<NodeIdx> {
if self.is_valid(idx) {
if idx == 0 | else { Some((idx - 1) / 2) }
} else {
panic!("Heap.parent({}): given `idx` not in the heap.", idx)
}
}
fn left_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
self.child(ChildType::Left, parent)
}
fn right_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
self.child(ChildType::Right, parent)
}
/// Takes the index of a node and returns the index of indicated child.
/// Returns `None` if the given node has no such child.
///
/// The function panics if the given index is not valid.
fn child(&self, ct: ChildType, parent: NodeIdx) -> Option<NodeIdx> {
if self.is_valid(parent) {
let child: NodeIdx = match ct {
ChildType::Left => left_child(parent),
ChildType::Right => right_child(parent)
};
if child < self.store.len() {
Some(child) }
else {
None
}
} else {
panic!("Heap.child({:?}, {:?}): the given `idx` is not in `Heap`.",
ct, parent)
}
}
/// Starting from the given `NodeIdx`, recursively move an element up the
/// heap until the heap property has been restored all along this node's
/// ancestor path.
fn percolate_up(&mut self, child: NodeIdx) {
let maybe_parent = self.parent(child);
match maybe_parent {
None => {
// Do nothing: The given `child` has no parent because it is
// the root node.
return
},
Some(parent) => {
if self.is_violating(parent, child) {
self.swap(parent, child);
self.percolate_up(parent)
} else {
// Do nothing: the two nodes are already ordered correctly.
return
}
}
}
}
/// Starting from the given `NodeIdx`, recursively move an element down
/// the heap until the heap property has been restored in the entire
/// sub-heap.
///
/// (For the heap property to be restored to the entire sub-heap being
/// re-heapified, the only element which may be violating the heap-property
/// is the node indicated by the given `NodeIdx`.)
fn percolate_down(&mut self, parent: NodeIdx) {
match (self.left_child(parent), self.right_child(parent)) {
(None, None) => return,
(None, Some(right)) => panic!("Heap can't only have right child."),
(Some(left), None) => {
if self.is_violating(parent, left) {
self.swap_down(parent, left)
}
},
(Some(left), Some(right)) => {
match (self.is_violating(parent, left),
self.is_violating(parent, right)) {
(false, false) => return,
(false, true) => self.swap_down(parent, right),
(true, false) => self.swap_down(parent, left),
(true, true) => {
// Since both of the parent's children are violating
// the heap property, choose which child should be
// swapped with the parent, such that the heap property
// will not be violated after the swap. (That is, the
// greater of the two will need to become the parent of
// the other.)
if self.store[left] >= self.store[right] {
self.swap_down(parent, left)
} else {
self.swap_down(parent, right)
}
}
}
}
}
}
/// Helper function for `percolate_down()`.
fn swap_down(&mut self, parent: NodeIdx, child: NodeIdx) {
self.swap(parent, child);
self.percolate_down(child);
}
/// Checks to see whether the given parent-child nodes are violating the
/// heap property.
///
/// Panics if either index is out of bounds. Panics if the given parent is
/// not actually the parent of the given child.
fn is_violating(&self, parent: NodeIdx, child: NodeIdx) -> bool{
if parent == self.parent(child).unwrap() {
self.store[parent] < self.store[child]
} else {
panic!("Given parent is not actually the parent of this child.")
}
}
fn is_valid(&self, idx: NodeIdx) -> bool {
idx < self.store.len()
}
/// Swaps the data stored at the two inciated heap nodes.
///
/// Does nothing if the two indices are the same. Panics if either index is
/// invalid.
fn swap(&mut self, a: NodeIdx, b: NodeIdx) {
if a!= b {
unsafe {
let pa: *mut T = &mut self.store[a];
let pb: *mut T = &mut self.store[b];
ptr::swap(pa, pb);
}
}
}
}
pub type Edge = (NodeIdx, NodeIdx);
impl<'a, T: Ord + 'a> graphviz::GraphWalk<'a, NodeIdx, Edge> for Heap<T> {
fn nodes(&self) -> graphviz::Nodes<'a, NodeIdx> {
let mut v: Vec<NodeIdx> = Vec::new();
for node_idx in (0..self.len()) {
v.push(node_idx);
}
v.into_cow()
}
fn edges(&'a self) -> graphviz::Edges<'a, Edge> {
let mut v: Vec<Edge> = Vec::with_capacity(2 * self.len());
// Add an edge for each parent-child relationship in the heap.
for idx in (0..self.len()) {
match self.left_child(idx) {
Some(l) => v.push((idx, l)),
None => ()
};
match self.right_child(idx) {
Some(r) => v.push((idx, r)),
None => ()
};
}
v.into_cow()
}
fn source(&self, edge: &Edge) -> NodeIdx {
let &(s, _) = edge;
s
}
fn target(&self, edge: &Edge) -> NodeIdx {
let &(_, t) = edge;
t
}
}
impl<'a, T: 'a + Ord + fmt::Debug> graphviz::Labeller<'a, NodeIdx, Edge> for Heap<T> {
fn graph_id(&'a self) -> graphviz::Id<'a> {
graphviz::Id::new("Heap").unwrap()
}
fn node_id(&'a self, n: &NodeIdx) -> graphviz::Id<'a> {
graphviz::Id::new(format!("n{}", n)).unwrap()
}
fn node_label(&'a self, n: &NodeIdx) -> graphviz::LabelText<'a> {
let label = format!("{:?}", self.store[*n]);
graphviz::LabelText::LabelStr(label.into_cow())
}
}
| { None } | conditional_block |
heap.rs | /// Implements a heap data structure (a.k.a. a priority queue).
///
/// In this implementation, heap is "top-heavy" meaning that the root node is
/// the node with the highest value in the heap. The relative priority of
/// two nodes is determined via the `cmp` function defined over type of the
/// heap's elements (i.e. the generic type `T`).
///
/// The allocated memory used to store the elements of the heap grows (and
/// shrinks) as necessary.
///
/// Method naming conventions generally follow those found in `std::vec::Vec`.
///
/// The heap can contain more than one element with the same priority. No
/// guarantees are made about the order in which elements with equivalent
/// priorities are popped from the queue.
///
/// The data sturcture can be output in Graphviz `.dot` format.
// This data structure is implemented as a vector-backed binary heap. (The
// parent-child relationships are therefore not stored via pointers between
// nodes, but using logical connections between NodeIdx values.
//
// See [Wikipedia](http://en.wikipedia.org/wiki/Heap_%28data_structure%29)
// for overview of this implementation strategy.
//
// A simple C implementation of a binary heap is available from
// [here](https://github.com/dale48/levawc). This code is adapted from Chapter
// 10 of O'Reilly book *Mastering Algorithms with C*. This chapter also served
// as a guide while implementing this module.
extern crate graphviz;
extern crate core;
use std;
use std::ptr;
use std::fmt;
use std::fmt::Debug;
use self::core::borrow::IntoCow;
pub type NodeIdx = usize;
pub struct Heap<T: Ord> {
store: Vec<T>,
}
#[derive(Debug)]
enum ChildType {
Left,
Right
}
fn left_child(i: NodeIdx) -> NodeIdx {
2 * i + 1
}
fn right_child(i: NodeIdx) -> NodeIdx {
2 * i + 2
}
impl<T: Ord> Heap<T> {
/// Creates a new empty heap.
pub fn new() -> Heap<T> {
Heap { store: Vec::new() }
}
/// Creates a new empty heap which has initially allocated enough memory
/// for the given number of elements.
pub fn with_capacity(capacity: usize) -> Heap<T> {
Heap { store: Vec::with_capacity(capacity) }
}
/// Adds the given element to the heap.
pub fn push(&mut self, elem: T) {
let len = self.store.len();
self.store.push(elem);
let insert_idx: NodeIdx = len as NodeIdx;
self.percolate_up(insert_idx);
}
/// Removes from the heap an element with the largest priority of all in
/// the heap. This element is then returned wrapped returns it wrapped in
/// an `Option<T>`. If there are no elements in the heap, then `None` is
/// returned.
pub fn pop(&mut self) -> Option<T> {
match self.store.len() {
0 => None,
1 => self.store.pop(),
_ => {
let rv = self.store.swap_remove(0);
self.percolate_down(0);
Some(rv)
}
}
}
/// Returns the number of elements in the heap.
pub fn len(&self) -> usize {
self.store.len()
}
/// Returns `true` iff there are no elements in the heap.
pub fn | (&self) -> bool {
self.len() == 0
}
/// Takes the index of a node and returns the index of its parent. Returns
/// `None` if the given node has no such parent (i.e. the given node is
/// the root.
///
/// The function panics if the given index is not valid.
fn parent(&self, idx: NodeIdx) -> Option<NodeIdx> {
if self.is_valid(idx) {
if idx == 0 { None } else { Some((idx - 1) / 2) }
} else {
panic!("Heap.parent({}): given `idx` not in the heap.", idx)
}
}
fn left_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
self.child(ChildType::Left, parent)
}
fn right_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
self.child(ChildType::Right, parent)
}
/// Takes the index of a node and returns the index of indicated child.
/// Returns `None` if the given node has no such child.
///
/// The function panics if the given index is not valid.
fn child(&self, ct: ChildType, parent: NodeIdx) -> Option<NodeIdx> {
if self.is_valid(parent) {
let child: NodeIdx = match ct {
ChildType::Left => left_child(parent),
ChildType::Right => right_child(parent)
};
if child < self.store.len() {
Some(child) }
else {
None
}
} else {
panic!("Heap.child({:?}, {:?}): the given `idx` is not in `Heap`.",
ct, parent)
}
}
/// Starting from the given `NodeIdx`, recursively move an element up the
/// heap until the heap property has been restored all along this node's
/// ancestor path.
fn percolate_up(&mut self, child: NodeIdx) {
let maybe_parent = self.parent(child);
match maybe_parent {
None => {
// Do nothing: The given `child` has no parent because it is
// the root node.
return
},
Some(parent) => {
if self.is_violating(parent, child) {
self.swap(parent, child);
self.percolate_up(parent)
} else {
// Do nothing: the two nodes are already ordered correctly.
return
}
}
}
}
/// Starting from the given `NodeIdx`, recursively move an element down
/// the heap until the heap property has been restored in the entire
/// sub-heap.
///
/// (For the heap property to be restored to the entire sub-heap being
/// re-heapified, the only element which may be violating the heap-property
/// is the node indicated by the given `NodeIdx`.)
fn percolate_down(&mut self, parent: NodeIdx) {
match (self.left_child(parent), self.right_child(parent)) {
(None, None) => return,
(None, Some(right)) => panic!("Heap can't only have right child."),
(Some(left), None) => {
if self.is_violating(parent, left) {
self.swap_down(parent, left)
}
},
(Some(left), Some(right)) => {
match (self.is_violating(parent, left),
self.is_violating(parent, right)) {
(false, false) => return,
(false, true) => self.swap_down(parent, right),
(true, false) => self.swap_down(parent, left),
(true, true) => {
// Since both of the parent's children are violating
// the heap property, choose which child should be
// swapped with the parent, such that the heap property
// will not be violated after the swap. (That is, the
// greater of the two will need to become the parent of
// the other.)
if self.store[left] >= self.store[right] {
self.swap_down(parent, left)
} else {
self.swap_down(parent, right)
}
}
}
}
}
}
/// Helper function for `percolate_down()`.
fn swap_down(&mut self, parent: NodeIdx, child: NodeIdx) {
self.swap(parent, child);
self.percolate_down(child);
}
/// Checks to see whether the given parent-child nodes are violating the
/// heap property.
///
/// Panics if either index is out of bounds. Panics if the given parent is
/// not actually the parent of the given child.
fn is_violating(&self, parent: NodeIdx, child: NodeIdx) -> bool{
if parent == self.parent(child).unwrap() {
self.store[parent] < self.store[child]
} else {
panic!("Given parent is not actually the parent of this child.")
}
}
fn is_valid(&self, idx: NodeIdx) -> bool {
idx < self.store.len()
}
/// Swaps the data stored at the two inciated heap nodes.
///
/// Does nothing if the two indices are the same. Panics if either index is
/// invalid.
fn swap(&mut self, a: NodeIdx, b: NodeIdx) {
if a!= b {
unsafe {
let pa: *mut T = &mut self.store[a];
let pb: *mut T = &mut self.store[b];
ptr::swap(pa, pb);
}
}
}
}
pub type Edge = (NodeIdx, NodeIdx);
impl<'a, T: Ord + 'a> graphviz::GraphWalk<'a, NodeIdx, Edge> for Heap<T> {
fn nodes(&self) -> graphviz::Nodes<'a, NodeIdx> {
let mut v: Vec<NodeIdx> = Vec::new();
for node_idx in (0..self.len()) {
v.push(node_idx);
}
v.into_cow()
}
fn edges(&'a self) -> graphviz::Edges<'a, Edge> {
let mut v: Vec<Edge> = Vec::with_capacity(2 * self.len());
// Add an edge for each parent-child relationship in the heap.
for idx in (0..self.len()) {
match self.left_child(idx) {
Some(l) => v.push((idx, l)),
None => ()
};
match self.right_child(idx) {
Some(r) => v.push((idx, r)),
None => ()
};
}
v.into_cow()
}
fn source(&self, edge: &Edge) -> NodeIdx {
let &(s, _) = edge;
s
}
fn target(&self, edge: &Edge) -> NodeIdx {
let &(_, t) = edge;
t
}
}
impl<'a, T: 'a + Ord + fmt::Debug> graphviz::Labeller<'a, NodeIdx, Edge> for Heap<T> {
fn graph_id(&'a self) -> graphviz::Id<'a> {
graphviz::Id::new("Heap").unwrap()
}
fn node_id(&'a self, n: &NodeIdx) -> graphviz::Id<'a> {
graphviz::Id::new(format!("n{}", n)).unwrap()
}
fn node_label(&'a self, n: &NodeIdx) -> graphviz::LabelText<'a> {
let label = format!("{:?}", self.store[*n]);
graphviz::LabelText::LabelStr(label.into_cow())
}
}
| empty | identifier_name |
pit.rs | //! Periodic interrupt timer (PIT) driver and futures
//!
//! The PIT timer channels are the most precise timers in the HAL. PIT timers run on the periodic clock
//! frequency.
//!
//! A single hardware PIT instance has four PIT channels. Use [`new`](PIT::new()) to acquire these four
//! channels.
//!
//! # Example
//!
//! Delay for 250ms using PIT channel 3.
//!
//! ```no_run
//! use imxrt_async_hal as hal;
//! use hal::ral;
//! use hal::PIT;
//!
//! let ccm = ral::ccm::CCM::take().unwrap(); | //! let (_, _, _, mut pit) = ral::pit::PIT::take()
//! .map(PIT::new)
//! .unwrap();
//!
//! # async {
//! pit.delay(250_000).await;
//! # };
//! ```
use crate::ral;
use core::{
future::Future,
marker::PhantomPinned,
pin::Pin,
sync::atomic,
task::{Context, Poll, Waker},
};
/// Periodic interrupt timer (PIT)
///
/// See the [module-level documentation](crate::pit) for more information.
#[cfg_attr(docsrs, doc(cfg(feature = "pit")))]
pub struct PIT {
channel: register::ChannelInstance,
}
impl PIT {
/// Acquire four PIT channels from the RAL's PIT instance
pub fn new(pit: ral::pit::Instance) -> (PIT, PIT, PIT, PIT) {
ral::write_reg!(ral::pit, pit, MCR, MDIS: MDIS_0);
// Reset all PIT channels
//
// PIT channels may be used by a systems boot ROM, or another
// user. Set them to a known, good state.
ral::write_reg!(ral::pit, pit, TCTRL0, 0);
ral::write_reg!(ral::pit, pit, TCTRL1, 0);
ral::write_reg!(ral::pit, pit, TCTRL2, 0);
ral::write_reg!(ral::pit, pit, TCTRL3, 0);
unsafe {
cortex_m::peripheral::NVIC::unmask(crate::ral::interrupt::PIT);
(
PIT {
channel: register::ChannelInstance::zero(),
},
PIT {
channel: register::ChannelInstance::one(),
},
PIT {
channel: register::ChannelInstance::two(),
},
PIT {
channel: register::ChannelInstance::three(),
},
)
}
}
/// Wait for the counts to elapse
///
/// The elapsed time is a function of your clock selection and clock frequency.
pub fn delay(&mut self, count: u32) -> Delay<'_> {
Delay {
channel: &mut self.channel,
count,
_pin: PhantomPinned,
}
}
}
static mut WAKERS: [Option<Waker>; 4] = [None, None, None, None];
/// A future that yields once the PIT timer elapses
pub struct Delay<'a> {
channel: &'a mut register::ChannelInstance,
_pin: PhantomPinned,
count: u32,
}
impl<'a> Future for Delay<'a> {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let count = self.count;
// Safety: future is safely Unpin; only exposed as!Unpin, just in case.
let this = unsafe { Pin::into_inner_unchecked(self) };
poll_delay(&mut this.channel, cx, count)
}
}
fn poll_delay(
channel: &mut register::ChannelInstance,
cx: &mut Context<'_>,
count: u32,
) -> Poll<()> {
if ral::read_reg!(register, channel, TFLG, TIF == 1) {
// Complete! W1C
ral::write_reg!(register, channel, TFLG, TIF: 1);
Poll::Ready(())
} else if ral::read_reg!(register, channel, TCTRL)!= 0 {
// We're active; do nothing
Poll::Pending
} else {
// Neither complete nor active; prepare to run
ral::write_reg!(register, channel, LDVAL, count);
unsafe {
WAKERS[channel.index()] = Some(cx.waker().clone());
}
atomic::compiler_fence(atomic::Ordering::SeqCst);
ral::modify_reg!(register, channel, TCTRL, TIE: 1);
ral::modify_reg!(register, channel, TCTRL, TEN: 1);
Poll::Pending
}
}
impl<'a> Drop for Delay<'a> {
fn drop(&mut self) {
poll_cancel(&mut self.channel);
}
}
fn poll_cancel(channel: &mut register::ChannelInstance) {
ral::write_reg!(register, channel, TCTRL, 0);
}
interrupts! {
handler!{unsafe fn PIT() {
use register::ChannelInstance;
[
ChannelInstance::zero(),
ChannelInstance::one(),
ChannelInstance::two(),
ChannelInstance::three(),
]
.iter_mut()
.zip(WAKERS.iter_mut())
.filter(|(channel, _)| ral::read_reg!(register, channel, TFLG, TIF == 1))
.for_each(|(channel, waker)| {
ral::write_reg!(register, channel, TCTRL, 0);
if let Some(waker) = waker.take() {
waker.wake();
}
});
}}
}
/// The auto-generated RAL API is cumbersome. This is a macro-compatible API that makes it
/// easier to work with.
///
/// The approach here is to
///
/// - take the RAL flags, and remove the channel number (copy-paste from RAL)
/// - expose a 'Channel' as a collection of PIT channel registers (copy-paste from RAL)
mod register {
#![allow(unused, non_snake_case, non_upper_case_globals)] // Compatibility with RAL
use crate::ral::{RORegister, RWRegister};
#[repr(C)]
pub struct ChannelRegisterBlock {
/// Timer Load Value Register
pub LDVAL: RWRegister<u32>,
/// Current Timer Value Register
pub CVAL: RORegister<u32>,
/// Timer Control Register
pub TCTRL: RWRegister<u32>,
/// Timer Flag Register
pub TFLG: RWRegister<u32>,
}
pub struct ChannelInstance {
addr: u32,
idx: usize,
_marker: ::core::marker::PhantomData<*const ChannelRegisterBlock>,
}
impl ::core::ops::Deref for ChannelInstance {
type Target = ChannelRegisterBlock;
#[inline(always)]
fn deref(&self) -> &ChannelRegisterBlock {
unsafe { &*(self.addr as *const _) }
}
}
const PIT_BASE_ADDRESS: u32 = 0x4008_4000;
const PIT_CHANNEL_0_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x100;
const PIT_CHANNEL_1_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x110;
const PIT_CHANNEL_2_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x120;
const PIT_CHANNEL_3_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x130;
impl ChannelInstance {
const unsafe fn new(addr: u32, idx: usize) -> Self {
ChannelInstance {
addr,
idx,
_marker: core::marker::PhantomData,
}
}
pub const fn index(&self) -> usize {
self.idx
}
pub const unsafe fn zero() -> Self {
Self::new(PIT_CHANNEL_0_ADDRESS, 0)
}
pub const unsafe fn one() -> Self {
Self::new(PIT_CHANNEL_1_ADDRESS, 1)
}
pub const unsafe fn two() -> Self {
Self::new(PIT_CHANNEL_2_ADDRESS, 2)
}
pub const unsafe fn three() -> Self {
Self::new(PIT_CHANNEL_3_ADDRESS, 3)
}
}
/// Timer Load Value Register
pub mod LDVAL {
/// Timer Start Value
pub mod TSV {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (32 bits: 0xffffffff << 0)
pub const mask: u32 = 0xffffffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Current Timer Value Register
pub mod CVAL {
/// Current Timer Value
pub mod TVL {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (32 bits: 0xffffffff << 0)
pub const mask: u32 = 0xffffffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timer Control Register
pub mod TCTRL {
/// Timer Enable
pub mod TEN {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timer n is disabled.
pub const TEN_0: u32 = 0b0;
/// 0b1: Timer n is enabled.
pub const TEN_1: u32 = 0b1;
}
}
/// Timer Interrupt Enable
pub mod TIE {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Interrupt requests from Timer n are disabled.
pub const TIE_0: u32 = 0b0;
/// 0b1: Interrupt will be requested whenever TIF is set.
pub const TIE_1: u32 = 0b1;
}
}
/// Chain Mode
pub mod CHN {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timer is not chained.
pub const CHN_0: u32 = 0b0;
/// 0b1: Timer is chained to previous timer. For example, for Channel 2, if this field is set, Timer 2 is chained to Timer 1.
pub const CHN_1: u32 = 0b1;
}
}
}
/// Timer Flag Register
pub mod TFLG {
/// Timer Interrupt Flag
pub mod TIF {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timeout has not yet occurred.
pub const TIF_0: u32 = 0b0;
/// 0b1: Timeout has occurred.
pub const TIF_1: u32 = 0b1;
}
}
}
} | //! // Select 24MHz crystal oscillator, divide by 24 == 1MHz clock
//! ral::modify_reg!(ral::ccm, ccm, CSCMR1, PERCLK_PODF: DIVIDE_24, PERCLK_CLK_SEL: 1);
//! // Enable PIT clock gate
//! ral::modify_reg!(ral::ccm, ccm, CCGR1, CG6: 0b11); | random_line_split |
pit.rs | //! Periodic interrupt timer (PIT) driver and futures
//!
//! The PIT timer channels are the most precise timers in the HAL. PIT timers run on the periodic clock
//! frequency.
//!
//! A single hardware PIT instance has four PIT channels. Use [`new`](PIT::new()) to acquire these four
//! channels.
//!
//! # Example
//!
//! Delay for 250ms using PIT channel 3.
//!
//! ```no_run
//! use imxrt_async_hal as hal;
//! use hal::ral;
//! use hal::PIT;
//!
//! let ccm = ral::ccm::CCM::take().unwrap();
//! // Select 24MHz crystal oscillator, divide by 24 == 1MHz clock
//! ral::modify_reg!(ral::ccm, ccm, CSCMR1, PERCLK_PODF: DIVIDE_24, PERCLK_CLK_SEL: 1);
//! // Enable PIT clock gate
//! ral::modify_reg!(ral::ccm, ccm, CCGR1, CG6: 0b11);
//! let (_, _, _, mut pit) = ral::pit::PIT::take()
//! .map(PIT::new)
//! .unwrap();
//!
//! # async {
//! pit.delay(250_000).await;
//! # };
//! ```
use crate::ral;
use core::{
future::Future,
marker::PhantomPinned,
pin::Pin,
sync::atomic,
task::{Context, Poll, Waker},
};
/// Periodic interrupt timer (PIT)
///
/// See the [module-level documentation](crate::pit) for more information.
#[cfg_attr(docsrs, doc(cfg(feature = "pit")))]
pub struct PIT {
channel: register::ChannelInstance,
}
impl PIT {
/// Acquire four PIT channels from the RAL's PIT instance
pub fn new(pit: ral::pit::Instance) -> (PIT, PIT, PIT, PIT) {
ral::write_reg!(ral::pit, pit, MCR, MDIS: MDIS_0);
// Reset all PIT channels
//
// PIT channels may be used by a systems boot ROM, or another
// user. Set them to a known, good state.
ral::write_reg!(ral::pit, pit, TCTRL0, 0);
ral::write_reg!(ral::pit, pit, TCTRL1, 0);
ral::write_reg!(ral::pit, pit, TCTRL2, 0);
ral::write_reg!(ral::pit, pit, TCTRL3, 0);
unsafe {
cortex_m::peripheral::NVIC::unmask(crate::ral::interrupt::PIT);
(
PIT {
channel: register::ChannelInstance::zero(),
},
PIT {
channel: register::ChannelInstance::one(),
},
PIT {
channel: register::ChannelInstance::two(),
},
PIT {
channel: register::ChannelInstance::three(),
},
)
}
}
/// Wait for the counts to elapse
///
/// The elapsed time is a function of your clock selection and clock frequency.
pub fn delay(&mut self, count: u32) -> Delay<'_> {
Delay {
channel: &mut self.channel,
count,
_pin: PhantomPinned,
}
}
}
static mut WAKERS: [Option<Waker>; 4] = [None, None, None, None];
/// A future that yields once the PIT timer elapses
pub struct Delay<'a> {
channel: &'a mut register::ChannelInstance,
_pin: PhantomPinned,
count: u32,
}
impl<'a> Future for Delay<'a> {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let count = self.count;
// Safety: future is safely Unpin; only exposed as!Unpin, just in case.
let this = unsafe { Pin::into_inner_unchecked(self) };
poll_delay(&mut this.channel, cx, count)
}
}
fn poll_delay(
channel: &mut register::ChannelInstance,
cx: &mut Context<'_>,
count: u32,
) -> Poll<()> {
if ral::read_reg!(register, channel, TFLG, TIF == 1) {
// Complete! W1C
ral::write_reg!(register, channel, TFLG, TIF: 1);
Poll::Ready(())
} else if ral::read_reg!(register, channel, TCTRL)!= 0 {
// We're active; do nothing
Poll::Pending
} else {
// Neither complete nor active; prepare to run
ral::write_reg!(register, channel, LDVAL, count);
unsafe {
WAKERS[channel.index()] = Some(cx.waker().clone());
}
atomic::compiler_fence(atomic::Ordering::SeqCst);
ral::modify_reg!(register, channel, TCTRL, TIE: 1);
ral::modify_reg!(register, channel, TCTRL, TEN: 1);
Poll::Pending
}
}
impl<'a> Drop for Delay<'a> {
fn drop(&mut self) {
poll_cancel(&mut self.channel);
}
}
fn poll_cancel(channel: &mut register::ChannelInstance) {
ral::write_reg!(register, channel, TCTRL, 0);
}
interrupts! {
handler!{unsafe fn PIT() {
use register::ChannelInstance;
[
ChannelInstance::zero(),
ChannelInstance::one(),
ChannelInstance::two(),
ChannelInstance::three(),
]
.iter_mut()
.zip(WAKERS.iter_mut())
.filter(|(channel, _)| ral::read_reg!(register, channel, TFLG, TIF == 1))
.for_each(|(channel, waker)| {
ral::write_reg!(register, channel, TCTRL, 0);
if let Some(waker) = waker.take() {
waker.wake();
}
});
}}
}
/// The auto-generated RAL API is cumbersome. This is a macro-compatible API that makes it
/// easier to work with.
///
/// The approach here is to
///
/// - take the RAL flags, and remove the channel number (copy-paste from RAL)
/// - expose a 'Channel' as a collection of PIT channel registers (copy-paste from RAL)
mod register {
#![allow(unused, non_snake_case, non_upper_case_globals)] // Compatibility with RAL
use crate::ral::{RORegister, RWRegister};
#[repr(C)]
pub struct ChannelRegisterBlock {
/// Timer Load Value Register
pub LDVAL: RWRegister<u32>,
/// Current Timer Value Register
pub CVAL: RORegister<u32>,
/// Timer Control Register
pub TCTRL: RWRegister<u32>,
/// Timer Flag Register
pub TFLG: RWRegister<u32>,
}
pub struct ChannelInstance {
addr: u32,
idx: usize,
_marker: ::core::marker::PhantomData<*const ChannelRegisterBlock>,
}
impl ::core::ops::Deref for ChannelInstance {
type Target = ChannelRegisterBlock;
#[inline(always)]
fn deref(&self) -> &ChannelRegisterBlock {
unsafe { &*(self.addr as *const _) }
}
}
const PIT_BASE_ADDRESS: u32 = 0x4008_4000;
const PIT_CHANNEL_0_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x100;
const PIT_CHANNEL_1_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x110;
const PIT_CHANNEL_2_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x120;
const PIT_CHANNEL_3_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x130;
impl ChannelInstance {
const unsafe fn new(addr: u32, idx: usize) -> Self {
ChannelInstance {
addr,
idx,
_marker: core::marker::PhantomData,
}
}
pub const fn index(&self) -> usize {
self.idx
}
pub const unsafe fn zero() -> Self {
Self::new(PIT_CHANNEL_0_ADDRESS, 0)
}
pub const unsafe fn one() -> Self {
Self::new(PIT_CHANNEL_1_ADDRESS, 1)
}
pub const unsafe fn two() -> Self {
Self::new(PIT_CHANNEL_2_ADDRESS, 2)
}
pub const unsafe fn | () -> Self {
Self::new(PIT_CHANNEL_3_ADDRESS, 3)
}
}
/// Timer Load Value Register
pub mod LDVAL {
/// Timer Start Value
pub mod TSV {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (32 bits: 0xffffffff << 0)
pub const mask: u32 = 0xffffffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Current Timer Value Register
pub mod CVAL {
/// Current Timer Value
pub mod TVL {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (32 bits: 0xffffffff << 0)
pub const mask: u32 = 0xffffffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timer Control Register
pub mod TCTRL {
/// Timer Enable
pub mod TEN {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timer n is disabled.
pub const TEN_0: u32 = 0b0;
/// 0b1: Timer n is enabled.
pub const TEN_1: u32 = 0b1;
}
}
/// Timer Interrupt Enable
pub mod TIE {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Interrupt requests from Timer n are disabled.
pub const TIE_0: u32 = 0b0;
/// 0b1: Interrupt will be requested whenever TIF is set.
pub const TIE_1: u32 = 0b1;
}
}
/// Chain Mode
pub mod CHN {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timer is not chained.
pub const CHN_0: u32 = 0b0;
/// 0b1: Timer is chained to previous timer. For example, for Channel 2, if this field is set, Timer 2 is chained to Timer 1.
pub const CHN_1: u32 = 0b1;
}
}
}
/// Timer Flag Register
pub mod TFLG {
/// Timer Interrupt Flag
pub mod TIF {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timeout has not yet occurred.
pub const TIF_0: u32 = 0b0;
/// 0b1: Timeout has occurred.
pub const TIF_1: u32 = 0b1;
}
}
}
}
| three | identifier_name |
pit.rs | //! Periodic interrupt timer (PIT) driver and futures
//!
//! The PIT timer channels are the most precise timers in the HAL. PIT timers run on the periodic clock
//! frequency.
//!
//! A single hardware PIT instance has four PIT channels. Use [`new`](PIT::new()) to acquire these four
//! channels.
//!
//! # Example
//!
//! Delay for 250ms using PIT channel 3.
//!
//! ```no_run
//! use imxrt_async_hal as hal;
//! use hal::ral;
//! use hal::PIT;
//!
//! let ccm = ral::ccm::CCM::take().unwrap();
//! // Select 24MHz crystal oscillator, divide by 24 == 1MHz clock
//! ral::modify_reg!(ral::ccm, ccm, CSCMR1, PERCLK_PODF: DIVIDE_24, PERCLK_CLK_SEL: 1);
//! // Enable PIT clock gate
//! ral::modify_reg!(ral::ccm, ccm, CCGR1, CG6: 0b11);
//! let (_, _, _, mut pit) = ral::pit::PIT::take()
//! .map(PIT::new)
//! .unwrap();
//!
//! # async {
//! pit.delay(250_000).await;
//! # };
//! ```
use crate::ral;
use core::{
future::Future,
marker::PhantomPinned,
pin::Pin,
sync::atomic,
task::{Context, Poll, Waker},
};
/// Periodic interrupt timer (PIT)
///
/// See the [module-level documentation](crate::pit) for more information.
#[cfg_attr(docsrs, doc(cfg(feature = "pit")))]
pub struct PIT {
channel: register::ChannelInstance,
}
impl PIT {
/// Acquire four PIT channels from the RAL's PIT instance
pub fn new(pit: ral::pit::Instance) -> (PIT, PIT, PIT, PIT) {
ral::write_reg!(ral::pit, pit, MCR, MDIS: MDIS_0);
// Reset all PIT channels
//
// PIT channels may be used by a systems boot ROM, or another
// user. Set them to a known, good state.
ral::write_reg!(ral::pit, pit, TCTRL0, 0);
ral::write_reg!(ral::pit, pit, TCTRL1, 0);
ral::write_reg!(ral::pit, pit, TCTRL2, 0);
ral::write_reg!(ral::pit, pit, TCTRL3, 0);
unsafe {
cortex_m::peripheral::NVIC::unmask(crate::ral::interrupt::PIT);
(
PIT {
channel: register::ChannelInstance::zero(),
},
PIT {
channel: register::ChannelInstance::one(),
},
PIT {
channel: register::ChannelInstance::two(),
},
PIT {
channel: register::ChannelInstance::three(),
},
)
}
}
/// Wait for the counts to elapse
///
/// The elapsed time is a function of your clock selection and clock frequency.
pub fn delay(&mut self, count: u32) -> Delay<'_> {
Delay {
channel: &mut self.channel,
count,
_pin: PhantomPinned,
}
}
}
static mut WAKERS: [Option<Waker>; 4] = [None, None, None, None];
/// A future that yields once the PIT timer elapses
pub struct Delay<'a> {
channel: &'a mut register::ChannelInstance,
_pin: PhantomPinned,
count: u32,
}
impl<'a> Future for Delay<'a> {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let count = self.count;
// Safety: future is safely Unpin; only exposed as!Unpin, just in case.
let this = unsafe { Pin::into_inner_unchecked(self) };
poll_delay(&mut this.channel, cx, count)
}
}
fn poll_delay(
channel: &mut register::ChannelInstance,
cx: &mut Context<'_>,
count: u32,
) -> Poll<()> {
if ral::read_reg!(register, channel, TFLG, TIF == 1) {
// Complete! W1C
ral::write_reg!(register, channel, TFLG, TIF: 1);
Poll::Ready(())
} else if ral::read_reg!(register, channel, TCTRL)!= 0 | else {
// Neither complete nor active; prepare to run
ral::write_reg!(register, channel, LDVAL, count);
unsafe {
WAKERS[channel.index()] = Some(cx.waker().clone());
}
atomic::compiler_fence(atomic::Ordering::SeqCst);
ral::modify_reg!(register, channel, TCTRL, TIE: 1);
ral::modify_reg!(register, channel, TCTRL, TEN: 1);
Poll::Pending
}
}
impl<'a> Drop for Delay<'a> {
fn drop(&mut self) {
poll_cancel(&mut self.channel);
}
}
fn poll_cancel(channel: &mut register::ChannelInstance) {
ral::write_reg!(register, channel, TCTRL, 0);
}
interrupts! {
handler!{unsafe fn PIT() {
use register::ChannelInstance;
[
ChannelInstance::zero(),
ChannelInstance::one(),
ChannelInstance::two(),
ChannelInstance::three(),
]
.iter_mut()
.zip(WAKERS.iter_mut())
.filter(|(channel, _)| ral::read_reg!(register, channel, TFLG, TIF == 1))
.for_each(|(channel, waker)| {
ral::write_reg!(register, channel, TCTRL, 0);
if let Some(waker) = waker.take() {
waker.wake();
}
});
}}
}
/// The auto-generated RAL API is cumbersome. This is a macro-compatible API that makes it
/// easier to work with.
///
/// The approach here is to
///
/// - take the RAL flags, and remove the channel number (copy-paste from RAL)
/// - expose a 'Channel' as a collection of PIT channel registers (copy-paste from RAL)
mod register {
#![allow(unused, non_snake_case, non_upper_case_globals)] // Compatibility with RAL
use crate::ral::{RORegister, RWRegister};
#[repr(C)]
pub struct ChannelRegisterBlock {
/// Timer Load Value Register
pub LDVAL: RWRegister<u32>,
/// Current Timer Value Register
pub CVAL: RORegister<u32>,
/// Timer Control Register
pub TCTRL: RWRegister<u32>,
/// Timer Flag Register
pub TFLG: RWRegister<u32>,
}
pub struct ChannelInstance {
addr: u32,
idx: usize,
_marker: ::core::marker::PhantomData<*const ChannelRegisterBlock>,
}
impl ::core::ops::Deref for ChannelInstance {
type Target = ChannelRegisterBlock;
#[inline(always)]
fn deref(&self) -> &ChannelRegisterBlock {
unsafe { &*(self.addr as *const _) }
}
}
const PIT_BASE_ADDRESS: u32 = 0x4008_4000;
const PIT_CHANNEL_0_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x100;
const PIT_CHANNEL_1_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x110;
const PIT_CHANNEL_2_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x120;
const PIT_CHANNEL_3_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x130;
impl ChannelInstance {
const unsafe fn new(addr: u32, idx: usize) -> Self {
ChannelInstance {
addr,
idx,
_marker: core::marker::PhantomData,
}
}
pub const fn index(&self) -> usize {
self.idx
}
pub const unsafe fn zero() -> Self {
Self::new(PIT_CHANNEL_0_ADDRESS, 0)
}
pub const unsafe fn one() -> Self {
Self::new(PIT_CHANNEL_1_ADDRESS, 1)
}
pub const unsafe fn two() -> Self {
Self::new(PIT_CHANNEL_2_ADDRESS, 2)
}
pub const unsafe fn three() -> Self {
Self::new(PIT_CHANNEL_3_ADDRESS, 3)
}
}
/// Timer Load Value Register
pub mod LDVAL {
/// Timer Start Value
pub mod TSV {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (32 bits: 0xffffffff << 0)
pub const mask: u32 = 0xffffffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Current Timer Value Register
pub mod CVAL {
/// Current Timer Value
pub mod TVL {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (32 bits: 0xffffffff << 0)
pub const mask: u32 = 0xffffffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timer Control Register
pub mod TCTRL {
/// Timer Enable
pub mod TEN {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timer n is disabled.
pub const TEN_0: u32 = 0b0;
/// 0b1: Timer n is enabled.
pub const TEN_1: u32 = 0b1;
}
}
/// Timer Interrupt Enable
pub mod TIE {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Interrupt requests from Timer n are disabled.
pub const TIE_0: u32 = 0b0;
/// 0b1: Interrupt will be requested whenever TIF is set.
pub const TIE_1: u32 = 0b1;
}
}
/// Chain Mode
pub mod CHN {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timer is not chained.
pub const CHN_0: u32 = 0b0;
/// 0b1: Timer is chained to previous timer. For example, for Channel 2, if this field is set, Timer 2 is chained to Timer 1.
pub const CHN_1: u32 = 0b1;
}
}
}
/// Timer Flag Register
pub mod TFLG {
/// Timer Interrupt Flag
pub mod TIF {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timeout has not yet occurred.
pub const TIF_0: u32 = 0b0;
/// 0b1: Timeout has occurred.
pub const TIF_1: u32 = 0b1;
}
}
}
}
| {
// We're active; do nothing
Poll::Pending
} | conditional_block |
pit.rs | //! Periodic interrupt timer (PIT) driver and futures
//!
//! The PIT timer channels are the most precise timers in the HAL. PIT timers run on the periodic clock
//! frequency.
//!
//! A single hardware PIT instance has four PIT channels. Use [`new`](PIT::new()) to acquire these four
//! channels.
//!
//! # Example
//!
//! Delay for 250ms using PIT channel 3.
//!
//! ```no_run
//! use imxrt_async_hal as hal;
//! use hal::ral;
//! use hal::PIT;
//!
//! let ccm = ral::ccm::CCM::take().unwrap();
//! // Select 24MHz crystal oscillator, divide by 24 == 1MHz clock
//! ral::modify_reg!(ral::ccm, ccm, CSCMR1, PERCLK_PODF: DIVIDE_24, PERCLK_CLK_SEL: 1);
//! // Enable PIT clock gate
//! ral::modify_reg!(ral::ccm, ccm, CCGR1, CG6: 0b11);
//! let (_, _, _, mut pit) = ral::pit::PIT::take()
//! .map(PIT::new)
//! .unwrap();
//!
//! # async {
//! pit.delay(250_000).await;
//! # };
//! ```
use crate::ral;
use core::{
future::Future,
marker::PhantomPinned,
pin::Pin,
sync::atomic,
task::{Context, Poll, Waker},
};
/// Periodic interrupt timer (PIT)
///
/// See the [module-level documentation](crate::pit) for more information.
#[cfg_attr(docsrs, doc(cfg(feature = "pit")))]
pub struct PIT {
channel: register::ChannelInstance,
}
impl PIT {
/// Acquire four PIT channels from the RAL's PIT instance
pub fn new(pit: ral::pit::Instance) -> (PIT, PIT, PIT, PIT) {
ral::write_reg!(ral::pit, pit, MCR, MDIS: MDIS_0);
// Reset all PIT channels
//
// PIT channels may be used by a systems boot ROM, or another
// user. Set them to a known, good state.
ral::write_reg!(ral::pit, pit, TCTRL0, 0);
ral::write_reg!(ral::pit, pit, TCTRL1, 0);
ral::write_reg!(ral::pit, pit, TCTRL2, 0);
ral::write_reg!(ral::pit, pit, TCTRL3, 0);
unsafe {
cortex_m::peripheral::NVIC::unmask(crate::ral::interrupt::PIT);
(
PIT {
channel: register::ChannelInstance::zero(),
},
PIT {
channel: register::ChannelInstance::one(),
},
PIT {
channel: register::ChannelInstance::two(),
},
PIT {
channel: register::ChannelInstance::three(),
},
)
}
}
/// Wait for the counts to elapse
///
/// The elapsed time is a function of your clock selection and clock frequency.
pub fn delay(&mut self, count: u32) -> Delay<'_> |
}
static mut WAKERS: [Option<Waker>; 4] = [None, None, None, None];
/// A future that yields once the PIT timer elapses
pub struct Delay<'a> {
channel: &'a mut register::ChannelInstance,
_pin: PhantomPinned,
count: u32,
}
impl<'a> Future for Delay<'a> {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let count = self.count;
// Safety: future is safely Unpin; only exposed as!Unpin, just in case.
let this = unsafe { Pin::into_inner_unchecked(self) };
poll_delay(&mut this.channel, cx, count)
}
}
fn poll_delay(
channel: &mut register::ChannelInstance,
cx: &mut Context<'_>,
count: u32,
) -> Poll<()> {
if ral::read_reg!(register, channel, TFLG, TIF == 1) {
// Complete! W1C
ral::write_reg!(register, channel, TFLG, TIF: 1);
Poll::Ready(())
} else if ral::read_reg!(register, channel, TCTRL)!= 0 {
// We're active; do nothing
Poll::Pending
} else {
// Neither complete nor active; prepare to run
ral::write_reg!(register, channel, LDVAL, count);
unsafe {
WAKERS[channel.index()] = Some(cx.waker().clone());
}
atomic::compiler_fence(atomic::Ordering::SeqCst);
ral::modify_reg!(register, channel, TCTRL, TIE: 1);
ral::modify_reg!(register, channel, TCTRL, TEN: 1);
Poll::Pending
}
}
impl<'a> Drop for Delay<'a> {
fn drop(&mut self) {
poll_cancel(&mut self.channel);
}
}
fn poll_cancel(channel: &mut register::ChannelInstance) {
ral::write_reg!(register, channel, TCTRL, 0);
}
interrupts! {
handler!{unsafe fn PIT() {
use register::ChannelInstance;
[
ChannelInstance::zero(),
ChannelInstance::one(),
ChannelInstance::two(),
ChannelInstance::three(),
]
.iter_mut()
.zip(WAKERS.iter_mut())
.filter(|(channel, _)| ral::read_reg!(register, channel, TFLG, TIF == 1))
.for_each(|(channel, waker)| {
ral::write_reg!(register, channel, TCTRL, 0);
if let Some(waker) = waker.take() {
waker.wake();
}
});
}}
}
/// The auto-generated RAL API is cumbersome. This is a macro-compatible API that makes it
/// easier to work with.
///
/// The approach here is to
///
/// - take the RAL flags, and remove the channel number (copy-paste from RAL)
/// - expose a 'Channel' as a collection of PIT channel registers (copy-paste from RAL)
mod register {
#![allow(unused, non_snake_case, non_upper_case_globals)] // Compatibility with RAL
use crate::ral::{RORegister, RWRegister};
#[repr(C)]
pub struct ChannelRegisterBlock {
/// Timer Load Value Register
pub LDVAL: RWRegister<u32>,
/// Current Timer Value Register
pub CVAL: RORegister<u32>,
/// Timer Control Register
pub TCTRL: RWRegister<u32>,
/// Timer Flag Register
pub TFLG: RWRegister<u32>,
}
pub struct ChannelInstance {
addr: u32,
idx: usize,
_marker: ::core::marker::PhantomData<*const ChannelRegisterBlock>,
}
impl ::core::ops::Deref for ChannelInstance {
type Target = ChannelRegisterBlock;
#[inline(always)]
fn deref(&self) -> &ChannelRegisterBlock {
unsafe { &*(self.addr as *const _) }
}
}
const PIT_BASE_ADDRESS: u32 = 0x4008_4000;
const PIT_CHANNEL_0_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x100;
const PIT_CHANNEL_1_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x110;
const PIT_CHANNEL_2_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x120;
const PIT_CHANNEL_3_ADDRESS: u32 = PIT_BASE_ADDRESS + 0x130;
impl ChannelInstance {
const unsafe fn new(addr: u32, idx: usize) -> Self {
ChannelInstance {
addr,
idx,
_marker: core::marker::PhantomData,
}
}
pub const fn index(&self) -> usize {
self.idx
}
pub const unsafe fn zero() -> Self {
Self::new(PIT_CHANNEL_0_ADDRESS, 0)
}
pub const unsafe fn one() -> Self {
Self::new(PIT_CHANNEL_1_ADDRESS, 1)
}
pub const unsafe fn two() -> Self {
Self::new(PIT_CHANNEL_2_ADDRESS, 2)
}
pub const unsafe fn three() -> Self {
Self::new(PIT_CHANNEL_3_ADDRESS, 3)
}
}
/// Timer Load Value Register
pub mod LDVAL {
/// Timer Start Value
pub mod TSV {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (32 bits: 0xffffffff << 0)
pub const mask: u32 = 0xffffffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Current Timer Value Register
pub mod CVAL {
/// Current Timer Value
pub mod TVL {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (32 bits: 0xffffffff << 0)
pub const mask: u32 = 0xffffffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timer Control Register
pub mod TCTRL {
/// Timer Enable
pub mod TEN {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timer n is disabled.
pub const TEN_0: u32 = 0b0;
/// 0b1: Timer n is enabled.
pub const TEN_1: u32 = 0b1;
}
}
/// Timer Interrupt Enable
pub mod TIE {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Interrupt requests from Timer n are disabled.
pub const TIE_0: u32 = 0b0;
/// 0b1: Interrupt will be requested whenever TIF is set.
pub const TIE_1: u32 = 0b1;
}
}
/// Chain Mode
pub mod CHN {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timer is not chained.
pub const CHN_0: u32 = 0b0;
/// 0b1: Timer is chained to previous timer. For example, for Channel 2, if this field is set, Timer 2 is chained to Timer 1.
pub const CHN_1: u32 = 0b1;
}
}
}
/// Timer Flag Register
pub mod TFLG {
/// Timer Interrupt Flag
pub mod TIF {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values
pub mod RW {
/// 0b0: Timeout has not yet occurred.
pub const TIF_0: u32 = 0b0;
/// 0b1: Timeout has occurred.
pub const TIF_1: u32 = 0b1;
}
}
}
}
| {
Delay {
channel: &mut self.channel,
count,
_pin: PhantomPinned,
}
} | identifier_body |
transactions_reader.rs | /// Reads transactions from a CSV file
/// Make it a separate file in case we want to add new methods
/// such as reading from a non-CSV file and so on
use std::{
collections::HashMap,
io::{BufRead, BufReader},
path::Path,
};
use anyhow::Context;
use crossbeam_channel::{Receiver, Sender};
use csv::{ByteRecord, ReaderBuilder, Trim};
use crate::records::TransactionRecord;
use log::*;
/// A type that represents a stream of transactions arriving into the system
/// Many channels (such as crossbeam) implement iterator interface, so can be used for multithreading
pub type TransactionsStream = Box<dyn Iterator<Item = TransactionRecord>>;
/// Trait to read CSV files into a `TransactionsStream`
pub trait TransactionCSVReader {
/// Read transactions from a CSV file
/// Returns a vector with all the transactions nicely packet into structs
fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream>;
}
/// A single threaded bulk reader
/// Reads and parses everything upfront and returns a stream to the records
pub struct STBulkReader {}
impl STBulkReader {
pub fn new() -> Self {
Self {}
}
}
impl TransactionCSVReader for STBulkReader {
fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream> {
let start_time = std::time::Instant::now();
info!("STBulkReader reading the transactions");
let mut csv_reader = ReaderBuilder::new()
.trim(Trim::All)
.flexible(true)
.from_path(path)?;
// Read as byte records, that should improve the performance without a lot of reallocations
let mut raw_record = csv::ByteRecord::new();
let headers = csv_reader.byte_headers()?.clone();
let mut transactions = Vec::new();
while csv_reader.read_byte_record(&mut raw_record)? {
let record = raw_record.deserialize::<TransactionRecord>(Some(&headers));
// for simplicity, ignore transactions that cannot be parsed
if let Ok(record) = record {
transactions.push(record);
}
}
info!(
"Read {} records in {:?}. Throughput: {} millions/second",
transactions.len(),
start_time.elapsed(),
transactions.len() as f32 / (1000000.0 * start_time.elapsed().as_secs_f32())
);
Ok(Box::new(transactions.into_iter()))
}
}
/// A multithreaded reader
/// Reads blocks of raw bytes from a file (sequentially)
/// And then forwards those blocks to a thread pool for deserialization
pub struct MTReader {
num_threads: usize,
block_size: usize,
}
impl MTReader {
pub fn new() -> Self {
Self {
num_threads: num_cpus::get(),
block_size: 32 * 1024,
}
}
pub fn with_threads(mut self, num_threads: usize) -> Self {
self.num_threads = num_threads;
self
}
#[allow(dead_code)]
pub fn block_size(mut self, block_size: usize) -> Self {
self.block_size = block_size;
self
}
}
impl TransactionCSVReader for MTReader {
fn read_csv<P: AsRef<Path>>(mut self, path: P) -> anyhow::Result<TransactionsStream> {
let mut file_reader =
BufReader::with_capacity(2 * self.block_size, std::fs::File::open(path)?);
let mut headers = vec![];
// read first row
file_reader
.read_until(b'\n', &mut headers)
.with_context(|| "Failed to read the headers")?;
let (parsed_tx, parsed_rx) =
crossbeam_channel::bounded::<(u32, Vec<TransactionRecord>)>(1000);
let (reorder_tx, reorder_rx) = crossbeam_channel::bounded::<TransactionRecord>(100000);
let (block_tx, block_rx) = crossbeam_channel::bounded::<(u32, Vec<u8>)>(1000);
Self::start_reorder(parsed_rx, reorder_tx);
Self::start_dispatcher(self.num_threads, parsed_tx, block_rx);
// Read blocks of transactions
let _ = std::thread::spawn(move || {
let mut block_id = 0;
while let Some(block) = self.read_block(&mut file_reader) {
block_id += 1;
// send them to the thread pool dispatcher
if block_tx.send((block_id, block)).is_err() {
break;
}
// the parsed blocks may arrive out of order, so we need to perform a reordering
}
});
Ok(Box::new(reorder_rx.into_iter()))
}
}
impl MTReader {
/// Dispatch a CSV raw block for parsing
fn start_dispatcher(
num_threads: usize,
parsed_tx: Sender<(u32, Vec<TransactionRecord>)>,
block_rx: Receiver<(u32, Vec<u8>)>,
) | while let Ok(true) = csv_reader.read_byte_record(&mut raw_record) {
let record = raw_record.deserialize::<TransactionRecord>(Some(&headers));
if let Ok(record) = record {
transactions.push(record);
}
}
// Will ignore the channel closed for now
let _ = parsed_tx.send((block_id, transactions));
}
});
}
}
/// Reorders transaction blocks from different thread
/// So in the end everything is chronologically in order
fn start_reorder(
parsed_rx: Receiver<(u32, Vec<TransactionRecord>)>,
reorder_tx: Sender<TransactionRecord>,
) {
// Ignore the join handle, since the lifetime of the thread is tied to the lifetime of the input and output channels
let _ = std::thread::spawn(move || {
let mut waiting_for = 1;
let mut queue = HashMap::new();
while let Ok(block) = parsed_rx.recv() {
if block.0 == waiting_for {
for record in block.1 {
if reorder_tx.send(record).is_err() {
return;
};
}
waiting_for += 1;
// Clear backlog
while let Some(transactions) = queue.remove(&waiting_for) {
for record in transactions {
if reorder_tx.send(record).is_err() {
return;
};
}
waiting_for += 1;
}
} else if block.0 > waiting_for {
queue.insert(block.0, block.1);
}
}
});
}
// Reads a big block until new line alignment
fn read_block(&mut self, reader: &mut impl BufRead) -> Option<Vec<u8>> {
let mut block = vec![0; self.block_size];
// put additional for adjustments
block.reserve(1000);
match reader.read(&mut block) {
Ok(0) => None,
Ok(n) => {
block.truncate(n);
// do not care if we reach EOF for now
let _ = reader.read_until(b'\n', &mut block);
Some(block)
}
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use rust_decimal_macros::dec;
use super::*;
use crate::records::TransactionType;
#[test]
fn test_no_file_exists() {
let transactions = STBulkReader::new().read_csv("tests/data/non_existent.csv");
assert!(transactions.is_err());
}
fn test_transaction_reader(reader: impl TransactionCSVReader, path: &str) {
let mut transactions = reader.read_csv(&path).expect("Test file is not found");
// Validate a few fields to give us enough confidence that parsing is successful
let trans = transactions.next().unwrap();
assert_eq!(trans.tr_type, TransactionType::Deposit);
let trans = transactions.next().unwrap();
assert_eq!(trans.tr_type, TransactionType::Withdrawal);
assert_eq!(trans.client, 6);
assert_eq!(trans.tx, 5);
assert_eq!(trans.amount, Some(dec!(9.0)));
let trans = transactions.skip(2).next().unwrap();
assert_eq!(trans.tr_type, TransactionType::ChargeBack);
assert_eq!(trans.amount, None);
}
/// Tests that we can read and parse all transactions
#[test]
fn test_st_bulk_transaction_reader_serde() {
let reader = STBulkReader::new();
test_transaction_reader(reader, "tests/data/test_serde.csv");
}
#[test]
fn test_mt_reader_transaction_reader_serde() {
let reader = MTReader::new();
test_transaction_reader(reader, "tests/data/test_serde.csv");
}
#[test]
fn test_mt_reader_transaction_reader_big() {
let reader = MTReader::new();
let mut transactions = reader
.read_csv("tests/data/test_mt_reader.csv")
.expect("Test file is not found");
for i in 1..20001 {
assert_eq!(transactions.next().unwrap().tx, i);
}
assert!(transactions.next().is_none());
}
}
| {
for _ in 0..num_threads {
let block_rx = block_rx.clone();
let parsed_tx = parsed_tx.clone();
// For now consider that the headers if read then they're OK and equal to below
let headers = ByteRecord::from(vec!["type", "client", "tx", "amount"]);
std::thread::spawn(move || {
while let Ok((block_id, block)) = block_rx.recv() {
let mut csv_reader = ReaderBuilder::new()
.trim(Trim::All)
.has_headers(true)
.flexible(true)
.from_reader(block.as_slice());
let mut raw_record = csv::ByteRecord::new();
// Looks like I have found a bug in CSV library
// It doesn't trim the first row if has_headers = false and the headers are supplied to deserialize
// I'll open a bug on github
csv_reader.set_byte_headers(headers.clone());
let mut transactions = Vec::new(); | identifier_body |
transactions_reader.rs | /// Reads transactions from a CSV file
/// Make it a separate file in case we want to add new methods
/// such as reading from a non-CSV file and so on
use std::{
collections::HashMap,
io::{BufRead, BufReader},
path::Path,
};
use anyhow::Context;
use crossbeam_channel::{Receiver, Sender};
use csv::{ByteRecord, ReaderBuilder, Trim};
use crate::records::TransactionRecord;
use log::*;
/// A type that represents a stream of transactions arriving into the system
/// Many channels (such as crossbeam) implement iterator interface, so can be used for multithreading
pub type TransactionsStream = Box<dyn Iterator<Item = TransactionRecord>>;
/// Trait to read CSV files into a `TransactionsStream`
pub trait TransactionCSVReader {
/// Read transactions from a CSV file
/// Returns a vector with all the transactions nicely packet into structs
fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream>;
}
/// A single threaded bulk reader
/// Reads and parses everything upfront and returns a stream to the records
pub struct STBulkReader {}
impl STBulkReader {
pub fn new() -> Self {
Self {}
}
}
impl TransactionCSVReader for STBulkReader {
fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream> {
let start_time = std::time::Instant::now();
info!("STBulkReader reading the transactions");
let mut csv_reader = ReaderBuilder::new()
.trim(Trim::All)
.flexible(true)
.from_path(path)?;
// Read as byte records, that should improve the performance without a lot of reallocations
let mut raw_record = csv::ByteRecord::new();
let headers = csv_reader.byte_headers()?.clone();
let mut transactions = Vec::new();
while csv_reader.read_byte_record(&mut raw_record)? {
let record = raw_record.deserialize::<TransactionRecord>(Some(&headers));
// for simplicity, ignore transactions that cannot be parsed
if let Ok(record) = record {
transactions.push(record);
}
}
info!(
"Read {} records in {:?}. Throughput: {} millions/second",
transactions.len(),
start_time.elapsed(),
transactions.len() as f32 / (1000000.0 * start_time.elapsed().as_secs_f32())
);
Ok(Box::new(transactions.into_iter()))
}
}
/// A multithreaded reader
/// Reads blocks of raw bytes from a file (sequentially)
/// And then forwards those blocks to a thread pool for deserialization
pub struct MTReader {
num_threads: usize,
block_size: usize,
}
impl MTReader {
pub fn new() -> Self {
Self {
num_threads: num_cpus::get(),
block_size: 32 * 1024,
}
}
pub fn with_threads(mut self, num_threads: usize) -> Self {
self.num_threads = num_threads;
self
}
#[allow(dead_code)]
pub fn block_size(mut self, block_size: usize) -> Self {
self.block_size = block_size;
self
}
}
impl TransactionCSVReader for MTReader {
fn read_csv<P: AsRef<Path>>(mut self, path: P) -> anyhow::Result<TransactionsStream> {
let mut file_reader =
BufReader::with_capacity(2 * self.block_size, std::fs::File::open(path)?);
let mut headers = vec![];
// read first row
file_reader
.read_until(b'\n', &mut headers)
.with_context(|| "Failed to read the headers")?;
let (parsed_tx, parsed_rx) =
crossbeam_channel::bounded::<(u32, Vec<TransactionRecord>)>(1000);
let (reorder_tx, reorder_rx) = crossbeam_channel::bounded::<TransactionRecord>(100000);
let (block_tx, block_rx) = crossbeam_channel::bounded::<(u32, Vec<u8>)>(1000);
Self::start_reorder(parsed_rx, reorder_tx);
Self::start_dispatcher(self.num_threads, parsed_tx, block_rx);
// Read blocks of transactions
let _ = std::thread::spawn(move || {
let mut block_id = 0;
while let Some(block) = self.read_block(&mut file_reader) {
block_id += 1;
// send them to the thread pool dispatcher
if block_tx.send((block_id, block)).is_err() {
break;
}
// the parsed blocks may arrive out of order, so we need to perform a reordering
}
});
Ok(Box::new(reorder_rx.into_iter()))
}
}
impl MTReader {
/// Dispatch a CSV raw block for parsing
fn start_dispatcher(
num_threads: usize,
parsed_tx: Sender<(u32, Vec<TransactionRecord>)>,
block_rx: Receiver<(u32, Vec<u8>)>,
) {
for _ in 0..num_threads {
let block_rx = block_rx.clone();
let parsed_tx = parsed_tx.clone();
// For now consider that the headers if read then they're OK and equal to below
let headers = ByteRecord::from(vec!["type", "client", "tx", "amount"]);
std::thread::spawn(move || {
while let Ok((block_id, block)) = block_rx.recv() {
let mut csv_reader = ReaderBuilder::new()
.trim(Trim::All)
.has_headers(true)
.flexible(true)
.from_reader(block.as_slice());
let mut raw_record = csv::ByteRecord::new();
// Looks like I have found a bug in CSV library
// It doesn't trim the first row if has_headers = false and the headers are supplied to deserialize
// I'll open a bug on github
csv_reader.set_byte_headers(headers.clone());
let mut transactions = Vec::new();
while let Ok(true) = csv_reader.read_byte_record(&mut raw_record) {
let record = raw_record.deserialize::<TransactionRecord>(Some(&headers));
if let Ok(record) = record {
transactions.push(record);
}
}
// Will ignore the channel closed for now
let _ = parsed_tx.send((block_id, transactions));
}
});
}
}
/// Reorders transaction blocks from different thread
/// So in the end everything is chronologically in order
fn start_reorder(
parsed_rx: Receiver<(u32, Vec<TransactionRecord>)>,
reorder_tx: Sender<TransactionRecord>,
) {
// Ignore the join handle, since the lifetime of the thread is tied to the lifetime of the input and output channels
let _ = std::thread::spawn(move || {
let mut waiting_for = 1;
let mut queue = HashMap::new();
while let Ok(block) = parsed_rx.recv() {
if block.0 == waiting_for {
for record in block.1 {
if reorder_tx.send(record).is_err() {
return;
};
}
waiting_for += 1;
// Clear backlog
while let Some(transactions) = queue.remove(&waiting_for) {
for record in transactions {
if reorder_tx.send(record).is_err() | ;
}
waiting_for += 1;
}
} else if block.0 > waiting_for {
queue.insert(block.0, block.1);
}
}
});
}
// Reads a big block until new line alignment
fn read_block(&mut self, reader: &mut impl BufRead) -> Option<Vec<u8>> {
let mut block = vec![0; self.block_size];
// put additional for adjustments
block.reserve(1000);
match reader.read(&mut block) {
Ok(0) => None,
Ok(n) => {
block.truncate(n);
// do not care if we reach EOF for now
let _ = reader.read_until(b'\n', &mut block);
Some(block)
}
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use rust_decimal_macros::dec;
use super::*;
use crate::records::TransactionType;
#[test]
fn test_no_file_exists() {
let transactions = STBulkReader::new().read_csv("tests/data/non_existent.csv");
assert!(transactions.is_err());
}
fn test_transaction_reader(reader: impl TransactionCSVReader, path: &str) {
let mut transactions = reader.read_csv(&path).expect("Test file is not found");
// Validate a few fields to give us enough confidence that parsing is successful
let trans = transactions.next().unwrap();
assert_eq!(trans.tr_type, TransactionType::Deposit);
let trans = transactions.next().unwrap();
assert_eq!(trans.tr_type, TransactionType::Withdrawal);
assert_eq!(trans.client, 6);
assert_eq!(trans.tx, 5);
assert_eq!(trans.amount, Some(dec!(9.0)));
let trans = transactions.skip(2).next().unwrap();
assert_eq!(trans.tr_type, TransactionType::ChargeBack);
assert_eq!(trans.amount, None);
}
/// Tests that we can read and parse all transactions
#[test]
fn test_st_bulk_transaction_reader_serde() {
let reader = STBulkReader::new();
test_transaction_reader(reader, "tests/data/test_serde.csv");
}
#[test]
fn test_mt_reader_transaction_reader_serde() {
let reader = MTReader::new();
test_transaction_reader(reader, "tests/data/test_serde.csv");
}
#[test]
fn test_mt_reader_transaction_reader_big() {
let reader = MTReader::new();
let mut transactions = reader
.read_csv("tests/data/test_mt_reader.csv")
.expect("Test file is not found");
for i in 1..20001 {
assert_eq!(transactions.next().unwrap().tx, i);
}
assert!(transactions.next().is_none());
}
}
| {
return;
} | conditional_block |
transactions_reader.rs | /// Reads transactions from a CSV file
/// Make it a separate file in case we want to add new methods
/// such as reading from a non-CSV file and so on
use std::{
collections::HashMap,
io::{BufRead, BufReader},
path::Path,
};
use anyhow::Context;
use crossbeam_channel::{Receiver, Sender};
use csv::{ByteRecord, ReaderBuilder, Trim};
use crate::records::TransactionRecord;
use log::*;
/// A type that represents a stream of transactions arriving into the system
/// Many channels (such as crossbeam) implement iterator interface, so can be used for multithreading
pub type TransactionsStream = Box<dyn Iterator<Item = TransactionRecord>>;
/// Trait to read CSV files into a `TransactionsStream`
pub trait TransactionCSVReader {
/// Read transactions from a CSV file
/// Returns a vector with all the transactions nicely packet into structs
fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream>;
}
/// A single threaded bulk reader
/// Reads and parses everything upfront and returns a stream to the records
pub struct STBulkReader {}
impl STBulkReader {
pub fn new() -> Self {
Self {}
}
}
impl TransactionCSVReader for STBulkReader {
fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream> {
let start_time = std::time::Instant::now();
info!("STBulkReader reading the transactions");
let mut csv_reader = ReaderBuilder::new()
.trim(Trim::All)
.flexible(true)
.from_path(path)?;
// Read as byte records, that should improve the performance without a lot of reallocations
let mut raw_record = csv::ByteRecord::new();
let headers = csv_reader.byte_headers()?.clone();
let mut transactions = Vec::new();
while csv_reader.read_byte_record(&mut raw_record)? {
let record = raw_record.deserialize::<TransactionRecord>(Some(&headers));
// for simplicity, ignore transactions that cannot be parsed
if let Ok(record) = record {
transactions.push(record);
}
}
info!(
"Read {} records in {:?}. Throughput: {} millions/second",
transactions.len(),
start_time.elapsed(),
transactions.len() as f32 / (1000000.0 * start_time.elapsed().as_secs_f32())
);
Ok(Box::new(transactions.into_iter()))
}
}
/// A multithreaded reader
/// Reads blocks of raw bytes from a file (sequentially)
/// And then forwards those blocks to a thread pool for deserialization
pub struct MTReader {
num_threads: usize,
block_size: usize,
}
impl MTReader {
pub fn new() -> Self {
Self {
num_threads: num_cpus::get(),
block_size: 32 * 1024,
}
}
pub fn with_threads(mut self, num_threads: usize) -> Self {
self.num_threads = num_threads;
self
}
#[allow(dead_code)]
pub fn block_size(mut self, block_size: usize) -> Self {
self.block_size = block_size;
self
}
}
impl TransactionCSVReader for MTReader {
fn read_csv<P: AsRef<Path>>(mut self, path: P) -> anyhow::Result<TransactionsStream> {
let mut file_reader =
BufReader::with_capacity(2 * self.block_size, std::fs::File::open(path)?);
let mut headers = vec![];
// read first row
file_reader
.read_until(b'\n', &mut headers)
.with_context(|| "Failed to read the headers")?;
let (parsed_tx, parsed_rx) =
crossbeam_channel::bounded::<(u32, Vec<TransactionRecord>)>(1000);
let (reorder_tx, reorder_rx) = crossbeam_channel::bounded::<TransactionRecord>(100000);
let (block_tx, block_rx) = crossbeam_channel::bounded::<(u32, Vec<u8>)>(1000);
Self::start_reorder(parsed_rx, reorder_tx);
Self::start_dispatcher(self.num_threads, parsed_tx, block_rx);
// Read blocks of transactions
let _ = std::thread::spawn(move || {
let mut block_id = 0;
while let Some(block) = self.read_block(&mut file_reader) {
block_id += 1;
// send them to the thread pool dispatcher
if block_tx.send((block_id, block)).is_err() {
break;
}
// the parsed blocks may arrive out of order, so we need to perform a reordering
}
});
Ok(Box::new(reorder_rx.into_iter()))
}
}
impl MTReader {
/// Dispatch a CSV raw block for parsing
fn start_dispatcher(
num_threads: usize,
parsed_tx: Sender<(u32, Vec<TransactionRecord>)>,
block_rx: Receiver<(u32, Vec<u8>)>,
) {
for _ in 0..num_threads {
let block_rx = block_rx.clone();
let parsed_tx = parsed_tx.clone();
// For now consider that the headers if read then they're OK and equal to below
let headers = ByteRecord::from(vec!["type", "client", "tx", "amount"]);
std::thread::spawn(move || {
while let Ok((block_id, block)) = block_rx.recv() {
let mut csv_reader = ReaderBuilder::new()
.trim(Trim::All)
.has_headers(true)
.flexible(true)
.from_reader(block.as_slice());
let mut raw_record = csv::ByteRecord::new();
// Looks like I have found a bug in CSV library
// It doesn't trim the first row if has_headers = false and the headers are supplied to deserialize
// I'll open a bug on github
csv_reader.set_byte_headers(headers.clone());
let mut transactions = Vec::new();
while let Ok(true) = csv_reader.read_byte_record(&mut raw_record) {
let record = raw_record.deserialize::<TransactionRecord>(Some(&headers));
if let Ok(record) = record {
transactions.push(record);
}
}
// Will ignore the channel closed for now
let _ = parsed_tx.send((block_id, transactions));
}
});
}
}
/// Reorders transaction blocks from different thread
/// So in the end everything is chronologically in order
fn start_reorder(
parsed_rx: Receiver<(u32, Vec<TransactionRecord>)>,
reorder_tx: Sender<TransactionRecord>,
) {
// Ignore the join handle, since the lifetime of the thread is tied to the lifetime of the input and output channels
let _ = std::thread::spawn(move || {
let mut waiting_for = 1;
let mut queue = HashMap::new();
while let Ok(block) = parsed_rx.recv() {
if block.0 == waiting_for {
for record in block.1 {
if reorder_tx.send(record).is_err() {
return;
};
}
waiting_for += 1;
// Clear backlog
while let Some(transactions) = queue.remove(&waiting_for) {
for record in transactions {
if reorder_tx.send(record).is_err() {
return;
};
}
waiting_for += 1;
}
} else if block.0 > waiting_for {
queue.insert(block.0, block.1);
}
}
});
}
// Reads a big block until new line alignment
fn read_block(&mut self, reader: &mut impl BufRead) -> Option<Vec<u8>> {
let mut block = vec![0; self.block_size];
// put additional for adjustments
block.reserve(1000);
match reader.read(&mut block) {
Ok(0) => None,
Ok(n) => {
block.truncate(n);
// do not care if we reach EOF for now
let _ = reader.read_until(b'\n', &mut block);
Some(block)
}
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use rust_decimal_macros::dec;
use super::*;
use crate::records::TransactionType;
#[test]
fn test_no_file_exists() {
let transactions = STBulkReader::new().read_csv("tests/data/non_existent.csv");
assert!(transactions.is_err());
}
fn test_transaction_reader(reader: impl TransactionCSVReader, path: &str) {
let mut transactions = reader.read_csv(&path).expect("Test file is not found");
// Validate a few fields to give us enough confidence that parsing is successful
let trans = transactions.next().unwrap();
assert_eq!(trans.tr_type, TransactionType::Deposit);
let trans = transactions.next().unwrap();
assert_eq!(trans.tr_type, TransactionType::Withdrawal);
assert_eq!(trans.client, 6);
assert_eq!(trans.tx, 5);
assert_eq!(trans.amount, Some(dec!(9.0)));
let trans = transactions.skip(2).next().unwrap();
assert_eq!(trans.tr_type, TransactionType::ChargeBack);
assert_eq!(trans.amount, None);
}
| /// Tests that we can read and parse all transactions
#[test]
fn test_st_bulk_transaction_reader_serde() {
let reader = STBulkReader::new();
test_transaction_reader(reader, "tests/data/test_serde.csv");
}
#[test]
fn test_mt_reader_transaction_reader_serde() {
let reader = MTReader::new();
test_transaction_reader(reader, "tests/data/test_serde.csv");
}
#[test]
fn test_mt_reader_transaction_reader_big() {
let reader = MTReader::new();
let mut transactions = reader
.read_csv("tests/data/test_mt_reader.csv")
.expect("Test file is not found");
for i in 1..20001 {
assert_eq!(transactions.next().unwrap().tx, i);
}
assert!(transactions.next().is_none());
}
} | random_line_split |
|
transactions_reader.rs | /// Reads transactions from a CSV file
/// Make it a separate file in case we want to add new methods
/// such as reading from a non-CSV file and so on
use std::{
collections::HashMap,
io::{BufRead, BufReader},
path::Path,
};
use anyhow::Context;
use crossbeam_channel::{Receiver, Sender};
use csv::{ByteRecord, ReaderBuilder, Trim};
use crate::records::TransactionRecord;
use log::*;
/// A type that represents a stream of transactions arriving into the system
/// Many channels (such as crossbeam) implement iterator interface, so can be used for multithreading
pub type TransactionsStream = Box<dyn Iterator<Item = TransactionRecord>>;
/// Trait to read CSV files into a `TransactionsStream`
pub trait TransactionCSVReader {
/// Read transactions from a CSV file
/// Returns a vector with all the transactions nicely packet into structs
fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream>;
}
/// A single threaded bulk reader
/// Reads and parses everything upfront and returns a stream to the records
pub struct | {}
impl STBulkReader {
pub fn new() -> Self {
Self {}
}
}
impl TransactionCSVReader for STBulkReader {
fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream> {
let start_time = std::time::Instant::now();
info!("STBulkReader reading the transactions");
let mut csv_reader = ReaderBuilder::new()
.trim(Trim::All)
.flexible(true)
.from_path(path)?;
// Read as byte records, that should improve the performance without a lot of reallocations
let mut raw_record = csv::ByteRecord::new();
let headers = csv_reader.byte_headers()?.clone();
let mut transactions = Vec::new();
while csv_reader.read_byte_record(&mut raw_record)? {
let record = raw_record.deserialize::<TransactionRecord>(Some(&headers));
// for simplicity, ignore transactions that cannot be parsed
if let Ok(record) = record {
transactions.push(record);
}
}
info!(
"Read {} records in {:?}. Throughput: {} millions/second",
transactions.len(),
start_time.elapsed(),
transactions.len() as f32 / (1000000.0 * start_time.elapsed().as_secs_f32())
);
Ok(Box::new(transactions.into_iter()))
}
}
/// A multithreaded reader
/// Reads blocks of raw bytes from a file (sequentially)
/// And then forwards those blocks to a thread pool for deserialization
pub struct MTReader {
num_threads: usize,
block_size: usize,
}
impl MTReader {
pub fn new() -> Self {
Self {
num_threads: num_cpus::get(),
block_size: 32 * 1024,
}
}
pub fn with_threads(mut self, num_threads: usize) -> Self {
self.num_threads = num_threads;
self
}
#[allow(dead_code)]
pub fn block_size(mut self, block_size: usize) -> Self {
self.block_size = block_size;
self
}
}
impl TransactionCSVReader for MTReader {
fn read_csv<P: AsRef<Path>>(mut self, path: P) -> anyhow::Result<TransactionsStream> {
let mut file_reader =
BufReader::with_capacity(2 * self.block_size, std::fs::File::open(path)?);
let mut headers = vec![];
// read first row
file_reader
.read_until(b'\n', &mut headers)
.with_context(|| "Failed to read the headers")?;
let (parsed_tx, parsed_rx) =
crossbeam_channel::bounded::<(u32, Vec<TransactionRecord>)>(1000);
let (reorder_tx, reorder_rx) = crossbeam_channel::bounded::<TransactionRecord>(100000);
let (block_tx, block_rx) = crossbeam_channel::bounded::<(u32, Vec<u8>)>(1000);
Self::start_reorder(parsed_rx, reorder_tx);
Self::start_dispatcher(self.num_threads, parsed_tx, block_rx);
// Read blocks of transactions
let _ = std::thread::spawn(move || {
let mut block_id = 0;
while let Some(block) = self.read_block(&mut file_reader) {
block_id += 1;
// send them to the thread pool dispatcher
if block_tx.send((block_id, block)).is_err() {
break;
}
// the parsed blocks may arrive out of order, so we need to perform a reordering
}
});
Ok(Box::new(reorder_rx.into_iter()))
}
}
impl MTReader {
/// Dispatch a CSV raw block for parsing
fn start_dispatcher(
num_threads: usize,
parsed_tx: Sender<(u32, Vec<TransactionRecord>)>,
block_rx: Receiver<(u32, Vec<u8>)>,
) {
for _ in 0..num_threads {
let block_rx = block_rx.clone();
let parsed_tx = parsed_tx.clone();
// For now consider that the headers if read then they're OK and equal to below
let headers = ByteRecord::from(vec!["type", "client", "tx", "amount"]);
std::thread::spawn(move || {
while let Ok((block_id, block)) = block_rx.recv() {
let mut csv_reader = ReaderBuilder::new()
.trim(Trim::All)
.has_headers(true)
.flexible(true)
.from_reader(block.as_slice());
let mut raw_record = csv::ByteRecord::new();
// Looks like I have found a bug in CSV library
// It doesn't trim the first row if has_headers = false and the headers are supplied to deserialize
// I'll open a bug on github
csv_reader.set_byte_headers(headers.clone());
let mut transactions = Vec::new();
while let Ok(true) = csv_reader.read_byte_record(&mut raw_record) {
let record = raw_record.deserialize::<TransactionRecord>(Some(&headers));
if let Ok(record) = record {
transactions.push(record);
}
}
// Will ignore the channel closed for now
let _ = parsed_tx.send((block_id, transactions));
}
});
}
}
/// Reorders transaction blocks from different thread
/// So in the end everything is chronologically in order
fn start_reorder(
parsed_rx: Receiver<(u32, Vec<TransactionRecord>)>,
reorder_tx: Sender<TransactionRecord>,
) {
// Ignore the join handle, since the lifetime of the thread is tied to the lifetime of the input and output channels
let _ = std::thread::spawn(move || {
let mut waiting_for = 1;
let mut queue = HashMap::new();
while let Ok(block) = parsed_rx.recv() {
if block.0 == waiting_for {
for record in block.1 {
if reorder_tx.send(record).is_err() {
return;
};
}
waiting_for += 1;
// Clear backlog
while let Some(transactions) = queue.remove(&waiting_for) {
for record in transactions {
if reorder_tx.send(record).is_err() {
return;
};
}
waiting_for += 1;
}
} else if block.0 > waiting_for {
queue.insert(block.0, block.1);
}
}
});
}
// Reads a big block until new line alignment
fn read_block(&mut self, reader: &mut impl BufRead) -> Option<Vec<u8>> {
let mut block = vec![0; self.block_size];
// put additional for adjustments
block.reserve(1000);
match reader.read(&mut block) {
Ok(0) => None,
Ok(n) => {
block.truncate(n);
// do not care if we reach EOF for now
let _ = reader.read_until(b'\n', &mut block);
Some(block)
}
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use rust_decimal_macros::dec;
use super::*;
use crate::records::TransactionType;
#[test]
fn test_no_file_exists() {
let transactions = STBulkReader::new().read_csv("tests/data/non_existent.csv");
assert!(transactions.is_err());
}
fn test_transaction_reader(reader: impl TransactionCSVReader, path: &str) {
let mut transactions = reader.read_csv(&path).expect("Test file is not found");
// Validate a few fields to give us enough confidence that parsing is successful
let trans = transactions.next().unwrap();
assert_eq!(trans.tr_type, TransactionType::Deposit);
let trans = transactions.next().unwrap();
assert_eq!(trans.tr_type, TransactionType::Withdrawal);
assert_eq!(trans.client, 6);
assert_eq!(trans.tx, 5);
assert_eq!(trans.amount, Some(dec!(9.0)));
let trans = transactions.skip(2).next().unwrap();
assert_eq!(trans.tr_type, TransactionType::ChargeBack);
assert_eq!(trans.amount, None);
}
/// Tests that we can read and parse all transactions
#[test]
fn test_st_bulk_transaction_reader_serde() {
let reader = STBulkReader::new();
test_transaction_reader(reader, "tests/data/test_serde.csv");
}
#[test]
fn test_mt_reader_transaction_reader_serde() {
let reader = MTReader::new();
test_transaction_reader(reader, "tests/data/test_serde.csv");
}
#[test]
fn test_mt_reader_transaction_reader_big() {
let reader = MTReader::new();
let mut transactions = reader
.read_csv("tests/data/test_mt_reader.csv")
.expect("Test file is not found");
for i in 1..20001 {
assert_eq!(transactions.next().unwrap().tx, i);
}
assert!(transactions.next().is_none());
}
}
| STBulkReader | identifier_name |
dir.rs | use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::str;
use traits::{self, Dir as DirTrait, Entry as EntryTrait};
use util::VecExt;
use vfat::{Attributes, Date, Metadata, Time, Timestamp};
use vfat::{Cluster, Entry, File, Shared, VFat};
#[derive(Debug)]
pub struct Dir {
vfat: Shared<VFat>,
start: Cluster,
name: String,
metadata: Metadata,
}
impl Dir {
pub fn new(vfat: Shared<VFat>, start: Cluster, name: String, metadata: Metadata) -> Dir {
Dir {
vfat,
start,
name,
metadata,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn metadata(&self) -> &Metadata {
&self.metadata
}
/// Finds the entry named `name` in `self` and returns it. Comparison is
/// case-insensitive.
///
/// # Errors
///
/// If no entry with name `name` exists in `self`, an error of `NotFound` is
/// returned.
///
/// If `name` contains invalid UTF-8 characters, an error of `InvalidInput`
/// is returned.
pub fn find<P: AsRef<OsStr>>(&self, name: P) -> io::Result<Entry> {
let name = name.as_ref().to_str().ok_or(io::Error::new(
io::ErrorKind::InvalidInput,
"name is not valid utf-8",
))?;
let entry = self
.entries()?
.find(|entry| entry.name().eq_ignore_ascii_case(name.as_ref()))
.ok_or(io::Error::new(
io::ErrorKind::NotFound,
format!("{}: not found", name),
))?;
Ok(entry)
}
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct VFatRegularDirEntry {
name: [u8; 8],
extension: [u8; 3],
attributes: u8,
_nt_reserved: u8,
_created_time_tenths_second: u8,
created_time: u16,
created_date: u16,
accessed_date: u16,
cluster_high: u16,
modified_time: u16,
modified_date: u16,
cluster_low: u16,
size: u32,
}
impl fmt::Debug for VFatRegularDirEntry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("VFatRegularDirEntry")
.field("name", &self.name())
.field("attributes", &self.attributes)
.field("created_time", &self.created_time)
.field("created_date", &self.created_date)
.field("accessed_date", &self.accessed_date)
.field("modified_time", &self.modified_time)
.field("modified_date", &self.modified_date)
.field("cluster", &self.cluster())
.finish()
}
}
impl VFatRegularDirEntry {
fn sentinel(&self) -> bool {
self.name[0] == 0x00
}
fn deleted(&self) -> bool {
self.name[0] == 0x05 || self.name[0] == 0xE5
}
fn cluster(&self) -> Cluster {
Cluster::from(((self.cluster_high as u32) << 16) | (self.cluster_low as u32))
}
fn created(&self) -> Timestamp {
let date = Date::from_raw(self.created_date);
let time = Time::from_raw(self.created_time);
Timestamp::new(date, time)
}
fn accessed(&self) -> Timestamp {
let date = Date::from_raw(self.accessed_date);
Timestamp::new(date, Default::default())
}
fn modified(&self) -> Timestamp {
let date = Date::from_raw(self.modified_date);
let time = Time::from_raw(self.modified_time);
Timestamp::new(date, time)
}
fn attributes(&self) -> Attributes {
Attributes::from_raw(self.attributes)
}
fn size(&self) -> u64 {
self.size as u64
}
fn metadata(&self) -> Metadata {
let attributes = self.attributes();
let created = self.created();
let accessed = self.accessed();
let modified = self.modified();
let size = self.size();
Metadata {
attributes,
created,
accessed,
modified,
size,
}
}
fn name(&self) -> Option<String> {
let &name_stop = &self.name[..]
.iter()
.position(|&c| c == 0x00 || c == b' ')
.unwrap_or(self.name.len());
let &ext_stop = &self.extension[..]
.iter()
.position(|&c| c == 0x00 || c == b' ')
.unwrap_or(self.extension.len());
let name = str::from_utf8(&self.name[..name_stop]).ok()?;
let extension = str::from_utf8(&self.extension[..ext_stop]).ok()?;
if name == "" {
return None;
}
if extension!= "" {
Some(format!("{}.{}", name, extension))
} else {
Some(format!("{}", name))
}
}
}
#[repr(C, packed)]
#[derive(Copy, Clone, Debug)]
pub struct VFatLfnDirEntry {
seqno: u8,
name_1: [u16; 5],
attributes: u8,
_reserved_1: u8,
dos_checksum: u8,
name_2: [u16; 6],
_reserved_2: [u8; 2],
name_3: [u16; 2],
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct VFatUnknownDirEntry {
_unknown_1: [u8; 11],
attributes: u8,
_unknown_2: [u8; 20],
}
pub union VFatDirEntry {
unknown: VFatUnknownDirEntry,
regular: VFatRegularDirEntry,
long_filename: VFatLfnDirEntry,
}
impl From<VFatRegularDirEntry> for VFatEntry {
fn from(regular: VFatRegularDirEntry) -> VFatEntry {
VFatEntry::Regular(regular)
}
}
impl From<VFatLfnDirEntry> for VFatEntry {
fn from(lfn: VFatLfnDirEntry) -> VFatEntry {
VFatEntry::Lfn(lfn)
}
}
impl<'a> From<&'a VFatDirEntry> for VFatEntry {
fn from(dir_entry: &'a VFatDirEntry) -> VFatEntry {
let attributes = unsafe { dir_entry.unknown.attributes };
let attributes = Attributes::from_raw(attributes);
unsafe {
match (attributes.lfn(), dir_entry) {
(true, &VFatDirEntry { long_filename }) => long_filename.into(),
(false, &VFatDirEntry { regular }) => regular.into(),
}
}
}
}
#[derive(Debug)]
enum VFatEntry {
Regular(VFatRegularDirEntry),
Lfn(VFatLfnDirEntry),
}
impl VFatEntry {
fn regular(&self) -> Option<&VFatRegularDirEntry> {
if let &VFatEntry::Regular(ref reg) = self {
Some(reg)
} else {
None
}
}
fn lfn(&self) -> Option<&VFatLfnDirEntry> {
if let &VFatEntry::Lfn(ref lfn) = self {
Some(lfn)
} else {
None
}
}
}
impl traits::Dir for Dir {
/// The type of entry stored in this directory.
type Entry = Entry;
/// An type that is an iterator over the entries in this directory.
type Iter = DirIter;
/// Returns an interator over the entries in this directory.
fn entries(&self) -> io::Result<Self::Iter> {
let mut vfat = self.vfat.borrow_mut();
let mut buf = vec![];
vfat.read_chain(self.start, &mut buf, None)?;
let buf = unsafe { buf.cast::<VFatDirEntry>() };
Ok(DirIter::new(self.vfat.clone(), buf))
}
}
pub struct DirIter {
vfat: Shared<VFat>,
buf: Vec<VFatDirEntry>,
current: usize,
}
impl DirIter {
fn new(vfat: Shared<VFat>, buf: Vec<VFatDirEntry>) -> DirIter {
DirIter {
vfat,
buf,
current: 0,
}
}
fn name_from_lfn(&self, lfn_start: usize, lfn_stop: usize) -> Option<String> {
let mut entries: Vec<VFatLfnDirEntry> = (&self.buf[lfn_start..lfn_stop])
.iter()
.rev()
.map(|entry| entry.into())
// first ensure that we stop at the preceding regular in the array
.take_while(|entry| {
if let &VFatEntry::Lfn(_) = entry {
true
} else |
}).filter_map(|entry| match entry.lfn() {
Some(lfn) if lfn.seqno!= 0xE5 => Some(*lfn),
_ => None,
}).collect();
entries.sort_by_key(|lfn| lfn.seqno);
let mut name: Vec<u16> = vec![];
for &lfn in entries.iter() {
name.extend(lfn.name_1.iter());
name.extend(lfn.name_2.iter());
name.extend(lfn.name_3.iter());
}
let end = name
.iter()
.position(|&c| c == 0x0000u16)
.unwrap_or(name.len());
let s = decode_utf16((&name[..end]).iter().cloned())
.map(|c| c.unwrap_or(REPLACEMENT_CHARACTER))
.collect::<String>();
if s.is_empty() {
None
} else {
Some(s)
}
}
}
impl Iterator for DirIter {
type Item = Entry;
fn next(&mut self) -> Option<Self::Item> {
if self.current >= self.buf.len() {
return None;
}
let (regular_index, regular, name) = (&self.buf)[self.current..]
.iter()
.enumerate()
.filter_map(|(i, union_entry)| {
let index = self.current + i;
let entry: VFatEntry = union_entry.into();
let regular = entry.regular()?;
if!regular.deleted() &&!regular.sentinel() {
Some((index, *regular))
} else {
None
}
}).next()
.and_then(|(regular_index, regular)| {
let name = if self.current < regular_index {
self.name_from_lfn(self.current, regular_index)
} else {
None
};
let name = name.or_else(|| regular.name())?;
Some((regular_index, regular, name))
})?;
self.current = regular_index + 1;
let metadata = regular.metadata();
let start = regular.cluster();
let vfat = self.vfat.clone();
if metadata.attributes.directory() {
Some(Entry::Dir(Dir::new(vfat, start, name, metadata)))
} else {
Some(Entry::File(File::new(vfat, start, name, metadata)))
}
}
}
| {
false
} | conditional_block |
dir.rs | use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::str;
use traits::{self, Dir as DirTrait, Entry as EntryTrait};
use util::VecExt;
use vfat::{Attributes, Date, Metadata, Time, Timestamp};
use vfat::{Cluster, Entry, File, Shared, VFat};
#[derive(Debug)]
pub struct Dir {
vfat: Shared<VFat>,
start: Cluster,
name: String,
metadata: Metadata,
}
impl Dir {
pub fn new(vfat: Shared<VFat>, start: Cluster, name: String, metadata: Metadata) -> Dir {
Dir {
vfat,
start,
name,
metadata,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn metadata(&self) -> &Metadata {
&self.metadata
}
/// Finds the entry named `name` in `self` and returns it. Comparison is
/// case-insensitive.
///
/// # Errors
///
/// If no entry with name `name` exists in `self`, an error of `NotFound` is
/// returned.
///
/// If `name` contains invalid UTF-8 characters, an error of `InvalidInput`
/// is returned.
pub fn find<P: AsRef<OsStr>>(&self, name: P) -> io::Result<Entry> {
let name = name.as_ref().to_str().ok_or(io::Error::new(
io::ErrorKind::InvalidInput,
"name is not valid utf-8",
))?;
let entry = self
.entries()?
.find(|entry| entry.name().eq_ignore_ascii_case(name.as_ref()))
.ok_or(io::Error::new(
io::ErrorKind::NotFound,
format!("{}: not found", name),
))?;
Ok(entry)
}
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct VFatRegularDirEntry {
name: [u8; 8],
extension: [u8; 3],
attributes: u8,
_nt_reserved: u8,
_created_time_tenths_second: u8,
created_time: u16,
created_date: u16,
accessed_date: u16,
cluster_high: u16,
modified_time: u16,
modified_date: u16,
cluster_low: u16,
size: u32,
}
impl fmt::Debug for VFatRegularDirEntry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("VFatRegularDirEntry")
.field("name", &self.name())
.field("attributes", &self.attributes)
.field("created_time", &self.created_time)
.field("created_date", &self.created_date)
.field("accessed_date", &self.accessed_date)
.field("modified_time", &self.modified_time)
.field("modified_date", &self.modified_date)
.field("cluster", &self.cluster())
.finish()
}
}
impl VFatRegularDirEntry {
fn sentinel(&self) -> bool {
self.name[0] == 0x00
}
fn deleted(&self) -> bool {
self.name[0] == 0x05 || self.name[0] == 0xE5
}
fn cluster(&self) -> Cluster {
Cluster::from(((self.cluster_high as u32) << 16) | (self.cluster_low as u32))
}
fn created(&self) -> Timestamp {
let date = Date::from_raw(self.created_date);
let time = Time::from_raw(self.created_time);
Timestamp::new(date, time)
}
fn accessed(&self) -> Timestamp {
let date = Date::from_raw(self.accessed_date);
Timestamp::new(date, Default::default())
}
fn modified(&self) -> Timestamp {
let date = Date::from_raw(self.modified_date);
let time = Time::from_raw(self.modified_time);
Timestamp::new(date, time)
}
fn attributes(&self) -> Attributes {
Attributes::from_raw(self.attributes)
}
fn size(&self) -> u64 {
self.size as u64
}
fn metadata(&self) -> Metadata {
let attributes = self.attributes();
let created = self.created();
let accessed = self.accessed();
let modified = self.modified();
let size = self.size();
Metadata {
attributes,
created,
accessed,
modified,
size,
}
}
fn name(&self) -> Option<String> {
let &name_stop = &self.name[..]
.iter()
.position(|&c| c == 0x00 || c == b' ')
.unwrap_or(self.name.len());
let &ext_stop = &self.extension[..]
.iter()
.position(|&c| c == 0x00 || c == b' ')
.unwrap_or(self.extension.len());
let name = str::from_utf8(&self.name[..name_stop]).ok()?;
let extension = str::from_utf8(&self.extension[..ext_stop]).ok()?;
if name == "" {
return None;
}
if extension!= "" {
Some(format!("{}.{}", name, extension))
} else {
Some(format!("{}", name))
} | #[repr(C, packed)]
#[derive(Copy, Clone, Debug)]
pub struct VFatLfnDirEntry {
seqno: u8,
name_1: [u16; 5],
attributes: u8,
_reserved_1: u8,
dos_checksum: u8,
name_2: [u16; 6],
_reserved_2: [u8; 2],
name_3: [u16; 2],
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct VFatUnknownDirEntry {
_unknown_1: [u8; 11],
attributes: u8,
_unknown_2: [u8; 20],
}
pub union VFatDirEntry {
unknown: VFatUnknownDirEntry,
regular: VFatRegularDirEntry,
long_filename: VFatLfnDirEntry,
}
impl From<VFatRegularDirEntry> for VFatEntry {
fn from(regular: VFatRegularDirEntry) -> VFatEntry {
VFatEntry::Regular(regular)
}
}
impl From<VFatLfnDirEntry> for VFatEntry {
fn from(lfn: VFatLfnDirEntry) -> VFatEntry {
VFatEntry::Lfn(lfn)
}
}
impl<'a> From<&'a VFatDirEntry> for VFatEntry {
fn from(dir_entry: &'a VFatDirEntry) -> VFatEntry {
let attributes = unsafe { dir_entry.unknown.attributes };
let attributes = Attributes::from_raw(attributes);
unsafe {
match (attributes.lfn(), dir_entry) {
(true, &VFatDirEntry { long_filename }) => long_filename.into(),
(false, &VFatDirEntry { regular }) => regular.into(),
}
}
}
}
#[derive(Debug)]
enum VFatEntry {
Regular(VFatRegularDirEntry),
Lfn(VFatLfnDirEntry),
}
impl VFatEntry {
fn regular(&self) -> Option<&VFatRegularDirEntry> {
if let &VFatEntry::Regular(ref reg) = self {
Some(reg)
} else {
None
}
}
fn lfn(&self) -> Option<&VFatLfnDirEntry> {
if let &VFatEntry::Lfn(ref lfn) = self {
Some(lfn)
} else {
None
}
}
}
impl traits::Dir for Dir {
/// The type of entry stored in this directory.
type Entry = Entry;
/// An type that is an iterator over the entries in this directory.
type Iter = DirIter;
/// Returns an interator over the entries in this directory.
fn entries(&self) -> io::Result<Self::Iter> {
let mut vfat = self.vfat.borrow_mut();
let mut buf = vec![];
vfat.read_chain(self.start, &mut buf, None)?;
let buf = unsafe { buf.cast::<VFatDirEntry>() };
Ok(DirIter::new(self.vfat.clone(), buf))
}
}
pub struct DirIter {
vfat: Shared<VFat>,
buf: Vec<VFatDirEntry>,
current: usize,
}
impl DirIter {
fn new(vfat: Shared<VFat>, buf: Vec<VFatDirEntry>) -> DirIter {
DirIter {
vfat,
buf,
current: 0,
}
}
fn name_from_lfn(&self, lfn_start: usize, lfn_stop: usize) -> Option<String> {
let mut entries: Vec<VFatLfnDirEntry> = (&self.buf[lfn_start..lfn_stop])
.iter()
.rev()
.map(|entry| entry.into())
// first ensure that we stop at the preceding regular in the array
.take_while(|entry| {
if let &VFatEntry::Lfn(_) = entry {
true
} else {
false
}
}).filter_map(|entry| match entry.lfn() {
Some(lfn) if lfn.seqno!= 0xE5 => Some(*lfn),
_ => None,
}).collect();
entries.sort_by_key(|lfn| lfn.seqno);
let mut name: Vec<u16> = vec![];
for &lfn in entries.iter() {
name.extend(lfn.name_1.iter());
name.extend(lfn.name_2.iter());
name.extend(lfn.name_3.iter());
}
let end = name
.iter()
.position(|&c| c == 0x0000u16)
.unwrap_or(name.len());
let s = decode_utf16((&name[..end]).iter().cloned())
.map(|c| c.unwrap_or(REPLACEMENT_CHARACTER))
.collect::<String>();
if s.is_empty() {
None
} else {
Some(s)
}
}
}
impl Iterator for DirIter {
type Item = Entry;
fn next(&mut self) -> Option<Self::Item> {
if self.current >= self.buf.len() {
return None;
}
let (regular_index, regular, name) = (&self.buf)[self.current..]
.iter()
.enumerate()
.filter_map(|(i, union_entry)| {
let index = self.current + i;
let entry: VFatEntry = union_entry.into();
let regular = entry.regular()?;
if!regular.deleted() &&!regular.sentinel() {
Some((index, *regular))
} else {
None
}
}).next()
.and_then(|(regular_index, regular)| {
let name = if self.current < regular_index {
self.name_from_lfn(self.current, regular_index)
} else {
None
};
let name = name.or_else(|| regular.name())?;
Some((regular_index, regular, name))
})?;
self.current = regular_index + 1;
let metadata = regular.metadata();
let start = regular.cluster();
let vfat = self.vfat.clone();
if metadata.attributes.directory() {
Some(Entry::Dir(Dir::new(vfat, start, name, metadata)))
} else {
Some(Entry::File(File::new(vfat, start, name, metadata)))
}
}
} | }
}
| random_line_split |
dir.rs | use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::str;
use traits::{self, Dir as DirTrait, Entry as EntryTrait};
use util::VecExt;
use vfat::{Attributes, Date, Metadata, Time, Timestamp};
use vfat::{Cluster, Entry, File, Shared, VFat};
#[derive(Debug)]
pub struct Dir {
vfat: Shared<VFat>,
start: Cluster,
name: String,
metadata: Metadata,
}
impl Dir {
pub fn new(vfat: Shared<VFat>, start: Cluster, name: String, metadata: Metadata) -> Dir {
Dir {
vfat,
start,
name,
metadata,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn metadata(&self) -> &Metadata {
&self.metadata
}
/// Finds the entry named `name` in `self` and returns it. Comparison is
/// case-insensitive.
///
/// # Errors
///
/// If no entry with name `name` exists in `self`, an error of `NotFound` is
/// returned.
///
/// If `name` contains invalid UTF-8 characters, an error of `InvalidInput`
/// is returned.
pub fn find<P: AsRef<OsStr>>(&self, name: P) -> io::Result<Entry> {
let name = name.as_ref().to_str().ok_or(io::Error::new(
io::ErrorKind::InvalidInput,
"name is not valid utf-8",
))?;
let entry = self
.entries()?
.find(|entry| entry.name().eq_ignore_ascii_case(name.as_ref()))
.ok_or(io::Error::new(
io::ErrorKind::NotFound,
format!("{}: not found", name),
))?;
Ok(entry)
}
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct VFatRegularDirEntry {
name: [u8; 8],
extension: [u8; 3],
attributes: u8,
_nt_reserved: u8,
_created_time_tenths_second: u8,
created_time: u16,
created_date: u16,
accessed_date: u16,
cluster_high: u16,
modified_time: u16,
modified_date: u16,
cluster_low: u16,
size: u32,
}
impl fmt::Debug for VFatRegularDirEntry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("VFatRegularDirEntry")
.field("name", &self.name())
.field("attributes", &self.attributes)
.field("created_time", &self.created_time)
.field("created_date", &self.created_date)
.field("accessed_date", &self.accessed_date)
.field("modified_time", &self.modified_time)
.field("modified_date", &self.modified_date)
.field("cluster", &self.cluster())
.finish()
}
}
impl VFatRegularDirEntry {
fn sentinel(&self) -> bool {
self.name[0] == 0x00
}
fn deleted(&self) -> bool {
self.name[0] == 0x05 || self.name[0] == 0xE5
}
fn cluster(&self) -> Cluster {
Cluster::from(((self.cluster_high as u32) << 16) | (self.cluster_low as u32))
}
fn created(&self) -> Timestamp {
let date = Date::from_raw(self.created_date);
let time = Time::from_raw(self.created_time);
Timestamp::new(date, time)
}
fn accessed(&self) -> Timestamp {
let date = Date::from_raw(self.accessed_date);
Timestamp::new(date, Default::default())
}
fn modified(&self) -> Timestamp {
let date = Date::from_raw(self.modified_date);
let time = Time::from_raw(self.modified_time);
Timestamp::new(date, time)
}
fn attributes(&self) -> Attributes {
Attributes::from_raw(self.attributes)
}
fn size(&self) -> u64 {
self.size as u64
}
fn metadata(&self) -> Metadata {
let attributes = self.attributes();
let created = self.created();
let accessed = self.accessed();
let modified = self.modified();
let size = self.size();
Metadata {
attributes,
created,
accessed,
modified,
size,
}
}
fn name(&self) -> Option<String> {
let &name_stop = &self.name[..]
.iter()
.position(|&c| c == 0x00 || c == b' ')
.unwrap_or(self.name.len());
let &ext_stop = &self.extension[..]
.iter()
.position(|&c| c == 0x00 || c == b' ')
.unwrap_or(self.extension.len());
let name = str::from_utf8(&self.name[..name_stop]).ok()?;
let extension = str::from_utf8(&self.extension[..ext_stop]).ok()?;
if name == "" {
return None;
}
if extension!= "" {
Some(format!("{}.{}", name, extension))
} else {
Some(format!("{}", name))
}
}
}
#[repr(C, packed)]
#[derive(Copy, Clone, Debug)]
pub struct VFatLfnDirEntry {
seqno: u8,
name_1: [u16; 5],
attributes: u8,
_reserved_1: u8,
dos_checksum: u8,
name_2: [u16; 6],
_reserved_2: [u8; 2],
name_3: [u16; 2],
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct VFatUnknownDirEntry {
_unknown_1: [u8; 11],
attributes: u8,
_unknown_2: [u8; 20],
}
pub union VFatDirEntry {
unknown: VFatUnknownDirEntry,
regular: VFatRegularDirEntry,
long_filename: VFatLfnDirEntry,
}
impl From<VFatRegularDirEntry> for VFatEntry {
fn from(regular: VFatRegularDirEntry) -> VFatEntry {
VFatEntry::Regular(regular)
}
}
impl From<VFatLfnDirEntry> for VFatEntry {
fn from(lfn: VFatLfnDirEntry) -> VFatEntry {
VFatEntry::Lfn(lfn)
}
}
impl<'a> From<&'a VFatDirEntry> for VFatEntry {
fn from(dir_entry: &'a VFatDirEntry) -> VFatEntry {
let attributes = unsafe { dir_entry.unknown.attributes };
let attributes = Attributes::from_raw(attributes);
unsafe {
match (attributes.lfn(), dir_entry) {
(true, &VFatDirEntry { long_filename }) => long_filename.into(),
(false, &VFatDirEntry { regular }) => regular.into(),
}
}
}
}
#[derive(Debug)]
enum VFatEntry {
Regular(VFatRegularDirEntry),
Lfn(VFatLfnDirEntry),
}
impl VFatEntry {
fn regular(&self) -> Option<&VFatRegularDirEntry> {
if let &VFatEntry::Regular(ref reg) = self {
Some(reg)
} else {
None
}
}
fn lfn(&self) -> Option<&VFatLfnDirEntry> {
if let &VFatEntry::Lfn(ref lfn) = self {
Some(lfn)
} else {
None
}
}
}
impl traits::Dir for Dir {
/// The type of entry stored in this directory.
type Entry = Entry;
/// An type that is an iterator over the entries in this directory.
type Iter = DirIter;
/// Returns an interator over the entries in this directory.
fn entries(&self) -> io::Result<Self::Iter> {
let mut vfat = self.vfat.borrow_mut();
let mut buf = vec![];
vfat.read_chain(self.start, &mut buf, None)?;
let buf = unsafe { buf.cast::<VFatDirEntry>() };
Ok(DirIter::new(self.vfat.clone(), buf))
}
}
pub struct DirIter {
vfat: Shared<VFat>,
buf: Vec<VFatDirEntry>,
current: usize,
}
impl DirIter {
fn new(vfat: Shared<VFat>, buf: Vec<VFatDirEntry>) -> DirIter {
DirIter {
vfat,
buf,
current: 0,
}
}
fn name_from_lfn(&self, lfn_start: usize, lfn_stop: usize) -> Option<String> {
let mut entries: Vec<VFatLfnDirEntry> = (&self.buf[lfn_start..lfn_stop])
.iter()
.rev()
.map(|entry| entry.into())
// first ensure that we stop at the preceding regular in the array
.take_while(|entry| {
if let &VFatEntry::Lfn(_) = entry {
true
} else {
false
}
}).filter_map(|entry| match entry.lfn() {
Some(lfn) if lfn.seqno!= 0xE5 => Some(*lfn),
_ => None,
}).collect();
entries.sort_by_key(|lfn| lfn.seqno);
let mut name: Vec<u16> = vec![];
for &lfn in entries.iter() {
name.extend(lfn.name_1.iter());
name.extend(lfn.name_2.iter());
name.extend(lfn.name_3.iter());
}
let end = name
.iter()
.position(|&c| c == 0x0000u16)
.unwrap_or(name.len());
let s = decode_utf16((&name[..end]).iter().cloned())
.map(|c| c.unwrap_or(REPLACEMENT_CHARACTER))
.collect::<String>();
if s.is_empty() {
None
} else {
Some(s)
}
}
}
impl Iterator for DirIter {
type Item = Entry;
fn | (&mut self) -> Option<Self::Item> {
if self.current >= self.buf.len() {
return None;
}
let (regular_index, regular, name) = (&self.buf)[self.current..]
.iter()
.enumerate()
.filter_map(|(i, union_entry)| {
let index = self.current + i;
let entry: VFatEntry = union_entry.into();
let regular = entry.regular()?;
if!regular.deleted() &&!regular.sentinel() {
Some((index, *regular))
} else {
None
}
}).next()
.and_then(|(regular_index, regular)| {
let name = if self.current < regular_index {
self.name_from_lfn(self.current, regular_index)
} else {
None
};
let name = name.or_else(|| regular.name())?;
Some((regular_index, regular, name))
})?;
self.current = regular_index + 1;
let metadata = regular.metadata();
let start = regular.cluster();
let vfat = self.vfat.clone();
if metadata.attributes.directory() {
Some(Entry::Dir(Dir::new(vfat, start, name, metadata)))
} else {
Some(Entry::File(File::new(vfat, start, name, metadata)))
}
}
}
| next | identifier_name |
dir.rs | use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::str;
use traits::{self, Dir as DirTrait, Entry as EntryTrait};
use util::VecExt;
use vfat::{Attributes, Date, Metadata, Time, Timestamp};
use vfat::{Cluster, Entry, File, Shared, VFat};
#[derive(Debug)]
pub struct Dir {
vfat: Shared<VFat>,
start: Cluster,
name: String,
metadata: Metadata,
}
impl Dir {
pub fn new(vfat: Shared<VFat>, start: Cluster, name: String, metadata: Metadata) -> Dir {
Dir {
vfat,
start,
name,
metadata,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn metadata(&self) -> &Metadata {
&self.metadata
}
/// Finds the entry named `name` in `self` and returns it. Comparison is
/// case-insensitive.
///
/// # Errors
///
/// If no entry with name `name` exists in `self`, an error of `NotFound` is
/// returned.
///
/// If `name` contains invalid UTF-8 characters, an error of `InvalidInput`
/// is returned.
pub fn find<P: AsRef<OsStr>>(&self, name: P) -> io::Result<Entry> {
let name = name.as_ref().to_str().ok_or(io::Error::new(
io::ErrorKind::InvalidInput,
"name is not valid utf-8",
))?;
let entry = self
.entries()?
.find(|entry| entry.name().eq_ignore_ascii_case(name.as_ref()))
.ok_or(io::Error::new(
io::ErrorKind::NotFound,
format!("{}: not found", name),
))?;
Ok(entry)
}
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct VFatRegularDirEntry {
name: [u8; 8],
extension: [u8; 3],
attributes: u8,
_nt_reserved: u8,
_created_time_tenths_second: u8,
created_time: u16,
created_date: u16,
accessed_date: u16,
cluster_high: u16,
modified_time: u16,
modified_date: u16,
cluster_low: u16,
size: u32,
}
impl fmt::Debug for VFatRegularDirEntry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("VFatRegularDirEntry")
.field("name", &self.name())
.field("attributes", &self.attributes)
.field("created_time", &self.created_time)
.field("created_date", &self.created_date)
.field("accessed_date", &self.accessed_date)
.field("modified_time", &self.modified_time)
.field("modified_date", &self.modified_date)
.field("cluster", &self.cluster())
.finish()
}
}
impl VFatRegularDirEntry {
fn sentinel(&self) -> bool {
self.name[0] == 0x00
}
fn deleted(&self) -> bool |
fn cluster(&self) -> Cluster {
Cluster::from(((self.cluster_high as u32) << 16) | (self.cluster_low as u32))
}
fn created(&self) -> Timestamp {
let date = Date::from_raw(self.created_date);
let time = Time::from_raw(self.created_time);
Timestamp::new(date, time)
}
fn accessed(&self) -> Timestamp {
let date = Date::from_raw(self.accessed_date);
Timestamp::new(date, Default::default())
}
fn modified(&self) -> Timestamp {
let date = Date::from_raw(self.modified_date);
let time = Time::from_raw(self.modified_time);
Timestamp::new(date, time)
}
fn attributes(&self) -> Attributes {
Attributes::from_raw(self.attributes)
}
fn size(&self) -> u64 {
self.size as u64
}
fn metadata(&self) -> Metadata {
let attributes = self.attributes();
let created = self.created();
let accessed = self.accessed();
let modified = self.modified();
let size = self.size();
Metadata {
attributes,
created,
accessed,
modified,
size,
}
}
fn name(&self) -> Option<String> {
let &name_stop = &self.name[..]
.iter()
.position(|&c| c == 0x00 || c == b' ')
.unwrap_or(self.name.len());
let &ext_stop = &self.extension[..]
.iter()
.position(|&c| c == 0x00 || c == b' ')
.unwrap_or(self.extension.len());
let name = str::from_utf8(&self.name[..name_stop]).ok()?;
let extension = str::from_utf8(&self.extension[..ext_stop]).ok()?;
if name == "" {
return None;
}
if extension!= "" {
Some(format!("{}.{}", name, extension))
} else {
Some(format!("{}", name))
}
}
}
#[repr(C, packed)]
#[derive(Copy, Clone, Debug)]
pub struct VFatLfnDirEntry {
seqno: u8,
name_1: [u16; 5],
attributes: u8,
_reserved_1: u8,
dos_checksum: u8,
name_2: [u16; 6],
_reserved_2: [u8; 2],
name_3: [u16; 2],
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct VFatUnknownDirEntry {
_unknown_1: [u8; 11],
attributes: u8,
_unknown_2: [u8; 20],
}
pub union VFatDirEntry {
unknown: VFatUnknownDirEntry,
regular: VFatRegularDirEntry,
long_filename: VFatLfnDirEntry,
}
impl From<VFatRegularDirEntry> for VFatEntry {
fn from(regular: VFatRegularDirEntry) -> VFatEntry {
VFatEntry::Regular(regular)
}
}
impl From<VFatLfnDirEntry> for VFatEntry {
fn from(lfn: VFatLfnDirEntry) -> VFatEntry {
VFatEntry::Lfn(lfn)
}
}
impl<'a> From<&'a VFatDirEntry> for VFatEntry {
fn from(dir_entry: &'a VFatDirEntry) -> VFatEntry {
let attributes = unsafe { dir_entry.unknown.attributes };
let attributes = Attributes::from_raw(attributes);
unsafe {
match (attributes.lfn(), dir_entry) {
(true, &VFatDirEntry { long_filename }) => long_filename.into(),
(false, &VFatDirEntry { regular }) => regular.into(),
}
}
}
}
#[derive(Debug)]
enum VFatEntry {
Regular(VFatRegularDirEntry),
Lfn(VFatLfnDirEntry),
}
impl VFatEntry {
fn regular(&self) -> Option<&VFatRegularDirEntry> {
if let &VFatEntry::Regular(ref reg) = self {
Some(reg)
} else {
None
}
}
fn lfn(&self) -> Option<&VFatLfnDirEntry> {
if let &VFatEntry::Lfn(ref lfn) = self {
Some(lfn)
} else {
None
}
}
}
impl traits::Dir for Dir {
/// The type of entry stored in this directory.
type Entry = Entry;
/// An type that is an iterator over the entries in this directory.
type Iter = DirIter;
/// Returns an interator over the entries in this directory.
fn entries(&self) -> io::Result<Self::Iter> {
let mut vfat = self.vfat.borrow_mut();
let mut buf = vec![];
vfat.read_chain(self.start, &mut buf, None)?;
let buf = unsafe { buf.cast::<VFatDirEntry>() };
Ok(DirIter::new(self.vfat.clone(), buf))
}
}
pub struct DirIter {
vfat: Shared<VFat>,
buf: Vec<VFatDirEntry>,
current: usize,
}
impl DirIter {
fn new(vfat: Shared<VFat>, buf: Vec<VFatDirEntry>) -> DirIter {
DirIter {
vfat,
buf,
current: 0,
}
}
fn name_from_lfn(&self, lfn_start: usize, lfn_stop: usize) -> Option<String> {
let mut entries: Vec<VFatLfnDirEntry> = (&self.buf[lfn_start..lfn_stop])
.iter()
.rev()
.map(|entry| entry.into())
// first ensure that we stop at the preceding regular in the array
.take_while(|entry| {
if let &VFatEntry::Lfn(_) = entry {
true
} else {
false
}
}).filter_map(|entry| match entry.lfn() {
Some(lfn) if lfn.seqno!= 0xE5 => Some(*lfn),
_ => None,
}).collect();
entries.sort_by_key(|lfn| lfn.seqno);
let mut name: Vec<u16> = vec![];
for &lfn in entries.iter() {
name.extend(lfn.name_1.iter());
name.extend(lfn.name_2.iter());
name.extend(lfn.name_3.iter());
}
let end = name
.iter()
.position(|&c| c == 0x0000u16)
.unwrap_or(name.len());
let s = decode_utf16((&name[..end]).iter().cloned())
.map(|c| c.unwrap_or(REPLACEMENT_CHARACTER))
.collect::<String>();
if s.is_empty() {
None
} else {
Some(s)
}
}
}
impl Iterator for DirIter {
type Item = Entry;
fn next(&mut self) -> Option<Self::Item> {
if self.current >= self.buf.len() {
return None;
}
let (regular_index, regular, name) = (&self.buf)[self.current..]
.iter()
.enumerate()
.filter_map(|(i, union_entry)| {
let index = self.current + i;
let entry: VFatEntry = union_entry.into();
let regular = entry.regular()?;
if!regular.deleted() &&!regular.sentinel() {
Some((index, *regular))
} else {
None
}
}).next()
.and_then(|(regular_index, regular)| {
let name = if self.current < regular_index {
self.name_from_lfn(self.current, regular_index)
} else {
None
};
let name = name.or_else(|| regular.name())?;
Some((regular_index, regular, name))
})?;
self.current = regular_index + 1;
let metadata = regular.metadata();
let start = regular.cluster();
let vfat = self.vfat.clone();
if metadata.attributes.directory() {
Some(Entry::Dir(Dir::new(vfat, start, name, metadata)))
} else {
Some(Entry::File(File::new(vfat, start, name, metadata)))
}
}
}
| {
self.name[0] == 0x05 || self.name[0] == 0xE5
} | identifier_body |
mod.rs | use amethyst::{
animation::{AnimationBundle, VertexSkinningBundle},
assets::{
AssetStorage,
Handle,
Loader,
PrefabLoader,
PrefabLoaderSystemDesc,
RonFormat,
},
controls::{ControlTagPrefab, FlyControlBundle},
core::{
HideHierarchySystemDesc,
Parent,
transform::{
Transform,
TransformBundle,
},
},
ecs::{
prelude::*,
storage::{
GenericReadStorage,
GenericWriteStorage,
},
},
audio::AudioBundle,
Error,
gltf::GltfSceneLoaderSystemDesc,
input::{InputBundle, StringBindings},
prelude::*,
renderer::{
plugins::{RenderPbr3D, RenderSkybox, RenderToWindow},
RenderingBundle,
Texture,
types::{DefaultBackend, Mesh, MeshData},
},
ui::{RenderUi, UiBundle},
utils::{
application_root_dir,
auto_fov::AutoFovSystem,
tag::{Tag, TagFinder},
},
};
// Our own rendering plugins.
use amethyst_particle::ParticleRender;
use combat_render::flash::pass::FlashRender;
use space_render::AtmosphereRender;
use space_render::cosmos::{Cosmos, CosmosRender};
use space_render::StarRender;
pub use action::Action;
pub use add_to_limit::*;
use crate::game;
use crate::game::combat::process::Principal;
use crate::game::ui::font::GameFonts;
use crate::state::*;
use rand::Rng;
use crate::game::character::{CharacterStore, CharacterRole};
use crate::game::combat::ability::{AbilityList, AbilityUsability};
use crate::game::combat::ability::charge::ChargeAbility;
use crate::game::combat::ability::spawn::SpawnAbility;
use crate::game::combat::ability::hack::HackAbility;
use crate::game::combat::ability::barrage::BarrageAbility;
use crate::game::combat::ability::twin_shot::TwinShotAbility;
use crate::game::combat::ability::focused_charge::FocusedChargeAbility;
use crate::game::combat::ability::snipe::SnipeAbility;
use crate::game::combat::ability::annihilate::AnnihilateAbility;
use crate::game::map::CombatStore;
use crate::game::combat::{CombatData, Wave};
use crate::game::CoreGameBundle;
use crate::core::rebuild_pass::RebuildPlugin;
pub mod action;
pub mod activity;
pub mod rebuild_pass;
mod add_to_limit;
/// Builds the application object for the game.
/// This contains the built ECS data, which has all the required logic registered.
pub fn build_application<'a, 'b, 'c, S: State<AggregateData<'a, 'b>, StateEvent> + 'c>(initial_state: S) -> Result<Application<'c, AggregateData<'a, 'b>>, Error> {
// Get the application root directory for asset loading.
let app_root = application_root_dir()?;
// Add our meshes directory to the asset loader.
let assets_dir = app_root.join("assets");
// Load display config
let display_config_path = app_root.join("config\\display.ron");
let mut world: World = World::new();
let game_data = AggregateDataBuilder::new()
// GAME SYSTEMS - these are only run when actually 'in' the game world, such as game logic and input systems.
.with_combat(
GameDataBuilder::new()
// Our custom core game bundle data.
.with_bundle(game::combat::CombatBundle)?
.with_bundle(game::character::CharacterBundle)?
)
.with_map(
GameDataBuilder::new()
// Our custom core game bundle data.
.with_bundle(game::map::MapBundle)?
)
// UI SYSTEMS - these should be ui specific and should not be required if not running with a UI.
// TODO: implement UI
.with_ui(
GameDataBuilder::new()
.with_system_desc(
crate::game::control::camera::menu::MenuCameraSystemDesc::default(),
"menu_camera",
&[],
)
)
// CORE SYSTEMS - these should be present at all times during the lifecycle of the game.
// This allows us to load assets at any time, even when not in the game state.
// FOV will update wen window is resized.
//.with_core(AutoFovSystem::default(), "auto_fov", &[])
.with_core(
GameDataBuilder::new()
// Input bundle.
.with_bundle(InputBundle::<StringBindings>::new())?
// Automatic FOV and aspect ration modifications
.with(
AutoFovSystem::new(),
"auto_fov",
&[],
)
// Register drone loader.
// .with_system_desc(
// PrefabLoaderSystemDesc::<game::drone::DronePrefabData>::default(),
// "drone_loader",
// &[],
// )
// Register map loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::map::MapPrefabData>::default(),
"map_loader",
&[],
)
// Register scene loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::map::WorldPrefabData>::default(),
"scene_loader",
&[],
)
// Register character loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::character::CharacterPrefabData>::default(),
"character_loader",
&[],
)
// 3D asset loading using the gltf format.
.with_system_desc(
GltfSceneLoaderSystemDesc::default(),
"gltf_loader",
&["map_loader", "scene_loader", "character_loader"], // This is important so that entity instantiation is performed in a single frame.
)
// Animation system.
// .with_bundle(
// AnimationBundle::<usize, Transform>::new("animation_control", "sampler_interpolation")
// .with_dep(&["gltf_loader"]),
// )?
// Basic transforms.
.with_bundle(TransformBundle::new().with_dep(&[
//"animation_control",
//"sampler_interpolation",
]))?
// Vertex skinning (applying bones to vertices) and manipulating.
// .with_bundle(VertexSkinningBundle::new().with_dep(&[
// "transform_system",
// //"animation_control",
// "sampler_interpolation",
// ]))?
// Amethyst core UI bundle - this requires other systems within the dispatcher to function properly.
.with_bundle(UiBundle::<StringBindings>::new())?
// Audio bundle
.with_bundle(AudioBundle::default())?
// RENDER SYSTEMS - these should be required only for rendering abstract data to the screen.
// Add the render bundle.
.with_bundle(CoreGameBundle)?
.with_system_desc(
HideHierarchySystemDesc::default(),
"hide_hierarchy",
&[],
)
.with_bundle(
RenderingBundle::<DefaultBackend>::new()
// Clear color is black - for custom background colors (e.g. for ui) extra geometry will need to be rendered.
.with_plugin(RenderToWindow::from_config_path(display_config_path)?.with_clear([0.0, 0.0, 0.0, 0.0]))
.with_plugin(RenderPbr3D::default())
// Our own custom plugins
.with_plugin(CosmosRender::new(Some(Cosmos::default())))
.with_plugin(FlashRender::new("textures/flash_billboard.png"))
.with_plugin(StarRender::new("textures/star_glow.png"))
.with_plugin(AtmosphereRender::default())
.with_plugin(ParticleRender::default())
.with_plugin(RebuildPlugin::default())
// Ui rendering.
.with_plugin(RenderUi::default())
)?
);
Ok(Application::new(assets_dir, initial_state, game_data)?)
}
pub fn get_root<'s, 'a, T, P, C>(
parents: &P, components: &'a C,
entity: Entity,
) -> Option<(&'a T, Entity)>
where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> {
if let Some(component) = components.get(entity) {
Some((component, entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root(
parents, components,
parent_ent,
)
}
}
pub fn get_root_cloned<'s, 'a, T, P, C>(
parents: &P, components: &'a C,
entity: Entity,
) -> Option<(T, Entity)>
where T: Component + Clone, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> {
if let Some(component) = components.get(entity) {
Some((component.clone(), entity))
} else { | let parent_ent: Entity = parents.get(entity)?.entity;
get_root_cloned(
parents, components,
parent_ent,
)
}
}
pub fn get_root_mut<'s, 'a, T, P, C>(
parents: &P, components: &'a mut C,
entity: Entity,
) -> Option<(&'a mut T, Entity)>
where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericWriteStorage<Component=T> {
if components.get_mut(entity).is_some() {
Some((components.get_mut(entity).unwrap(), entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root_mut(
parents, components,
parent_ent,
)
}
}
pub fn load_texture(world: &mut World, path: impl Into<String>) -> Handle<Texture> {
if!world.has_value::<AssetStorage::<Texture>>() {
world.insert(AssetStorage::<Texture>::new());
}
let loader = world.read_resource::<Loader>();
loader.load(
path,
amethyst::renderer::formats::texture::ImageFormat::default(),
(),
&world.read_resource::<AssetStorage<Texture>>(),
)
}
/// Rolls a 'dice' based on the specified chance.
pub fn roll(chance: f32) -> bool {
let mut rng = rand::thread_rng();
let value: f32 = rng.gen_range(0.0, 1.0);
if value < chance {
true
} else {
false
}
}
pub fn select_rng(values: &[f32]) -> Option<usize> {
if values.is_empty() {
return None;
}
let mut total: f32 = 0.0;
for value in values {
total += *value;
}
if total <= 0.0 {
return None;
}
let mut rng = rand::thread_rng();
let random: f32 = rng.gen_range(0.0, total);
let mut current: f32 = 0.0;
for (i, value) in values.iter().enumerate() {
if *value!= 0.0 {
let next: f32 = current + *value;
if random >= current && random < next {
return Some(i);
}
current = next;
}
}
panic!("No value selected. The slice must contain non zero values...");
} | random_line_split |
|
mod.rs | use amethyst::{
animation::{AnimationBundle, VertexSkinningBundle},
assets::{
AssetStorage,
Handle,
Loader,
PrefabLoader,
PrefabLoaderSystemDesc,
RonFormat,
},
controls::{ControlTagPrefab, FlyControlBundle},
core::{
HideHierarchySystemDesc,
Parent,
transform::{
Transform,
TransformBundle,
},
},
ecs::{
prelude::*,
storage::{
GenericReadStorage,
GenericWriteStorage,
},
},
audio::AudioBundle,
Error,
gltf::GltfSceneLoaderSystemDesc,
input::{InputBundle, StringBindings},
prelude::*,
renderer::{
plugins::{RenderPbr3D, RenderSkybox, RenderToWindow},
RenderingBundle,
Texture,
types::{DefaultBackend, Mesh, MeshData},
},
ui::{RenderUi, UiBundle},
utils::{
application_root_dir,
auto_fov::AutoFovSystem,
tag::{Tag, TagFinder},
},
};
// Our own rendering plugins.
use amethyst_particle::ParticleRender;
use combat_render::flash::pass::FlashRender;
use space_render::AtmosphereRender;
use space_render::cosmos::{Cosmos, CosmosRender};
use space_render::StarRender;
pub use action::Action;
pub use add_to_limit::*;
use crate::game;
use crate::game::combat::process::Principal;
use crate::game::ui::font::GameFonts;
use crate::state::*;
use rand::Rng;
use crate::game::character::{CharacterStore, CharacterRole};
use crate::game::combat::ability::{AbilityList, AbilityUsability};
use crate::game::combat::ability::charge::ChargeAbility;
use crate::game::combat::ability::spawn::SpawnAbility;
use crate::game::combat::ability::hack::HackAbility;
use crate::game::combat::ability::barrage::BarrageAbility;
use crate::game::combat::ability::twin_shot::TwinShotAbility;
use crate::game::combat::ability::focused_charge::FocusedChargeAbility;
use crate::game::combat::ability::snipe::SnipeAbility;
use crate::game::combat::ability::annihilate::AnnihilateAbility;
use crate::game::map::CombatStore;
use crate::game::combat::{CombatData, Wave};
use crate::game::CoreGameBundle;
use crate::core::rebuild_pass::RebuildPlugin;
pub mod action;
pub mod activity;
pub mod rebuild_pass;
mod add_to_limit;
/// Builds the application object for the game.
/// This contains the built ECS data, which has all the required logic registered.
pub fn build_application<'a, 'b, 'c, S: State<AggregateData<'a, 'b>, StateEvent> + 'c>(initial_state: S) -> Result<Application<'c, AggregateData<'a, 'b>>, Error> {
// Get the application root directory for asset loading.
let app_root = application_root_dir()?;
// Add our meshes directory to the asset loader.
let assets_dir = app_root.join("assets");
// Load display config
let display_config_path = app_root.join("config\\display.ron");
let mut world: World = World::new();
let game_data = AggregateDataBuilder::new()
// GAME SYSTEMS - these are only run when actually 'in' the game world, such as game logic and input systems.
.with_combat(
GameDataBuilder::new()
// Our custom core game bundle data.
.with_bundle(game::combat::CombatBundle)?
.with_bundle(game::character::CharacterBundle)?
)
.with_map(
GameDataBuilder::new()
// Our custom core game bundle data.
.with_bundle(game::map::MapBundle)?
)
// UI SYSTEMS - these should be ui specific and should not be required if not running with a UI.
// TODO: implement UI
.with_ui(
GameDataBuilder::new()
.with_system_desc(
crate::game::control::camera::menu::MenuCameraSystemDesc::default(),
"menu_camera",
&[],
)
)
// CORE SYSTEMS - these should be present at all times during the lifecycle of the game.
// This allows us to load assets at any time, even when not in the game state.
// FOV will update wen window is resized.
//.with_core(AutoFovSystem::default(), "auto_fov", &[])
.with_core(
GameDataBuilder::new()
// Input bundle.
.with_bundle(InputBundle::<StringBindings>::new())?
// Automatic FOV and aspect ration modifications
.with(
AutoFovSystem::new(),
"auto_fov",
&[],
)
// Register drone loader.
// .with_system_desc(
// PrefabLoaderSystemDesc::<game::drone::DronePrefabData>::default(),
// "drone_loader",
// &[],
// )
// Register map loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::map::MapPrefabData>::default(),
"map_loader",
&[],
)
// Register scene loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::map::WorldPrefabData>::default(),
"scene_loader",
&[],
)
// Register character loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::character::CharacterPrefabData>::default(),
"character_loader",
&[],
)
// 3D asset loading using the gltf format.
.with_system_desc(
GltfSceneLoaderSystemDesc::default(),
"gltf_loader",
&["map_loader", "scene_loader", "character_loader"], // This is important so that entity instantiation is performed in a single frame.
)
// Animation system.
// .with_bundle(
// AnimationBundle::<usize, Transform>::new("animation_control", "sampler_interpolation")
// .with_dep(&["gltf_loader"]),
// )?
// Basic transforms.
.with_bundle(TransformBundle::new().with_dep(&[
//"animation_control",
//"sampler_interpolation",
]))?
// Vertex skinning (applying bones to vertices) and manipulating.
// .with_bundle(VertexSkinningBundle::new().with_dep(&[
// "transform_system",
// //"animation_control",
// "sampler_interpolation",
// ]))?
// Amethyst core UI bundle - this requires other systems within the dispatcher to function properly.
.with_bundle(UiBundle::<StringBindings>::new())?
// Audio bundle
.with_bundle(AudioBundle::default())?
// RENDER SYSTEMS - these should be required only for rendering abstract data to the screen.
// Add the render bundle.
.with_bundle(CoreGameBundle)?
.with_system_desc(
HideHierarchySystemDesc::default(),
"hide_hierarchy",
&[],
)
.with_bundle(
RenderingBundle::<DefaultBackend>::new()
// Clear color is black - for custom background colors (e.g. for ui) extra geometry will need to be rendered.
.with_plugin(RenderToWindow::from_config_path(display_config_path)?.with_clear([0.0, 0.0, 0.0, 0.0]))
.with_plugin(RenderPbr3D::default())
// Our own custom plugins
.with_plugin(CosmosRender::new(Some(Cosmos::default())))
.with_plugin(FlashRender::new("textures/flash_billboard.png"))
.with_plugin(StarRender::new("textures/star_glow.png"))
.with_plugin(AtmosphereRender::default())
.with_plugin(ParticleRender::default())
.with_plugin(RebuildPlugin::default())
// Ui rendering.
.with_plugin(RenderUi::default())
)?
);
Ok(Application::new(assets_dir, initial_state, game_data)?)
}
pub fn get_root<'s, 'a, T, P, C>(
parents: &P, components: &'a C,
entity: Entity,
) -> Option<(&'a T, Entity)>
where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> {
if let Some(component) = components.get(entity) {
Some((component, entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root(
parents, components,
parent_ent,
)
}
}
pub fn get_root_cloned<'s, 'a, T, P, C>(
parents: &P, components: &'a C,
entity: Entity,
) -> Option<(T, Entity)>
where T: Component + Clone, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> {
if let Some(component) = components.get(entity) | else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root_cloned(
parents, components,
parent_ent,
)
}
}
pub fn get_root_mut<'s, 'a, T, P, C>(
parents: &P, components: &'a mut C,
entity: Entity,
) -> Option<(&'a mut T, Entity)>
where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericWriteStorage<Component=T> {
if components.get_mut(entity).is_some() {
Some((components.get_mut(entity).unwrap(), entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root_mut(
parents, components,
parent_ent,
)
}
}
pub fn load_texture(world: &mut World, path: impl Into<String>) -> Handle<Texture> {
if!world.has_value::<AssetStorage::<Texture>>() {
world.insert(AssetStorage::<Texture>::new());
}
let loader = world.read_resource::<Loader>();
loader.load(
path,
amethyst::renderer::formats::texture::ImageFormat::default(),
(),
&world.read_resource::<AssetStorage<Texture>>(),
)
}
/// Rolls a 'dice' based on the specified chance.
pub fn roll(chance: f32) -> bool {
let mut rng = rand::thread_rng();
let value: f32 = rng.gen_range(0.0, 1.0);
if value < chance {
true
} else {
false
}
}
pub fn select_rng(values: &[f32]) -> Option<usize> {
if values.is_empty() {
return None;
}
let mut total: f32 = 0.0;
for value in values {
total += *value;
}
if total <= 0.0 {
return None;
}
let mut rng = rand::thread_rng();
let random: f32 = rng.gen_range(0.0, total);
let mut current: f32 = 0.0;
for (i, value) in values.iter().enumerate() {
if *value!= 0.0 {
let next: f32 = current + *value;
if random >= current && random < next {
return Some(i);
}
current = next;
}
}
panic!("No value selected. The slice must contain non zero values...");
} | {
Some((component.clone(), entity))
} | conditional_block |
mod.rs | use amethyst::{
animation::{AnimationBundle, VertexSkinningBundle},
assets::{
AssetStorage,
Handle,
Loader,
PrefabLoader,
PrefabLoaderSystemDesc,
RonFormat,
},
controls::{ControlTagPrefab, FlyControlBundle},
core::{
HideHierarchySystemDesc,
Parent,
transform::{
Transform,
TransformBundle,
},
},
ecs::{
prelude::*,
storage::{
GenericReadStorage,
GenericWriteStorage,
},
},
audio::AudioBundle,
Error,
gltf::GltfSceneLoaderSystemDesc,
input::{InputBundle, StringBindings},
prelude::*,
renderer::{
plugins::{RenderPbr3D, RenderSkybox, RenderToWindow},
RenderingBundle,
Texture,
types::{DefaultBackend, Mesh, MeshData},
},
ui::{RenderUi, UiBundle},
utils::{
application_root_dir,
auto_fov::AutoFovSystem,
tag::{Tag, TagFinder},
},
};
// Our own rendering plugins.
use amethyst_particle::ParticleRender;
use combat_render::flash::pass::FlashRender;
use space_render::AtmosphereRender;
use space_render::cosmos::{Cosmos, CosmosRender};
use space_render::StarRender;
pub use action::Action;
pub use add_to_limit::*;
use crate::game;
use crate::game::combat::process::Principal;
use crate::game::ui::font::GameFonts;
use crate::state::*;
use rand::Rng;
use crate::game::character::{CharacterStore, CharacterRole};
use crate::game::combat::ability::{AbilityList, AbilityUsability};
use crate::game::combat::ability::charge::ChargeAbility;
use crate::game::combat::ability::spawn::SpawnAbility;
use crate::game::combat::ability::hack::HackAbility;
use crate::game::combat::ability::barrage::BarrageAbility;
use crate::game::combat::ability::twin_shot::TwinShotAbility;
use crate::game::combat::ability::focused_charge::FocusedChargeAbility;
use crate::game::combat::ability::snipe::SnipeAbility;
use crate::game::combat::ability::annihilate::AnnihilateAbility;
use crate::game::map::CombatStore;
use crate::game::combat::{CombatData, Wave};
use crate::game::CoreGameBundle;
use crate::core::rebuild_pass::RebuildPlugin;
pub mod action;
pub mod activity;
pub mod rebuild_pass;
mod add_to_limit;
/// Builds the application object for the game.
/// This contains the built ECS data, which has all the required logic registered.
pub fn build_application<'a, 'b, 'c, S: State<AggregateData<'a, 'b>, StateEvent> + 'c>(initial_state: S) -> Result<Application<'c, AggregateData<'a, 'b>>, Error> {
// Get the application root directory for asset loading.
let app_root = application_root_dir()?;
// Add our meshes directory to the asset loader.
let assets_dir = app_root.join("assets");
// Load display config
let display_config_path = app_root.join("config\\display.ron");
let mut world: World = World::new();
let game_data = AggregateDataBuilder::new()
// GAME SYSTEMS - these are only run when actually 'in' the game world, such as game logic and input systems.
.with_combat(
GameDataBuilder::new()
// Our custom core game bundle data.
.with_bundle(game::combat::CombatBundle)?
.with_bundle(game::character::CharacterBundle)?
)
.with_map(
GameDataBuilder::new()
// Our custom core game bundle data.
.with_bundle(game::map::MapBundle)?
)
// UI SYSTEMS - these should be ui specific and should not be required if not running with a UI.
// TODO: implement UI
.with_ui(
GameDataBuilder::new()
.with_system_desc(
crate::game::control::camera::menu::MenuCameraSystemDesc::default(),
"menu_camera",
&[],
)
)
// CORE SYSTEMS - these should be present at all times during the lifecycle of the game.
// This allows us to load assets at any time, even when not in the game state.
// FOV will update wen window is resized.
//.with_core(AutoFovSystem::default(), "auto_fov", &[])
.with_core(
GameDataBuilder::new()
// Input bundle.
.with_bundle(InputBundle::<StringBindings>::new())?
// Automatic FOV and aspect ration modifications
.with(
AutoFovSystem::new(),
"auto_fov",
&[],
)
// Register drone loader.
// .with_system_desc(
// PrefabLoaderSystemDesc::<game::drone::DronePrefabData>::default(),
// "drone_loader",
// &[],
// )
// Register map loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::map::MapPrefabData>::default(),
"map_loader",
&[],
)
// Register scene loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::map::WorldPrefabData>::default(),
"scene_loader",
&[],
)
// Register character loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::character::CharacterPrefabData>::default(),
"character_loader",
&[],
)
// 3D asset loading using the gltf format.
.with_system_desc(
GltfSceneLoaderSystemDesc::default(),
"gltf_loader",
&["map_loader", "scene_loader", "character_loader"], // This is important so that entity instantiation is performed in a single frame.
)
// Animation system.
// .with_bundle(
// AnimationBundle::<usize, Transform>::new("animation_control", "sampler_interpolation")
// .with_dep(&["gltf_loader"]),
// )?
// Basic transforms.
.with_bundle(TransformBundle::new().with_dep(&[
//"animation_control",
//"sampler_interpolation",
]))?
// Vertex skinning (applying bones to vertices) and manipulating.
// .with_bundle(VertexSkinningBundle::new().with_dep(&[
// "transform_system",
// //"animation_control",
// "sampler_interpolation",
// ]))?
// Amethyst core UI bundle - this requires other systems within the dispatcher to function properly.
.with_bundle(UiBundle::<StringBindings>::new())?
// Audio bundle
.with_bundle(AudioBundle::default())?
// RENDER SYSTEMS - these should be required only for rendering abstract data to the screen.
// Add the render bundle.
.with_bundle(CoreGameBundle)?
.with_system_desc(
HideHierarchySystemDesc::default(),
"hide_hierarchy",
&[],
)
.with_bundle(
RenderingBundle::<DefaultBackend>::new()
// Clear color is black - for custom background colors (e.g. for ui) extra geometry will need to be rendered.
.with_plugin(RenderToWindow::from_config_path(display_config_path)?.with_clear([0.0, 0.0, 0.0, 0.0]))
.with_plugin(RenderPbr3D::default())
// Our own custom plugins
.with_plugin(CosmosRender::new(Some(Cosmos::default())))
.with_plugin(FlashRender::new("textures/flash_billboard.png"))
.with_plugin(StarRender::new("textures/star_glow.png"))
.with_plugin(AtmosphereRender::default())
.with_plugin(ParticleRender::default())
.with_plugin(RebuildPlugin::default())
// Ui rendering.
.with_plugin(RenderUi::default())
)?
);
Ok(Application::new(assets_dir, initial_state, game_data)?)
}
pub fn get_root<'s, 'a, T, P, C>(
parents: &P, components: &'a C,
entity: Entity,
) -> Option<(&'a T, Entity)>
where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> {
if let Some(component) = components.get(entity) {
Some((component, entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root(
parents, components,
parent_ent,
)
}
}
pub fn get_root_cloned<'s, 'a, T, P, C>(
parents: &P, components: &'a C,
entity: Entity,
) -> Option<(T, Entity)>
where T: Component + Clone, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> |
pub fn get_root_mut<'s, 'a, T, P, C>(
parents: &P, components: &'a mut C,
entity: Entity,
) -> Option<(&'a mut T, Entity)>
where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericWriteStorage<Component=T> {
if components.get_mut(entity).is_some() {
Some((components.get_mut(entity).unwrap(), entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root_mut(
parents, components,
parent_ent,
)
}
}
pub fn load_texture(world: &mut World, path: impl Into<String>) -> Handle<Texture> {
if!world.has_value::<AssetStorage::<Texture>>() {
world.insert(AssetStorage::<Texture>::new());
}
let loader = world.read_resource::<Loader>();
loader.load(
path,
amethyst::renderer::formats::texture::ImageFormat::default(),
(),
&world.read_resource::<AssetStorage<Texture>>(),
)
}
/// Rolls a 'dice' based on the specified chance.
pub fn roll(chance: f32) -> bool {
let mut rng = rand::thread_rng();
let value: f32 = rng.gen_range(0.0, 1.0);
if value < chance {
true
} else {
false
}
}
pub fn select_rng(values: &[f32]) -> Option<usize> {
if values.is_empty() {
return None;
}
let mut total: f32 = 0.0;
for value in values {
total += *value;
}
if total <= 0.0 {
return None;
}
let mut rng = rand::thread_rng();
let random: f32 = rng.gen_range(0.0, total);
let mut current: f32 = 0.0;
for (i, value) in values.iter().enumerate() {
if *value!= 0.0 {
let next: f32 = current + *value;
if random >= current && random < next {
return Some(i);
}
current = next;
}
}
panic!("No value selected. The slice must contain non zero values...");
} | {
if let Some(component) = components.get(entity) {
Some((component.clone(), entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root_cloned(
parents, components,
parent_ent,
)
}
} | identifier_body |
mod.rs | use amethyst::{
animation::{AnimationBundle, VertexSkinningBundle},
assets::{
AssetStorage,
Handle,
Loader,
PrefabLoader,
PrefabLoaderSystemDesc,
RonFormat,
},
controls::{ControlTagPrefab, FlyControlBundle},
core::{
HideHierarchySystemDesc,
Parent,
transform::{
Transform,
TransformBundle,
},
},
ecs::{
prelude::*,
storage::{
GenericReadStorage,
GenericWriteStorage,
},
},
audio::AudioBundle,
Error,
gltf::GltfSceneLoaderSystemDesc,
input::{InputBundle, StringBindings},
prelude::*,
renderer::{
plugins::{RenderPbr3D, RenderSkybox, RenderToWindow},
RenderingBundle,
Texture,
types::{DefaultBackend, Mesh, MeshData},
},
ui::{RenderUi, UiBundle},
utils::{
application_root_dir,
auto_fov::AutoFovSystem,
tag::{Tag, TagFinder},
},
};
// Our own rendering plugins.
use amethyst_particle::ParticleRender;
use combat_render::flash::pass::FlashRender;
use space_render::AtmosphereRender;
use space_render::cosmos::{Cosmos, CosmosRender};
use space_render::StarRender;
pub use action::Action;
pub use add_to_limit::*;
use crate::game;
use crate::game::combat::process::Principal;
use crate::game::ui::font::GameFonts;
use crate::state::*;
use rand::Rng;
use crate::game::character::{CharacterStore, CharacterRole};
use crate::game::combat::ability::{AbilityList, AbilityUsability};
use crate::game::combat::ability::charge::ChargeAbility;
use crate::game::combat::ability::spawn::SpawnAbility;
use crate::game::combat::ability::hack::HackAbility;
use crate::game::combat::ability::barrage::BarrageAbility;
use crate::game::combat::ability::twin_shot::TwinShotAbility;
use crate::game::combat::ability::focused_charge::FocusedChargeAbility;
use crate::game::combat::ability::snipe::SnipeAbility;
use crate::game::combat::ability::annihilate::AnnihilateAbility;
use crate::game::map::CombatStore;
use crate::game::combat::{CombatData, Wave};
use crate::game::CoreGameBundle;
use crate::core::rebuild_pass::RebuildPlugin;
pub mod action;
pub mod activity;
pub mod rebuild_pass;
mod add_to_limit;
/// Builds the application object for the game.
/// This contains the built ECS data, which has all the required logic registered.
pub fn build_application<'a, 'b, 'c, S: State<AggregateData<'a, 'b>, StateEvent> + 'c>(initial_state: S) -> Result<Application<'c, AggregateData<'a, 'b>>, Error> {
// Get the application root directory for asset loading.
let app_root = application_root_dir()?;
// Add our meshes directory to the asset loader.
let assets_dir = app_root.join("assets");
// Load display config
let display_config_path = app_root.join("config\\display.ron");
let mut world: World = World::new();
let game_data = AggregateDataBuilder::new()
// GAME SYSTEMS - these are only run when actually 'in' the game world, such as game logic and input systems.
.with_combat(
GameDataBuilder::new()
// Our custom core game bundle data.
.with_bundle(game::combat::CombatBundle)?
.with_bundle(game::character::CharacterBundle)?
)
.with_map(
GameDataBuilder::new()
// Our custom core game bundle data.
.with_bundle(game::map::MapBundle)?
)
// UI SYSTEMS - these should be ui specific and should not be required if not running with a UI.
// TODO: implement UI
.with_ui(
GameDataBuilder::new()
.with_system_desc(
crate::game::control::camera::menu::MenuCameraSystemDesc::default(),
"menu_camera",
&[],
)
)
// CORE SYSTEMS - these should be present at all times during the lifecycle of the game.
// This allows us to load assets at any time, even when not in the game state.
// FOV will update wen window is resized.
//.with_core(AutoFovSystem::default(), "auto_fov", &[])
.with_core(
GameDataBuilder::new()
// Input bundle.
.with_bundle(InputBundle::<StringBindings>::new())?
// Automatic FOV and aspect ration modifications
.with(
AutoFovSystem::new(),
"auto_fov",
&[],
)
// Register drone loader.
// .with_system_desc(
// PrefabLoaderSystemDesc::<game::drone::DronePrefabData>::default(),
// "drone_loader",
// &[],
// )
// Register map loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::map::MapPrefabData>::default(),
"map_loader",
&[],
)
// Register scene loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::map::WorldPrefabData>::default(),
"scene_loader",
&[],
)
// Register character loader.
.with_system_desc(
PrefabLoaderSystemDesc::<game::character::CharacterPrefabData>::default(),
"character_loader",
&[],
)
// 3D asset loading using the gltf format.
.with_system_desc(
GltfSceneLoaderSystemDesc::default(),
"gltf_loader",
&["map_loader", "scene_loader", "character_loader"], // This is important so that entity instantiation is performed in a single frame.
)
// Animation system.
// .with_bundle(
// AnimationBundle::<usize, Transform>::new("animation_control", "sampler_interpolation")
// .with_dep(&["gltf_loader"]),
// )?
// Basic transforms.
.with_bundle(TransformBundle::new().with_dep(&[
//"animation_control",
//"sampler_interpolation",
]))?
// Vertex skinning (applying bones to vertices) and manipulating.
// .with_bundle(VertexSkinningBundle::new().with_dep(&[
// "transform_system",
// //"animation_control",
// "sampler_interpolation",
// ]))?
// Amethyst core UI bundle - this requires other systems within the dispatcher to function properly.
.with_bundle(UiBundle::<StringBindings>::new())?
// Audio bundle
.with_bundle(AudioBundle::default())?
// RENDER SYSTEMS - these should be required only for rendering abstract data to the screen.
// Add the render bundle.
.with_bundle(CoreGameBundle)?
.with_system_desc(
HideHierarchySystemDesc::default(),
"hide_hierarchy",
&[],
)
.with_bundle(
RenderingBundle::<DefaultBackend>::new()
// Clear color is black - for custom background colors (e.g. for ui) extra geometry will need to be rendered.
.with_plugin(RenderToWindow::from_config_path(display_config_path)?.with_clear([0.0, 0.0, 0.0, 0.0]))
.with_plugin(RenderPbr3D::default())
// Our own custom plugins
.with_plugin(CosmosRender::new(Some(Cosmos::default())))
.with_plugin(FlashRender::new("textures/flash_billboard.png"))
.with_plugin(StarRender::new("textures/star_glow.png"))
.with_plugin(AtmosphereRender::default())
.with_plugin(ParticleRender::default())
.with_plugin(RebuildPlugin::default())
// Ui rendering.
.with_plugin(RenderUi::default())
)?
);
Ok(Application::new(assets_dir, initial_state, game_data)?)
}
pub fn get_root<'s, 'a, T, P, C>(
parents: &P, components: &'a C,
entity: Entity,
) -> Option<(&'a T, Entity)>
where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> {
if let Some(component) = components.get(entity) {
Some((component, entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root(
parents, components,
parent_ent,
)
}
}
pub fn | <'s, 'a, T, P, C>(
parents: &P, components: &'a C,
entity: Entity,
) -> Option<(T, Entity)>
where T: Component + Clone, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> {
if let Some(component) = components.get(entity) {
Some((component.clone(), entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root_cloned(
parents, components,
parent_ent,
)
}
}
pub fn get_root_mut<'s, 'a, T, P, C>(
parents: &P, components: &'a mut C,
entity: Entity,
) -> Option<(&'a mut T, Entity)>
where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericWriteStorage<Component=T> {
if components.get_mut(entity).is_some() {
Some((components.get_mut(entity).unwrap(), entity))
} else {
let parent_ent: Entity = parents.get(entity)?.entity;
get_root_mut(
parents, components,
parent_ent,
)
}
}
pub fn load_texture(world: &mut World, path: impl Into<String>) -> Handle<Texture> {
if!world.has_value::<AssetStorage::<Texture>>() {
world.insert(AssetStorage::<Texture>::new());
}
let loader = world.read_resource::<Loader>();
loader.load(
path,
amethyst::renderer::formats::texture::ImageFormat::default(),
(),
&world.read_resource::<AssetStorage<Texture>>(),
)
}
/// Rolls a 'dice' based on the specified chance.
pub fn roll(chance: f32) -> bool {
let mut rng = rand::thread_rng();
let value: f32 = rng.gen_range(0.0, 1.0);
if value < chance {
true
} else {
false
}
}
pub fn select_rng(values: &[f32]) -> Option<usize> {
if values.is_empty() {
return None;
}
let mut total: f32 = 0.0;
for value in values {
total += *value;
}
if total <= 0.0 {
return None;
}
let mut rng = rand::thread_rng();
let random: f32 = rng.gen_range(0.0, total);
let mut current: f32 = 0.0;
for (i, value) in values.iter().enumerate() {
if *value!= 0.0 {
let next: f32 = current + *value;
if random >= current && random < next {
return Some(i);
}
current = next;
}
}
panic!("No value selected. The slice must contain non zero values...");
} | get_root_cloned | identifier_name |
revaultd.rs | bitcoin::{
secp256k1,
util::bip32::{ChildNumber, ExtendedPubKey},
Address, BlockHash, PublicKey as BitcoinPublicKey, Script, TxOut,
},
miniscript::descriptor::{DescriptorPublicKey, DescriptorTrait},
scripts::{
CpfpDescriptor, DepositDescriptor, DerivedCpfpDescriptor, DerivedDepositDescriptor,
DerivedUnvaultDescriptor, EmergencyAddress, UnvaultDescriptor,
},
transactions::{
CancelTransaction, DepositTransaction, EmergencyTransaction, UnvaultEmergencyTransaction,
UnvaultTransaction,
},
};
/// The status of a [Vault], depends both on the block chain and the set of pre-signed
/// transactions
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VaultStatus {
/// The deposit transaction has less than 6 confirmations
Unconfirmed,
/// The deposit transaction has more than 6 confirmations
Funded,
/// The revocation transactions are signed by us
Securing,
/// The revocation transactions are signed by everyone
Secured,
/// The unvault transaction is signed (implies that the second emergency and the
/// cancel transaction are signed).
Activating,
/// The unvault transaction is signed (implies that the second emergency and the
/// cancel transaction are signed).
Active,
/// The unvault transaction has been broadcast
Unvaulting,
/// The unvault transaction is confirmed
Unvaulted,
/// The cancel transaction has been broadcast
Canceling,
/// The cancel transaction is confirmed
Canceled,
/// The first emergency transactions has been broadcast
EmergencyVaulting,
/// The first emergency transactions is confirmed
EmergencyVaulted,
/// The unvault emergency transactions has been broadcast
UnvaultEmergencyVaulting,
/// The unvault emergency transactions is confirmed
UnvaultEmergencyVaulted,
/// The spend transaction has been broadcast
Spending,
// TODO: At what depth do we forget it?
/// The spend transaction is confirmed
Spent,
}
impl TryFrom<u32> for VaultStatus {
type Error = ();
fn try_from(n: u32) -> Result<Self, Self::Error> {
match n {
0 => Ok(Self::Unconfirmed),
1 => Ok(Self::Funded),
2 => Ok(Self::Securing),
3 => Ok(Self::Secured),
4 => Ok(Self::Activating),
5 => Ok(Self::Active),
6 => Ok(Self::Unvaulting),
7 => Ok(Self::Unvaulted),
8 => Ok(Self::Canceling),
9 => Ok(Self::Canceled),
10 => Ok(Self::EmergencyVaulting),
11 => Ok(Self::EmergencyVaulted),
12 => Ok(Self::UnvaultEmergencyVaulting),
13 => Ok(Self::UnvaultEmergencyVaulted),
14 => Ok(Self::Spending),
15 => Ok(Self::Spent),
_ => Err(()),
}
}
}
impl FromStr for VaultStatus {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"unconfirmed" => Ok(Self::Unconfirmed),
"funded" => Ok(Self::Funded),
"securing" => Ok(Self::Securing),
"secured" => Ok(Self::Secured),
"activating" => Ok(Self::Activating),
"active" => Ok(Self::Active),
"unvaulting" => Ok(Self::Unvaulting),
"unvaulted" => Ok(Self::Unvaulted),
"canceling" => Ok(Self::Canceling),
"canceled" => Ok(Self::Canceled),
"emergencyvaulting" => Ok(Self::EmergencyVaulting),
"emergencyvaulted" => Ok(Self::EmergencyVaulted),
"unvaultemergencyvaulting" => Ok(Self::UnvaultEmergencyVaulting),
"unvaultemergencyvaulted" => Ok(Self::UnvaultEmergencyVaulted),
"spending" => Ok(Self::Spending),
"spent" => Ok(Self::Spent),
_ => Err(()),
}
}
}
impl fmt::Display for VaultStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match *self {
Self::Unconfirmed => "unconfirmed",
Self::Funded => "funded",
Self::Securing => "securing",
Self::Secured => "secured",
Self::Activating => "activating",
Self::Active => "active",
Self::Unvaulting => "unvaulting",
Self::Unvaulted => "unvaulted",
Self::Canceling => "canceling",
Self::Canceled => "canceled",
Self::EmergencyVaulting => "emergencyvaulting",
Self::EmergencyVaulted => "emergencyvaulted",
Self::UnvaultEmergencyVaulting => "unvaultemergencyvaulting",
Self::UnvaultEmergencyVaulted => "unvaultemergencyvaulted",
Self::Spending => "spending",
Self::Spent => "spent",
}
)
}
}
// An error related to the initialization of communication keys
#[derive(Debug)]
enum KeyError {
ReadingKey(io::Error),
WritingKey(io::Error),
}
impl fmt::Display for KeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::ReadingKey(e) => write!(f, "Error reading Noise key: '{}'", e),
Self::WritingKey(e) => write!(f, "Error writing Noise key: '{}'", e),
}
}
}
impl std::error::Error for KeyError {}
// The communication keys are (for now) hot, so we just create it ourselves on first run.
fn read_or_create_noise_key(secret_file: PathBuf) -> Result<NoisePrivKey, KeyError> {
let mut noise_secret = NoisePrivKey([0; 32]);
if!secret_file.as_path().exists() {
log::info!(
"No Noise private key at '{:?}', generating a new one",
secret_file
);
noise_secret = sodiumoxide::crypto::box_::gen_keypair().1;
// We create it in read-only but open it in write only.
let mut options = fs::OpenOptions::new();
options = options.write(true).create_new(true).clone();
// FIXME: handle Windows ACLs
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options = options.mode(0o400).clone();
}
let mut fd = options.open(secret_file).map_err(KeyError::WritingKey)?;
fd.write_all(&noise_secret.as_ref())
.map_err(KeyError::WritingKey)?;
} else {
let mut noise_secret_fd = fs::File::open(secret_file).map_err(KeyError::ReadingKey)?;
noise_secret_fd
.read_exact(&mut noise_secret.0)
.map_err(KeyError::ReadingKey)?;
}
// TODO: have a decent memory management and mlock() the key
assert!(noise_secret.0!= [0; 32]);
Ok(noise_secret)
}
/// A vault is defined as a confirmed utxo paying to the Vault Descriptor for which
/// we have a set of pre-signed transaction (emergency, cancel, unvault).
/// Depending on its status we may not yet be in possession of part -or the entirety-
/// of the pre-signed transactions.
/// Likewise, depending on our role (manager or stakeholder), we may not have the
/// emergency transactions.
pub struct _Vault {
pub deposit_txo: TxOut,
pub status: VaultStatus,
pub vault_tx: Option<DepositTransaction>,
pub emergency_tx: Option<EmergencyTransaction>,
pub unvault_tx: Option<UnvaultTransaction>,
pub cancel_tx: Option<CancelTransaction>,
pub unvault_emergency_tx: Option<UnvaultEmergencyTransaction>,
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct BlockchainTip {
pub height: u32,
pub hash: BlockHash,
}
/// Our global state
pub struct RevaultD {
// Bitcoind stuff
/// Everything we need to know to talk to bitcoind
pub bitcoind_config: BitcoindConfig,
/// Last block we heard about
pub tip: Option<BlockchainTip>,
/// Minimum confirmations before considering a deposit as mature
pub min_conf: u32,
// Scripts stuff
/// Who am i, and where am i in all this mess?
pub our_stk_xpub: Option<ExtendedPubKey>,
pub our_man_xpub: Option<ExtendedPubKey>,
/// The miniscript descriptor of vault's outputs scripts
pub deposit_descriptor: DepositDescriptor,
/// The miniscript descriptor of unvault's outputs scripts
pub unvault_descriptor: UnvaultDescriptor,
/// The miniscript descriptor of CPFP output scripts (in unvault and spend transaction)
pub cpfp_descriptor: CpfpDescriptor,
/// The Emergency address, only available if we are a stakeholder
pub emergency_address: Option<EmergencyAddress>,
/// We don't make an enormous deal of address reuse (we cancel to the same keys),
/// however we at least try to generate new addresses once they're used.
// FIXME: think more about desync reconciliation..
pub current_unused_index: ChildNumber,
/// The secp context required by the xpub one.. We'll eventually use it to verify keys.
pub secp_ctx: secp256k1::Secp256k1<secp256k1::VerifyOnly>,
/// The locktime to use on all created transaction. Always 0 for now.
pub lock_time: u32,
// Network stuff
/// The static private key we use to establish connections to servers. We reuse it, but Trevor
/// said it's fine! https://github.com/noiseprotocol/noise_spec/blob/master/noise.md#14-security-considerations
pub noise_secret: NoisePrivKey,
/// The ip:port the coordinator is listening on. TODO: Tor
pub coordinator_host: SocketAddr,
/// The static public key to enact the Noise channel with the Coordinator
pub coordinator_noisekey: NoisePubKey,
pub coordinator_poll_interval: time::Duration,
/// The ip:port (TODO: Tor) and Noise public key of each cosigning server, only set if we are
/// a manager.
pub cosigs: Option<Vec<(SocketAddr, NoisePubKey)>>,
// 'Wallet' stuff
/// A map from a scriptPubKey to a derivation index. Used to retrieve the actual public
/// keys used to generate a script from bitcoind until we can pass it xpub-expressed
/// Miniscript descriptors.
pub derivation_index_map: HashMap<Script, ChildNumber>,
/// The id of the wallet used in the db
pub wallet_id: Option<u32>,
// Misc stuff
/// We store all our data in one place, that's here.
pub data_dir: PathBuf,
/// Should we run as a daemon? (Default: yes)
pub daemon: bool,
// TODO: servers connection stuff
}
fn create_datadir(datadir_path: &PathBuf) -> Result<(), std::io::Error> {
#[cfg(unix)]
return {
use fs::DirBuilder;
use std::os::unix::fs::DirBuilderExt;
let mut builder = DirBuilder::new();
builder.mode(0o700).recursive(true).create(datadir_path)
};
#[cfg(not(unix))]
return {
// FIXME: make Windows secure (again?)
fs::create_dir_all(datadir_path)
};
}
impl RevaultD {
/// Creates our global state by consuming the static configuration
pub fn from_config(config: Config) -> Result<RevaultD, Box<dyn std::error::Error>> {
let our_man_xpub = config.manager_config.as_ref().map(|x| x.xpub);
let our_stk_xpub = config.stakeholder_config.as_ref().map(|x| x.xpub);
// Config should have checked that!
assert!(our_man_xpub.is_some() || our_stk_xpub.is_some());
let deposit_descriptor = config.scripts_config.deposit_descriptor;
let unvault_descriptor = config.scripts_config.unvault_descriptor;
let cpfp_descriptor = config.scripts_config.cpfp_descriptor;
let emergency_address = config.stakeholder_config.map(|x| x.emergency_address);
let mut data_dir = config.data_dir.unwrap_or(config_folder_path()?);
data_dir.push(config.bitcoind_config.network.to_string());
if!data_dir.as_path().exists() {
if let Err(e) = create_datadir(&data_dir) {
return Err(Box::from(ConfigError(format!(
"Could not create data dir '{:?}': {}.",
data_dir,
e.to_string()
))));
}
}
data_dir = fs::canonicalize(data_dir)?;
let data_dir_str = data_dir
.to_str()
.expect("Impossible: the datadir path is valid unicode");
let noise_secret_file = [data_dir_str, "noise_secret"].iter().collect();
let noise_secret = read_or_create_noise_key(noise_secret_file)?;
// TODO: support hidden services
let coordinator_host = SocketAddr::from_str(&config.coordinator_host)?;
let coordinator_noisekey = config.coordinator_noise_key;
let coordinator_poll_interval = config.coordinator_poll_seconds;
let cosigs = config.manager_config.map(|config| {
config
.cosigners
.into_iter()
.map(|config| (config.host, config.noise_key))
.collect()
});
let daemon =!matches!(config.daemon, Some(false));
let secp_ctx = secp256k1::Secp256k1::verification_only();
Ok(RevaultD {
our_stk_xpub,
our_man_xpub,
deposit_descriptor,
unvault_descriptor,
cpfp_descriptor,
secp_ctx,
data_dir,
daemon,
emergency_address,
noise_secret,
coordinator_host,
coordinator_noisekey,
coordinator_poll_interval,
cosigs,
lock_time: 0,
min_conf: config.min_conf,
bitcoind_config: config.bitcoind_config,
tip: None,
// Will be updated by the database
current_unused_index: ChildNumber::from(0),
// FIXME: we don't need SipHash for those, use a faster alternative
derivation_index_map: HashMap::new(),
// Will be updated soon (:tm:)
wallet_id: None,
})
}
fn file_from_datadir(&self, file_name: &str) -> PathBuf {
let data_dir_str = self
.data_dir
.to_str()
.expect("Impossible: the datadir path is valid unicode");
[data_dir_str, file_name].iter().collect()
}
/// Our Noise static public key
pub fn noise_pubkey(&self) -> NoisePubKey {
let scalar = curve25519::Scalar(self.noise_secret.0);
NoisePubKey(curve25519::scalarmult_base(&scalar).0)
}
pub fn vault_address(&self, child_number: ChildNumber) -> Address {
self.deposit_descriptor
.derive(child_number, &self.secp_ctx)
.inner()
.address(self.bitcoind_config.network)
.expect("deposit_descriptor is a wsh")
}
pub fn unvault_address(&self, child_number: ChildNumber) -> Address {
self.unvault_descriptor
.derive(child_number, &self.secp_ctx)
.inner()
.address(self.bitcoind_config.network)
.expect("unvault_descriptor is a wsh")
}
pub fn gap_limit(&self) -> u32 {
100
}
pub fn watchonly_wallet_name(&self) -> Option<String> {
self.wallet_id
.map(|ref id| format!("revaultd-watchonly-wallet-{}", id))
}
pub fn log_file(&self) -> PathBuf {
self.file_from_datadir("log")
}
pub fn pid_file(&self) -> PathBuf {
self.file_from_datadir("revaultd.pid")
}
pub fn db_file(&self) -> PathBuf {
self.file_from_datadir("revaultd.sqlite3")
}
pub fn watchonly_wallet_file(&self) -> Option<String> {
self.watchonly_wallet_name().map(|ref name| {
self.file_from_datadir(name)
.to_str()
.expect("Valid utf-8")
.to_string()
})
}
pub fn rpc_socket_file(&self) -> PathBuf {
self.file_from_datadir("revaultd_rpc")
}
pub fn is_stakeholder(&self) -> bool {
self.our_stk_xpub.is_some()
}
pub fn is_manager(&self) -> bool {
self.our_man_xpub.is_some()
}
pub fn | (&self) -> Address {
self.vault_address(self.current_unused_index)
}
pub fn last_deposit_address(&self) -> Address {
let raw_index: u32 = self.current_unused_index.into();
// FIXME: this should fail instead of creating a hardened index
self.vault_address(ChildNumber::from(raw_index + self.gap_limit()))
}
pub fn last_unvault_address(&self) -> Address {
let raw_index: u32 = self.current_unused_index.into();
// FIXME: this should fail instead of creating a hardened index
self.unvault_address(ChildNumber::from(raw_index + self.gap_limit()))
}
/// All deposit addresses as strings up to the gap limit (100)
pub fn all_deposit_addresses(&mut self) -> Vec<String> {
self.derivation_index_map
.keys()
.map(|s| {
Address::from_script(s, self.bitcoind_config.network)
.expect("Created from P2WSH address")
.to_string()
})
.collect()
}
/// All unvault addresses as strings up to the gap limit (100)
pub fn all_unvault_addresses(&mut self) -> Vec<String> {
let raw_index: u32 = self.current_unused_index.into();
(0..raw_index + self.gap_limit())
.map(|raw_index| {
// FIXME: this should fail instead of creating a hardened index
self.unvault_address(ChildNumber::from(raw_index))
.to_string()
})
.collect()
}
pub fn derived_deposit_descriptor(&self, index: ChildNumber) -> DerivedDepositDescriptor {
self.deposit_descriptor.derive(index, &self.secp_ctx)
}
pub fn derived_unvault_descriptor(&self, index: ChildNumber) -> DerivedUnvaultDescriptor {
self.unvault_descriptor.derive(index, &self.secp_ctx)
}
pub fn derived_cpfp_descriptor(&self, index: ChildNumber) -> DerivedCpfpDescriptor {
self.cpfp_descriptor.derive(index, &self.secp_ctx)
}
pub fn stakeholders_xpubs(&self) -> Vec<DescriptorPublicKey> {
self.deposit_descriptor.xpubs()
}
pub fn managers_xpubs(&self) -> Vec<DescriptorPublicKey> {
// The managers' xpubs are all the xpubs from the Unvault descriptor except the
// Stakehodlers' ones and the Cosigning Servers' ones.
let stk_xpubs = self.stakeholders_xpubs();
self.unvault_descriptor
.xpubs()
.into_iter()
.filter_map(|xpub| {
match xpub {
DescriptorPublicKey::SinglePub(_) => None, // Cosig
DescriptorPublicKey::XPub(_) => {
if stk_xpubs.contains(&xpub) {
None // Stakeholder
} else {
Some(xpub) // Manager
}
}
}
})
.collect()
}
pub fn stakeholders_xpubs_at(&self, index: ChildNumber) -> Vec<BitcoinPublicKey> {
self.deposit_descriptor
.xpubs()
.into_iter()
.map(|desc_xpub| {
desc_xpub
.derive(index.into())
.derive_public_key(&self.secp_ctx)
.expect("Is derived, and there is never any hardened path")
})
.collect()
}
pub fn our_stk_xpub_at(&self, index: ChildNumber) -> Option<BitcoinPublicKey> {
self.our_stk_xpub.map(|xpub| {
xpub.derive_pub(&self.secp_ctx, &[index])
.expect("The derivation index stored in the database is sane (unhardened)")
| deposit_address | identifier_name |
revaultd.rs | bitcoin::{
secp256k1,
util::bip32::{ChildNumber, ExtendedPubKey},
Address, BlockHash, PublicKey as BitcoinPublicKey, Script, TxOut,
},
miniscript::descriptor::{DescriptorPublicKey, DescriptorTrait},
scripts::{
CpfpDescriptor, DepositDescriptor, DerivedCpfpDescriptor, DerivedDepositDescriptor,
DerivedUnvaultDescriptor, EmergencyAddress, UnvaultDescriptor,
},
transactions::{
CancelTransaction, DepositTransaction, EmergencyTransaction, UnvaultEmergencyTransaction,
UnvaultTransaction,
},
};
/// The status of a [Vault], depends both on the block chain and the set of pre-signed
/// transactions
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VaultStatus {
/// The deposit transaction has less than 6 confirmations
Unconfirmed,
/// The deposit transaction has more than 6 confirmations
Funded,
/// The revocation transactions are signed by us
Securing,
/// The revocation transactions are signed by everyone
Secured,
/// The unvault transaction is signed (implies that the second emergency and the
/// cancel transaction are signed).
Activating,
/// The unvault transaction is signed (implies that the second emergency and the
/// cancel transaction are signed).
Active,
/// The unvault transaction has been broadcast
Unvaulting,
/// The unvault transaction is confirmed
Unvaulted,
/// The cancel transaction has been broadcast
Canceling,
/// The cancel transaction is confirmed
Canceled,
/// The first emergency transactions has been broadcast
EmergencyVaulting,
/// The first emergency transactions is confirmed
EmergencyVaulted,
/// The unvault emergency transactions has been broadcast
UnvaultEmergencyVaulting,
/// The unvault emergency transactions is confirmed
UnvaultEmergencyVaulted,
/// The spend transaction has been broadcast
Spending,
// TODO: At what depth do we forget it?
/// The spend transaction is confirmed
Spent,
}
impl TryFrom<u32> for VaultStatus {
type Error = ();
fn try_from(n: u32) -> Result<Self, Self::Error> {
match n {
0 => Ok(Self::Unconfirmed),
1 => Ok(Self::Funded),
2 => Ok(Self::Securing),
3 => Ok(Self::Secured),
4 => Ok(Self::Activating),
5 => Ok(Self::Active),
6 => Ok(Self::Unvaulting),
7 => Ok(Self::Unvaulted),
8 => Ok(Self::Canceling),
9 => Ok(Self::Canceled),
10 => Ok(Self::EmergencyVaulting),
11 => Ok(Self::EmergencyVaulted),
12 => Ok(Self::UnvaultEmergencyVaulting),
13 => Ok(Self::UnvaultEmergencyVaulted),
14 => Ok(Self::Spending),
15 => Ok(Self::Spent),
_ => Err(()),
}
}
}
impl FromStr for VaultStatus {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"unconfirmed" => Ok(Self::Unconfirmed),
"funded" => Ok(Self::Funded),
"securing" => Ok(Self::Securing),
"secured" => Ok(Self::Secured),
"activating" => Ok(Self::Activating),
"active" => Ok(Self::Active),
"unvaulting" => Ok(Self::Unvaulting),
"unvaulted" => Ok(Self::Unvaulted),
"canceling" => Ok(Self::Canceling),
"canceled" => Ok(Self::Canceled),
"emergencyvaulting" => Ok(Self::EmergencyVaulting),
"emergencyvaulted" => Ok(Self::EmergencyVaulted),
"unvaultemergencyvaulting" => Ok(Self::UnvaultEmergencyVaulting),
"unvaultemergencyvaulted" => Ok(Self::UnvaultEmergencyVaulted),
"spending" => Ok(Self::Spending),
"spent" => Ok(Self::Spent),
_ => Err(()),
}
}
}
impl fmt::Display for VaultStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match *self {
Self::Unconfirmed => "unconfirmed",
Self::Funded => "funded",
Self::Securing => "securing",
Self::Secured => "secured",
Self::Activating => "activating",
Self::Active => "active",
Self::Unvaulting => "unvaulting",
Self::Unvaulted => "unvaulted",
Self::Canceling => "canceling",
Self::Canceled => "canceled",
Self::EmergencyVaulting => "emergencyvaulting",
Self::EmergencyVaulted => "emergencyvaulted",
Self::UnvaultEmergencyVaulting => "unvaultemergencyvaulting",
Self::UnvaultEmergencyVaulted => "unvaultemergencyvaulted",
Self::Spending => "spending",
Self::Spent => "spent",
}
)
}
}
// An error related to the initialization of communication keys
#[derive(Debug)]
enum KeyError {
ReadingKey(io::Error),
WritingKey(io::Error),
}
impl fmt::Display for KeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::ReadingKey(e) => write!(f, "Error reading Noise key: '{}'", e),
Self::WritingKey(e) => write!(f, "Error writing Noise key: '{}'", e),
}
}
}
impl std::error::Error for KeyError {}
// The communication keys are (for now) hot, so we just create it ourselves on first run.
fn read_or_create_noise_key(secret_file: PathBuf) -> Result<NoisePrivKey, KeyError> {
let mut noise_secret = NoisePrivKey([0; 32]);
if!secret_file.as_path().exists() {
log::info!(
"No Noise private key at '{:?}', generating a new one",
secret_file
);
noise_secret = sodiumoxide::crypto::box_::gen_keypair().1;
// We create it in read-only but open it in write only.
let mut options = fs::OpenOptions::new();
options = options.write(true).create_new(true).clone();
// FIXME: handle Windows ACLs
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options = options.mode(0o400).clone();
}
let mut fd = options.open(secret_file).map_err(KeyError::WritingKey)?;
fd.write_all(&noise_secret.as_ref())
.map_err(KeyError::WritingKey)?;
} else {
let mut noise_secret_fd = fs::File::open(secret_file).map_err(KeyError::ReadingKey)?;
noise_secret_fd
.read_exact(&mut noise_secret.0)
.map_err(KeyError::ReadingKey)?;
}
// TODO: have a decent memory management and mlock() the key
assert!(noise_secret.0!= [0; 32]);
Ok(noise_secret)
}
/// A vault is defined as a confirmed utxo paying to the Vault Descriptor for which
/// we have a set of pre-signed transaction (emergency, cancel, unvault).
/// Depending on its status we may not yet be in possession of part -or the entirety-
/// of the pre-signed transactions.
/// Likewise, depending on our role (manager or stakeholder), we may not have the
/// emergency transactions.
pub struct _Vault {
pub deposit_txo: TxOut,
pub status: VaultStatus,
pub vault_tx: Option<DepositTransaction>,
pub emergency_tx: Option<EmergencyTransaction>,
pub unvault_tx: Option<UnvaultTransaction>,
pub cancel_tx: Option<CancelTransaction>,
pub unvault_emergency_tx: Option<UnvaultEmergencyTransaction>,
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct BlockchainTip {
pub height: u32,
pub hash: BlockHash,
}
/// Our global state
pub struct RevaultD {
// Bitcoind stuff
/// Everything we need to know to talk to bitcoind
pub bitcoind_config: BitcoindConfig,
/// Last block we heard about
pub tip: Option<BlockchainTip>,
/// Minimum confirmations before considering a deposit as mature
pub min_conf: u32,
// Scripts stuff
/// Who am i, and where am i in all this mess?
pub our_stk_xpub: Option<ExtendedPubKey>,
pub our_man_xpub: Option<ExtendedPubKey>,
/// The miniscript descriptor of vault's outputs scripts
pub deposit_descriptor: DepositDescriptor,
/// The miniscript descriptor of unvault's outputs scripts
pub unvault_descriptor: UnvaultDescriptor,
/// The miniscript descriptor of CPFP output scripts (in unvault and spend transaction)
pub cpfp_descriptor: CpfpDescriptor,
/// The Emergency address, only available if we are a stakeholder
pub emergency_address: Option<EmergencyAddress>,
/// We don't make an enormous deal of address reuse (we cancel to the same keys),
/// however we at least try to generate new addresses once they're used.
// FIXME: think more about desync reconciliation..
pub current_unused_index: ChildNumber,
/// The secp context required by the xpub one.. We'll eventually use it to verify keys.
pub secp_ctx: secp256k1::Secp256k1<secp256k1::VerifyOnly>,
/// The locktime to use on all created transaction. Always 0 for now.
pub lock_time: u32,
// Network stuff
/// The static private key we use to establish connections to servers. We reuse it, but Trevor
/// said it's fine! https://github.com/noiseprotocol/noise_spec/blob/master/noise.md#14-security-considerations
pub noise_secret: NoisePrivKey,
/// The ip:port the coordinator is listening on. TODO: Tor
pub coordinator_host: SocketAddr,
/// The static public key to enact the Noise channel with the Coordinator
pub coordinator_noisekey: NoisePubKey,
pub coordinator_poll_interval: time::Duration,
/// The ip:port (TODO: Tor) and Noise public key of each cosigning server, only set if we are
/// a manager.
pub cosigs: Option<Vec<(SocketAddr, NoisePubKey)>>,
// 'Wallet' stuff
/// A map from a scriptPubKey to a derivation index. Used to retrieve the actual public
/// keys used to generate a script from bitcoind until we can pass it xpub-expressed
/// Miniscript descriptors.
pub derivation_index_map: HashMap<Script, ChildNumber>,
/// The id of the wallet used in the db
pub wallet_id: Option<u32>,
// Misc stuff
/// We store all our data in one place, that's here.
pub data_dir: PathBuf,
/// Should we run as a daemon? (Default: yes)
pub daemon: bool,
// TODO: servers connection stuff
}
fn create_datadir(datadir_path: &PathBuf) -> Result<(), std::io::Error> {
#[cfg(unix)]
return {
use fs::DirBuilder;
use std::os::unix::fs::DirBuilderExt;
let mut builder = DirBuilder::new();
builder.mode(0o700).recursive(true).create(datadir_path)
};
#[cfg(not(unix))]
return {
// FIXME: make Windows secure (again?)
fs::create_dir_all(datadir_path)
};
}
impl RevaultD {
/// Creates our global state by consuming the static configuration
pub fn from_config(config: Config) -> Result<RevaultD, Box<dyn std::error::Error>> {
let our_man_xpub = config.manager_config.as_ref().map(|x| x.xpub);
let our_stk_xpub = config.stakeholder_config.as_ref().map(|x| x.xpub);
// Config should have checked that!
assert!(our_man_xpub.is_some() || our_stk_xpub.is_some());
let deposit_descriptor = config.scripts_config.deposit_descriptor;
let unvault_descriptor = config.scripts_config.unvault_descriptor;
let cpfp_descriptor = config.scripts_config.cpfp_descriptor;
let emergency_address = config.stakeholder_config.map(|x| x.emergency_address);
let mut data_dir = config.data_dir.unwrap_or(config_folder_path()?);
data_dir.push(config.bitcoind_config.network.to_string());
if!data_dir.as_path().exists() {
if let Err(e) = create_datadir(&data_dir) {
return Err(Box::from(ConfigError(format!(
"Could not create data dir '{:?}': {}.",
data_dir, | e.to_string()
))));
}
}
data_dir = fs::canonicalize(data_dir)?;
let data_dir_str = data_dir
.to_str()
.expect("Impossible: the datadir path is valid unicode");
let noise_secret_file = [data_dir_str, "noise_secret"].iter().collect();
let noise_secret = read_or_create_noise_key(noise_secret_file)?;
// TODO: support hidden services
let coordinator_host = SocketAddr::from_str(&config.coordinator_host)?;
let coordinator_noisekey = config.coordinator_noise_key;
let coordinator_poll_interval = config.coordinator_poll_seconds;
let cosigs = config.manager_config.map(|config| {
config
.cosigners
.into_iter()
.map(|config| (config.host, config.noise_key))
.collect()
});
let daemon =!matches!(config.daemon, Some(false));
let secp_ctx = secp256k1::Secp256k1::verification_only();
Ok(RevaultD {
our_stk_xpub,
our_man_xpub,
deposit_descriptor,
unvault_descriptor,
cpfp_descriptor,
secp_ctx,
data_dir,
daemon,
emergency_address,
noise_secret,
coordinator_host,
coordinator_noisekey,
coordinator_poll_interval,
cosigs,
lock_time: 0,
min_conf: config.min_conf,
bitcoind_config: config.bitcoind_config,
tip: None,
// Will be updated by the database
current_unused_index: ChildNumber::from(0),
// FIXME: we don't need SipHash for those, use a faster alternative
derivation_index_map: HashMap::new(),
// Will be updated soon (:tm:)
wallet_id: None,
})
}
fn file_from_datadir(&self, file_name: &str) -> PathBuf {
let data_dir_str = self
.data_dir
.to_str()
.expect("Impossible: the datadir path is valid unicode");
[data_dir_str, file_name].iter().collect()
}
/// Our Noise static public key
pub fn noise_pubkey(&self) -> NoisePubKey {
let scalar = curve25519::Scalar(self.noise_secret.0);
NoisePubKey(curve25519::scalarmult_base(&scalar).0)
}
pub fn vault_address(&self, child_number: ChildNumber) -> Address {
self.deposit_descriptor
.derive(child_number, &self.secp_ctx)
.inner()
.address(self.bitcoind_config.network)
.expect("deposit_descriptor is a wsh")
}
pub fn unvault_address(&self, child_number: ChildNumber) -> Address {
self.unvault_descriptor
.derive(child_number, &self.secp_ctx)
.inner()
.address(self.bitcoind_config.network)
.expect("unvault_descriptor is a wsh")
}
pub fn gap_limit(&self) -> u32 {
100
}
pub fn watchonly_wallet_name(&self) -> Option<String> {
self.wallet_id
.map(|ref id| format!("revaultd-watchonly-wallet-{}", id))
}
pub fn log_file(&self) -> PathBuf {
self.file_from_datadir("log")
}
pub fn pid_file(&self) -> PathBuf {
self.file_from_datadir("revaultd.pid")
}
pub fn db_file(&self) -> PathBuf {
self.file_from_datadir("revaultd.sqlite3")
}
pub fn watchonly_wallet_file(&self) -> Option<String> {
self.watchonly_wallet_name().map(|ref name| {
self.file_from_datadir(name)
.to_str()
.expect("Valid utf-8")
.to_string()
})
}
pub fn rpc_socket_file(&self) -> PathBuf {
self.file_from_datadir("revaultd_rpc")
}
pub fn is_stakeholder(&self) -> bool {
self.our_stk_xpub.is_some()
}
pub fn is_manager(&self) -> bool {
self.our_man_xpub.is_some()
}
pub fn deposit_address(&self) -> Address {
self.vault_address(self.current_unused_index)
}
pub fn last_deposit_address(&self) -> Address {
let raw_index: u32 = self.current_unused_index.into();
// FIXME: this should fail instead of creating a hardened index
self.vault_address(ChildNumber::from(raw_index + self.gap_limit()))
}
pub fn last_unvault_address(&self) -> Address {
let raw_index: u32 = self.current_unused_index.into();
// FIXME: this should fail instead of creating a hardened index
self.unvault_address(ChildNumber::from(raw_index + self.gap_limit()))
}
/// All deposit addresses as strings up to the gap limit (100)
pub fn all_deposit_addresses(&mut self) -> Vec<String> {
self.derivation_index_map
.keys()
.map(|s| {
Address::from_script(s, self.bitcoind_config.network)
.expect("Created from P2WSH address")
.to_string()
})
.collect()
}
/// All unvault addresses as strings up to the gap limit (100)
pub fn all_unvault_addresses(&mut self) -> Vec<String> {
let raw_index: u32 = self.current_unused_index.into();
(0..raw_index + self.gap_limit())
.map(|raw_index| {
// FIXME: this should fail instead of creating a hardened index
self.unvault_address(ChildNumber::from(raw_index))
.to_string()
})
.collect()
}
pub fn derived_deposit_descriptor(&self, index: ChildNumber) -> DerivedDepositDescriptor {
self.deposit_descriptor.derive(index, &self.secp_ctx)
}
pub fn derived_unvault_descriptor(&self, index: ChildNumber) -> DerivedUnvaultDescriptor {
self.unvault_descriptor.derive(index, &self.secp_ctx)
}
pub fn derived_cpfp_descriptor(&self, index: ChildNumber) -> DerivedCpfpDescriptor {
self.cpfp_descriptor.derive(index, &self.secp_ctx)
}
pub fn stakeholders_xpubs(&self) -> Vec<DescriptorPublicKey> {
self.deposit_descriptor.xpubs()
}
pub fn managers_xpubs(&self) -> Vec<DescriptorPublicKey> {
// The managers' xpubs are all the xpubs from the Unvault descriptor except the
// Stakehodlers' ones and the Cosigning Servers' ones.
let stk_xpubs = self.stakeholders_xpubs();
self.unvault_descriptor
.xpubs()
.into_iter()
.filter_map(|xpub| {
match xpub {
DescriptorPublicKey::SinglePub(_) => None, // Cosig
DescriptorPublicKey::XPub(_) => {
if stk_xpubs.contains(&xpub) {
None // Stakeholder
} else {
Some(xpub) // Manager
}
}
}
})
.collect()
}
pub fn stakeholders_xpubs_at(&self, index: ChildNumber) -> Vec<BitcoinPublicKey> {
self.deposit_descriptor
.xpubs()
.into_iter()
.map(|desc_xpub| {
desc_xpub
.derive(index.into())
.derive_public_key(&self.secp_ctx)
.expect("Is derived, and there is never any hardened path")
})
.collect()
}
pub fn our_stk_xpub_at(&self, index: ChildNumber) -> Option<BitcoinPublicKey> {
self.our_stk_xpub.map(|xpub| {
xpub.derive_pub(&self.secp_ctx, &[index])
.expect("The derivation index stored in the database is sane (unhardened)")
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.