hexsha
stringlengths 40
40
| size
int64 4
1.05M
| content
stringlengths 4
1.05M
| avg_line_length
float64 1.33
100
| max_line_length
int64 1
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
3a6515c788f9e8ab2da62595d5ac54e0ee1fecc5 | 6,737 | //! SQLite authenticator module
//!
//! Requires `features = ["sqlite"]` in your `Cargo.toml`
use diesel::prelude::*;
use diesel::r2d2::{Builder, ConnectionManager};
use diesel::sqlite::SqliteConnection;
use rowdy;
use rowdy::auth::{AuthenticatorConfiguration, Basic};
use schema;
use {Error, PooledConnection};
/// A rowdy authenticator that uses a SQLite backed database to provide the users
pub type Authenticator = ::Authenticator<SqliteConnection>;
impl Authenticator {
/// Connect to a SQLite database at a certain path
///
/// Note: Diesel does not support [URI filenames](https://www.sqlite.org/c3ref/open.html)
/// at this moment.
///
/// # Warning about in memory databases
///
/// Rowdy uses a connection pool to SQLite databases. So a distinct
/// [`:memory:` database ](https://www.sqlite.org/inmemorydb.html) is created for ever
/// connection in the pool. Since URI filenames are not supported,
/// `file:memdb1?mode=memory&cache=shared` cannot be used.
pub fn with_path<S: AsRef<str>>(path: S) -> Result<Self, Error> {
// Attempt a test connection with diesel
let _ = Self::connect(path.as_ref())?;
let manager = ConnectionManager::new(path.as_ref());
let pool = Builder::new().build(manager)?;
Ok(Self::new(pool))
}
/// Test connection with the database uri
fn connect(path: &str) -> Result<SqliteConnection, Error> {
debug_!("Attempting a connection to SQLite database");
Ok(SqliteConnection::establish(path)?)
}
}
impl schema::Migration<SqliteConnection> for Authenticator {
type Connection = PooledConnection<ConnectionManager<SqliteConnection>>;
fn connection(&self) -> Result<Self::Connection, ::Error> {
self.get_pooled_connection()
}
fn migration_query(&self) -> &str {
r#"CREATE TABLE IF NOT EXISTS 'users' (
'username' VARCHAR(255) UNIQUE NOT NULL,
'hash' BLOB(32) NOT NULL,
'salt' BLOB(255) NOT NULL,
PRIMARY KEY ('username')
);"#
}
}
/// (De)Serializable configuration for SQLite Authenticator. This struct should be included
/// in the base `Configuration`.
/// # Examples
/// ```json
/// {
/// "database": "file:/home/fred/data.db"
/// }
/// ```
#[derive(Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct Configuration {
/// Connect to a SQLite database at a certain path
///
/// Note: Diesel does not support [URI filenames](https://www.sqlite.org/c3ref/open.html)
/// at this moment.
///
/// # Warning about in memory databases
///
/// Rowdy uses a connection pool to SQLite databases. So a distinct
/// [`:memory:` database ](https://www.sqlite.org/inmemorydb.html) is created for ever
/// connection in the pool. Since URI filenames are not supported,
/// `file:memdb1?mode=memory&cache=shared` cannot be used.
pub path: String,
}
impl AuthenticatorConfiguration<Basic> for Configuration {
type Authenticator = Authenticator;
fn make_authenticator(&self) -> Result<Self::Authenticator, rowdy::Error> {
Ok(Authenticator::with_path(&self.path)?)
}
}
#[cfg(test)]
mod tests {
use std::sync::{Once, ONCE_INIT};
use diesel::connection::SimpleConnection;
use rowdy::auth::Authenticator;
use super::*;
use schema::Migration;
static SEED: Once = ONCE_INIT;
/// Reset and seed the databse. This should only be run once.
fn migrate_and_seed(authenticator: &super::Authenticator) {
SEED.call_once(|| {
let query = format!(
include_str!("../test/fixtures/sqlite.sql"),
migration = authenticator.migration_query()
);
let connection = authenticator.get_pooled_connection().expect("to succeed");
connection.batch_execute(&query).expect("to work");
});
}
fn make_authenticator() -> super::Authenticator {
let authenticator = super::Authenticator::with_path("../target/sqlite.db")
.expect("To be constructed successfully");
migrate_and_seed(&authenticator);
authenticator
}
#[test]
fn hashing_is_done_correctly() {
let hashed_password = super::Authenticator::hash_password("password", &[0; 32])
.expect("to hash successfully");
assert_eq!(
"e6e1111452a5574d8d64f6f4ba6fabc86af5c45c341df1eb23026373c41d24b8",
hashed_password
);
}
#[test]
fn hashing_is_done_correctly_for_unicode() {
let hashed_password = super::Authenticator::hash_password("冻住,不许走!", &[0; 32])
.expect("to hash successfully");
assert_eq!(
"b400a5eea452afcc67a81602f28012e5634404ddf1e043d6ff1df67022c88cd2",
hashed_password
);
}
/// Migration should be idempotent
#[test]
fn migration_is_idempotent() {
let authenticator = make_authenticator();
authenticator
.migrate()
.expect("To succeed and be idempotent")
}
#[test]
fn authentication_with_username_and_password() {
let authenticator = make_authenticator();
let _ = authenticator
.verify("foobar", "password", false)
.expect("To verify correctly");
let result = authenticator
.verify("mei", "冻住,不许走!", false)
.expect("to be verified");
// refresh refresh_payload is not provided when not requested
assert!(result.refresh_payload.is_none());
}
#[test]
fn authentication_with_refresh_payload() {
let authenticator = make_authenticator();
let result = authenticator
.verify("foobar", "password", true)
.expect("To verify correctly");
// refresh refresh_payload is provided when requested
assert!(result.refresh_payload.is_some());
let result = authenticator
.authenticate_refresh_token(result.refresh_payload.as_ref().unwrap())
.expect("to be successful");
assert!(result.refresh_payload.is_none());
}
#[test]
fn sqlite_authenticator_configuration_deserialization() {
use rowdy::auth::AuthenticatorConfiguration;
use serde_json;
let json = r#"{
"path": "../target/test.db"
}"#;
let deserialized: Configuration =
serde_json::from_str(json).expect("to deserialize successfully");
let expected_config = Configuration {
path: From::from("../target/test.db"),
};
assert_eq!(deserialized, expected_config);
let _ = expected_config
.make_authenticator()
.expect("to be constructed correctly");
}
}
| 32.389423 | 93 | 0.634704 |
fb81d06bee510881dc950525a1efa07e88eb2174 | 5,030 | //! Provides fetcher for Yarn distributions
use std::fs::File;
use std::path::{Path, PathBuf};
use super::super::download_tool_error;
use crate::error::{Context, ErrorKind, Fallible};
use crate::fs::{create_staging_dir, create_staging_file, rename};
use crate::hook::ToolHooks;
use crate::layout::volta_home;
use crate::style::{progress_bar, tool_version};
use crate::tool::{self, Yarn};
use crate::version::VersionSpec;
use archive::{Archive, Tarball};
use cfg_if::cfg_if;
use fs_utils::ensure_containing_dir_exists;
use log::debug;
use semver::Version;
cfg_if! {
if #[cfg(feature = "mock-network")] {
fn public_yarn_server_root() -> String {
mockito::SERVER_URL.to_string()
}
} else {
fn public_yarn_server_root() -> String {
"https://github.com/yarnpkg/yarn/releases/download".to_string()
}
}
}
pub fn fetch(version: &Version, hooks: Option<&ToolHooks<Yarn>>) -> Fallible<()> {
let yarn_dir = volta_home()?.yarn_inventory_dir();
let cache_file = yarn_dir.join(Yarn::archive_filename(&version.to_string()));
let (archive, staging) = match load_cached_distro(&cache_file) {
Some(archive) => {
debug!(
"Loading {} from cached archive at '{}'",
tool_version("yarn", &version),
cache_file.display(),
);
(archive, None)
}
None => {
let staging = create_staging_file()?;
let remote_url = determine_remote_url(&version, hooks)?;
let archive = fetch_remote_distro(&version, &remote_url, staging.path())?;
(archive, Some(staging))
}
};
unpack_archive(archive, version)?;
if let Some(staging_file) = staging {
ensure_containing_dir_exists(&cache_file).with_context(|| {
ErrorKind::ContainingDirError {
path: cache_file.clone(),
}
})?;
staging_file
.persist(cache_file)
.with_context(|| ErrorKind::PersistInventoryError {
tool: "Yarn".into(),
})?;
}
Ok(())
}
/// Unpack the yarn archive into the image directory so that it is ready for use
fn unpack_archive(archive: Box<dyn Archive>, version: &Version) -> Fallible<()> {
let temp = create_staging_dir()?;
debug!("Unpacking yarn into '{}'", temp.path().display());
let progress = progress_bar(
archive.origin(),
&tool_version("yarn", version),
archive
.uncompressed_size()
.unwrap_or_else(|| archive.compressed_size()),
);
let version_string = version.to_string();
archive
.unpack(temp.path(), &mut |_, read| {
progress.inc(read as u64);
})
.with_context(|| ErrorKind::UnpackArchiveError {
tool: "Yarn".into(),
version: version_string.clone(),
})?;
let dest = volta_home()?.yarn_image_dir(&version_string);
ensure_containing_dir_exists(&dest)
.with_context(|| ErrorKind::ContainingDirError { path: dest.clone() })?;
rename(
temp.path().join(Yarn::archive_basename(&version_string)),
&dest,
)
.with_context(|| ErrorKind::SetupToolImageError {
tool: "Yarn".into(),
version: version_string.clone(),
dir: dest.clone(),
})?;
progress.finish_and_clear();
// Note: We write this after the progress bar is finished to avoid display bugs with re-renders of the progress
debug!("Installing yarn in '{}'", dest.display());
Ok(())
}
/// Return the archive if it is valid. It may have been corrupted or interrupted in the middle of
/// downloading.
// ISSUE(#134) - verify checksum
fn load_cached_distro(file: &PathBuf) -> Option<Box<dyn Archive>> {
if file.is_file() {
let file = File::open(file).ok()?;
Tarball::load(file).ok()
} else {
None
}
}
/// Determine the remote URL to download from, using the hooks if available
fn determine_remote_url(version: &Version, hooks: Option<&ToolHooks<Yarn>>) -> Fallible<String> {
let version_str = version.to_string();
let distro_file_name = Yarn::archive_filename(&version_str);
match hooks {
Some(&ToolHooks {
distro: Some(ref hook),
..
}) => {
debug!("Using yarn.distro hook to determine download URL");
hook.resolve(&version, &distro_file_name)
}
_ => Ok(format!(
"{}/v{}/{}",
public_yarn_server_root(),
version_str,
distro_file_name
)),
}
}
/// Fetch the distro archive from the internet
fn fetch_remote_distro(
version: &Version,
url: &str,
staging_path: &Path,
) -> Fallible<Box<dyn Archive>> {
debug!("Downloading {} from {}", tool_version("yarn", version), url);
Tarball::fetch(url, staging_path).with_context(download_tool_error(
tool::Spec::Yarn(VersionSpec::Exact(version.clone())),
url,
))
}
| 31.242236 | 115 | 0.60338 |
64364772dd87d8b3a32366fc2ec88d764e7bf609 | 3,213 | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::experiments::ExperimentParam;
use crate::{
aws, cluster::Cluster, experiments::Context, experiments::Experiment, instance,
instance::Instance,
};
use crate::effects::{Action, GenerateCpuFlamegraph};
use anyhow::{format_err, Result};
use async_trait::async_trait;
use chrono::{Datelike, Timelike, Utc};
use futures::future::FutureExt;
use futures::join;
use std::{
collections::HashSet,
fmt::{Display, Error, Formatter},
time::Duration,
};
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
pub struct CpuFlamegraphParams {
#[structopt(
long,
default_value = "60",
help = "Number of seconds for which perf should be run"
)]
pub duration_secs: usize,
}
pub struct CpuFlamegraph {
duration_secs: usize,
perf_instance: Instance,
}
impl ExperimentParam for CpuFlamegraphParams {
type E = CpuFlamegraph;
fn build(self, cluster: &Cluster) -> Self::E {
let perf_instance = cluster.random_validator_instance();
Self::E {
duration_secs: self.duration_secs,
perf_instance,
}
}
}
#[async_trait]
impl Experiment for CpuFlamegraph {
fn affected_validators(&self) -> HashSet<String> {
instance::instancelist_to_set(&[self.perf_instance.clone()])
}
async fn run(&mut self, context: &mut Context<'_>) -> Result<()> {
let buffer = Duration::from_secs(60);
let tx_emitter_duration = 2 * buffer + Duration::from_secs(self.duration_secs as u64);
let emit_future = context
.tx_emitter
.emit_txn_for(
tx_emitter_duration,
context.cluster.validator_instances().clone(),
)
.boxed();
let flame_graph =
GenerateCpuFlamegraph::new(self.perf_instance.clone(), self.duration_secs);
let flame_graph_future = tokio::time::delay_for(buffer)
.then(|_| flame_graph.apply())
.boxed();
let (emit_result, flame_graph_result) = join!(emit_future, flame_graph_future);
emit_result.map_err(|e| format_err!("Emiting tx failed: {:?}", e))?;
flame_graph_result.map_err(|e| format_err!("Failed to generate flamegraph: {:?}", e))?;
let now = Utc::now();
let filename = format!(
"{:04}{:02}{:02}-{:02}{:02}{:02}-libra-node-perf.svg",
now.year(),
now.month(),
now.day(),
now.hour(),
now.minute(),
now.second()
);
aws::upload_to_s3(
"perf-kernel.svg",
"toro-cluster-test-flamegraphs",
filename.as_str(),
)?;
context.report.report_text(format!(
"perf flamegraph : https://s3.console.aws.amazon.com/s3/object/toro-cluster-test-flamegraphs/{}",
filename
));
Ok(())
}
fn deadline(&self) -> Duration {
Duration::from_secs(480)
}
}
impl Display for CpuFlamegraph {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "Generating CpuFlamegraph on {}", self.perf_instance)
}
}
| 30.6 | 109 | 0.602863 |
71b19dd4aac1c4032472fdf9f49d071529c93b00 | 1,229 | use ragnar_lib::{LocalComponent, UpdateResult, LocalNode, NativeComponent, TextNode, LocalContext};
use crate::state::Task;
use ragnar_html_markup::li::*;
use ragnar_html_markup::div::Div;
use ragnar_html_markup::label::Label;
use ragnar_html_markup::button::Button;
#[derive(Component)]
pub struct TodoComponent {
todo: Task,
}
pub trait VecExtend<T> {
fn extend_vec(self, vec: &mut Vec<T>);
}
impl VecExtend<String> for String {
fn extend_vec(self, vec: &mut Vec<String>) {
vec.push(self);
}
}
impl VecExtend<String> for Vec<String> {
fn extend_vec(self, vec: &mut Vec<String>) {
vec.extend(self.into_iter())
}
}
impl LocalComponent for TodoComponent {
type Msg = ();
fn render(self, ctx: LocalContext<Self::Msg>) -> LocalNode {
local! {
<li>
<div class="view">
<label for="huhu">
"bla hallo\"\" welt 123 false"
<button/>
"blubb"
</label>
</div>
</li>
}
}
fn update(&self, _msg: &Self::Msg, ctx: LocalContext<Self::Msg>) -> UpdateResult<Self> {
UpdateResult::Keep
}
}
| 24.58 | 99 | 0.561432 |
3956ffc5587c96b8aba7ce043bcf686b19de13eb | 1,542 | /*
* Client Portal Web API
*
* Client Portal Web API
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MarketData {
/// IBKR Contract ID
#[serde(rename = "Conid", skip_serializing_if = "Option::is_none")]
pub conid: Option<f32>,
/// Exchange
#[serde(rename = "Exchange", skip_serializing_if = "Option::is_none")]
pub exchange: Option<String>,
#[serde(rename = "minTick", skip_serializing_if = "Option::is_none")]
pub min_tick: Option<f32>,
#[serde(rename = "Last", skip_serializing_if = "Option::is_none")]
pub last: Option<f32>,
#[serde(rename = "LastSize", skip_serializing_if = "Option::is_none")]
pub last_size: Option<f32>,
#[serde(rename = "Bid", skip_serializing_if = "Option::is_none")]
pub bid: Option<f32>,
#[serde(rename = "BidSize", skip_serializing_if = "Option::is_none")]
pub bid_size: Option<f32>,
#[serde(rename = "Ask", skip_serializing_if = "Option::is_none")]
pub ask: Option<f32>,
#[serde(rename = "AskSize", skip_serializing_if = "Option::is_none")]
pub ask_size: Option<f32>,
}
impl MarketData {
pub fn new() -> MarketData {
MarketData {
conid: None,
exchange: None,
min_tick: None,
last: None,
last_size: None,
bid: None,
bid_size: None,
ask: None,
ask_size: None,
}
}
}
| 28.036364 | 74 | 0.603761 |
ab700c7cfb61f18d500289dcc3b4139522934182 | 17,468 | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! Transformations for relation expressions.
//!
//! This crate contains traits, types, and methods suitable for transforming
//! `MirRelationExpr` types in ways that preserve semantics and improve performance.
//! The core trait is `Transform`, and many implementors of this trait can be
//! boxed and iterated over. Some common transformation patterns are wrapped
//! as `Transform` implementors themselves.
//!
//! The crate also contains the beginnings of whole-dataflow optimization,
//! which uses the same analyses but spanning multiple dataflow elements.
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
use std::error::Error;
use std::fmt;
use std::iter;
use mz_expr::visit::Visit;
use mz_expr::{MirRelationExpr, MirScalarExpr};
use mz_ore::id_gen::IdGen;
use mz_repr::GlobalId;
pub mod canonicalize_mfp;
pub mod column_knowledge;
pub mod cse;
pub mod demand;
pub mod fusion;
pub mod inline_let;
pub mod join_implementation;
pub mod map_lifting;
pub mod monotonic;
pub mod nonnull_requirements;
pub mod nonnullable;
pub mod predicate_pushdown;
pub mod projection_extraction;
pub mod projection_lifting;
pub mod projection_pushdown;
pub mod reduce_elision;
pub mod reduction;
pub mod reduction_pushdown;
pub mod redundant_join;
pub mod topk_elision;
pub mod union_cancel;
pub mod update_let;
pub mod dataflow;
pub use dataflow::optimize_dataflow;
use mz_ore::stack::RecursionLimitError;
/// Arguments that get threaded through all transforms.
#[derive(Debug)]
pub struct TransformArgs<'a> {
/// A shared instance of IdGen to allow constructing new Let expressions.
pub id_gen: &'a mut IdGen,
/// The indexes accessible.
pub indexes: &'a dyn IndexOracle,
}
/// Types capable of transforming relation expressions.
pub trait Transform: std::fmt::Debug {
/// Transform a relation into a functionally equivalent relation.
fn transform(
&self,
relation: &mut MirRelationExpr,
args: TransformArgs,
) -> Result<(), TransformError>;
/// A string describing the transform.
///
/// This is useful mainly when iterating through many `Box<Transform>`
/// and one wants to judge progress before some defect occurs.
fn debug(&self) -> String {
format!("{:?}", self)
}
}
/// Errors that can occur during a transformation.
#[derive(Debug, Clone)]
pub enum TransformError {
/// An unstructured error.
Internal(String),
}
impl fmt::Display for TransformError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TransformError::Internal(msg) => write!(f, "internal transform error: {}", msg),
}
}
}
impl Error for TransformError {}
impl From<RecursionLimitError> for TransformError {
fn from(error: RecursionLimitError) -> Self {
TransformError::Internal(error.to_string())
}
}
/// A trait for a type that can answer questions about what indexes exist.
pub trait IndexOracle: fmt::Debug {
/// Returns an iterator over the indexes that exist on the identified
/// collection.
///
/// Each index is described by the list of key expressions. If no indexes
/// exist for the identified collection, or if the identified collection
/// is unknown, the returned iterator will be empty.
///
// NOTE(benesch): The allocation here is unfortunate, but on the other hand
// you need only allocate when you actually look for an index. Can we do
// better somehow? Making the entire optimizer generic over this iterator
// type doesn't presently seem worthwhile.
fn indexes_on(&self, id: GlobalId) -> Box<dyn Iterator<Item = &[MirScalarExpr]> + '_>;
}
/// An [`IndexOracle`] that knows about no indexes.
#[derive(Debug)]
pub struct EmptyIndexOracle;
impl IndexOracle for EmptyIndexOracle {
fn indexes_on(&self, _: GlobalId) -> Box<dyn Iterator<Item = &[MirScalarExpr]> + '_> {
Box::new(iter::empty())
}
}
/// A sequence of transformations iterated some number of times.
#[derive(Debug)]
pub struct Fixpoint {
transforms: Vec<Box<dyn crate::Transform>>,
limit: usize,
}
impl Transform for Fixpoint {
fn transform(
&self,
relation: &mut MirRelationExpr,
args: TransformArgs,
) -> Result<(), TransformError> {
// The number of iterations for a relation to settle depends on the
// number of nodes in the relation. Instead of picking an arbitrary
// hard limit on the number of iterations, we use a soft limit and
// check whether the relation has become simpler after reaching it.
// If so, we perform another pass of transforms. Otherwise, there is
// a bug somewhere that prevents the relation from settling on a
// stable shape.
loop {
let mut original_count = 0;
relation.try_visit_post::<_, TransformError>(&mut |_| Ok(original_count += 1))?;
for _ in 0..self.limit {
let original = relation.clone();
for transform in self.transforms.iter() {
transform.transform(
relation,
TransformArgs {
id_gen: args.id_gen,
indexes: args.indexes,
},
)?;
}
if *relation == original {
return Ok(());
}
}
let mut final_count = 0;
relation.try_visit_post::<_, TransformError>(&mut |_| Ok(final_count += 1))?;
if final_count >= original_count {
break;
}
}
for transform in self.transforms.iter() {
transform.transform(
relation,
TransformArgs {
id_gen: args.id_gen,
indexes: args.indexes,
},
)?;
}
Err(TransformError::Internal(format!(
"fixpoint looped too many times {:#?}; transformed relation: {}",
self,
relation.pretty()
)))
}
}
/// A sequence of transformations that simplify the `MirRelationExpr`
#[derive(Debug)]
pub struct FuseAndCollapse {
transforms: Vec<Box<dyn crate::Transform>>,
}
impl Default for FuseAndCollapse {
fn default() -> Self {
Self {
// TODO: The relative orders of the transforms have not been
// determined except where there are comments.
// TODO (#6542): All the transforms here except for
// `ProjectionLifting`, `InlineLet`, `UpdateLet`, and
// `RedundantJoin` can be implemented as free functions. Note that
// (#716) proposes the removal of `InlineLet` and `UpdateLet` as a
// transforms.
transforms: vec![
Box::new(crate::projection_extraction::ProjectionExtraction),
Box::new(crate::projection_lifting::ProjectionLifting::default()),
Box::new(crate::fusion::map::Map),
Box::new(crate::fusion::negate::Negate),
Box::new(crate::fusion::filter::Filter),
Box::new(crate::fusion::flatmap_to_map::FlatMapToMap),
Box::new(crate::fusion::project::Project),
Box::new(crate::fusion::join::Join),
Box::new(crate::fusion::top_k::TopK),
Box::new(crate::inline_let::InlineLet::new(false)),
Box::new(crate::fusion::reduce::Reduce),
Box::new(crate::fusion::union::Union),
// This goes after union fusion so we can cancel out
// more branches at a time.
Box::new(crate::union_cancel::UnionBranchCancellation),
// This should run before redundant join to ensure that key info
// is correct.
Box::new(crate::update_let::UpdateLet::default()),
// Removes redundant inputs from joins.
// Note that this eliminates one redundant input per join,
// so it is necessary to run this section in a loop.
// TODO: (#6748) Predicate pushdown unlocks the ability to
// remove some redundant joins but also prevents other
// redundant joins from being removed. When predicate pushdown
// no longer works against redundant join, check if it is still
// necessary to run RedundantJoin here.
Box::new(crate::redundant_join::RedundantJoin::default()),
// As a final logical action, convert any constant expression to a constant.
// Some optimizations fight against this, and we want to be sure to end as a
// `MirRelationExpr::Constant` if that is the case, so that subsequent use can
// clearly see this.
Box::new(crate::reduction::FoldConstants { limit: Some(10000) }),
],
}
}
}
impl Transform for FuseAndCollapse {
fn transform(
&self,
relation: &mut MirRelationExpr,
args: TransformArgs,
) -> Result<(), TransformError> {
for transform in self.transforms.iter() {
transform.transform(
relation,
TransformArgs {
id_gen: args.id_gen,
indexes: args.indexes,
},
)?;
}
Ok(())
}
}
/// A naive optimizer for relation expressions.
///
/// The optimizer currently applies only peep-hole optimizations, from a limited
/// set that were sufficient to get some of TPC-H up and working. It is worth a
/// review at some point to improve the quality, coverage, and architecture of
/// the optimizations.
#[derive(Debug)]
pub struct Optimizer {
/// The list of transforms to apply to an input relation.
pub transforms: Vec<Box<dyn crate::Transform>>,
}
impl Optimizer {
/// Builds a logical optimizer that only performs logical transformations.
pub fn logical_optimizer() -> Self {
let transforms: Vec<Box<dyn crate::Transform>> = vec![
// 1. Structure-agnostic cleanup
Box::new(crate::topk_elision::TopKElision),
Box::new(crate::nonnull_requirements::NonNullRequirements::default()),
// 2. Collapse constants, joins, unions, and lets as much as possible.
// TODO: lift filters/maps to maximize ability to collapse
// things down?
Box::new(crate::Fixpoint {
limit: 100,
transforms: vec![Box::new(crate::FuseAndCollapse::default())],
}),
// 3. Move predicate information up and down the tree.
// This also fixes the shape of joins in the plan.
Box::new(crate::Fixpoint {
limit: 100,
transforms: vec![
// Predicate pushdown sets the equivalence classes of joins.
Box::new(crate::predicate_pushdown::PredicatePushdown::default()),
// Lifts the information `!isnull(col)`
Box::new(crate::nonnullable::NonNullable),
// Lifts the information `col = literal`
// TODO (#6613): this also tries to lift `!isnull(col)` but
// less well than the previous transform. Eliminate
// redundancy between the two transforms.
Box::new(crate::column_knowledge::ColumnKnowledge::default()),
// Lifts the information `col1 = col2`
Box::new(crate::demand::Demand::default()),
Box::new(crate::FuseAndCollapse::default()),
],
}),
// 4. Reduce/Join simplifications.
Box::new(crate::Fixpoint {
limit: 100,
transforms: vec![
// Pushes aggregations down
Box::new(crate::reduction_pushdown::ReductionPushdown),
// Replaces reduces with maps when the group keys are
// unique with maps
Box::new(crate::reduce_elision::ReduceElision),
// Converts `Cross Join {Constant(Literal) + Input}` to
// `Map {Cross Join (Input, Constant()), Literal}`.
// Join fusion will clean this up to `Map{Input, Literal}`
Box::new(crate::map_lifting::LiteralLifting::default()),
// Identifies common relation subexpressions.
// Must be followed by let inlining, to keep under control.
Box::new(crate::cse::relation_cse::RelationCSE),
Box::new(crate::inline_let::InlineLet::new(false)),
Box::new(crate::update_let::UpdateLet::default()),
Box::new(crate::FuseAndCollapse::default()),
],
}),
];
Self { transforms }
}
/// Builds a physical optimizer.
///
/// Performs logical transformations followed by all physical ones.
/// This is meant to be used for optimizing each view within a dataflow
/// once view inlining has already happened, right before dataflow
/// rendering.
pub fn physical_optimizer() -> Self {
// Implementation transformations
let transforms: Vec<Box<dyn crate::Transform>> = vec![
Box::new(crate::Fixpoint {
limit: 100,
transforms: vec![
Box::new(crate::join_implementation::JoinImplementation::default()),
Box::new(crate::column_knowledge::ColumnKnowledge::default()),
Box::new(crate::reduction::FoldConstants { limit: Some(10000) }),
Box::new(crate::demand::Demand::default()),
Box::new(crate::map_lifting::LiteralLifting::default()),
],
}),
Box::new(crate::canonicalize_mfp::CanonicalizeMfp),
// Identifies common relation subexpressions.
// Must be followed by let inlining, to keep under control.
Box::new(crate::cse::relation_cse::RelationCSE),
Box::new(crate::inline_let::InlineLet::new(false)),
Box::new(crate::update_let::UpdateLet::default()),
Box::new(crate::reduction::FoldConstants { limit: Some(10000) }),
];
Self { transforms }
}
/// Contains the logical optimizations that should run after cross-view
/// transformations run.
pub fn logical_cleanup_pass() -> Self {
let transforms: Vec<Box<dyn crate::Transform>> = vec![
// Delete unnecessary maps.
Box::new(crate::fusion::map::Map),
Box::new(crate::Fixpoint {
limit: 100,
transforms: vec![
// Projection pushdown may unblock fusing joins and unions.
Box::new(crate::fusion::join::Join),
Box::new(crate::redundant_join::RedundantJoin::default()),
// Redundant join produces projects that need to be fused.
Box::new(crate::fusion::project::Project),
Box::new(crate::fusion::union::Union),
// This goes after union fusion so we can cancel out
// more branches at a time.
Box::new(crate::union_cancel::UnionBranchCancellation),
Box::new(crate::cse::relation_cse::RelationCSE),
Box::new(crate::inline_let::InlineLet::new(true)),
Box::new(crate::reduction::FoldConstants { limit: Some(10000) }),
],
}),
];
Self { transforms }
}
/// Optimizes the supplied relation expression.
///
/// These optimizations are performed with no information about available arrangements,
/// which makes them suitable for pre-optimization before dataflow deployment.
pub fn optimize(
&mut self,
mut relation: MirRelationExpr,
) -> Result<mz_expr::OptimizedMirRelationExpr, TransformError> {
self.transform(&mut relation, &EmptyIndexOracle)?;
Ok(mz_expr::OptimizedMirRelationExpr(relation))
}
/// Optimizes the supplied relation expression in place, using available arrangements.
///
/// This method should only be called with non-empty `indexes` when optimizing a dataflow,
/// as the optimizations may lock in the use of arrangements that may cease to exist.
fn transform(
&self,
relation: &mut MirRelationExpr,
indexes: &dyn IndexOracle,
) -> Result<(), TransformError> {
let mut id_gen = Default::default();
for transform in self.transforms.iter() {
transform.transform(
relation,
TransformArgs {
id_gen: &mut id_gen,
indexes,
},
)?;
}
Ok(())
}
}
| 40.623256 | 94 | 0.592111 |
3385af8eec51dd14e7d98bc1d122f255890a597d | 1,135 | use crate::game::tile::Tile;
use std::{fs};
pub struct Map {
pub tiles: Vec<Vec<Tile>>,
pub width: usize,
pub height: usize,
}
//split a string into a vector of chars and remove the last char
fn split_and_rem_last(y: usize, input: &str) -> Vec<Tile> {
let mut output = input.chars().collect::<Vec<char>>();
output = output.iter().filter(|&&x| x != '\r').map(|x| *x).collect::<Vec<char>>();
let mut output2: Vec<Tile> = Vec::new();
for (x, c) in output.iter().enumerate() {
output2.push(Tile::new(*c, x as f64, y as f64, 1.0, 1.0));
}
output2
}
pub fn load_map(map_src: &str) -> Map {
let map_raw =
fs::read_to_string(format!("{}{}", "src/data/", map_src)).expect("Unable to read file");
let map_split: Vec<&str> = map_raw.split('\n').collect();
let mut map: Vec<Vec<Tile>> = Vec::new();
for (i, s) in map_split.iter().enumerate(){
map.push(split_and_rem_last(i, s))
}
let mw = map[0].len();
let mh = map.len();
return Map {
tiles: map,
width: mw,
height: mh,
};
}
| 25.222222 | 97 | 0.544493 |
013c831a6573f161fb53f1de2fb6190c4a64a9f6 | 37,140 | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::fmt::{self, Display, Formatter};
use std::io::Write;
use std::{i64, u64};
use tikv_util::codec::number::{self, NumberEncoder};
use tikv_util::codec::BytesSlice;
use super::{check_fsp, Decimal};
use crate::coprocessor::codec::mysql::MAX_FSP;
use crate::coprocessor::codec::{Result, TEN_POW};
use bitfield::bitfield;
pub const NANOS_PER_SEC: i64 = 1_000_000_000;
pub const MICROS_PER_SEC: i64 = 1_000_000;
pub const NANO_WIDTH: usize = 9;
pub const MICRO_WIDTH: usize = 6;
const SECS_PER_HOUR: u32 = 3600;
const SECS_PER_MINUTE: u32 = 60;
const MAX_HOURS: u32 = 838;
const MAX_MINUTES: u32 = 59;
const MAX_SECONDS: u32 = 59;
const MAX_MICROS: u32 = 999_999;
#[inline]
fn check_hour(hour: u32) -> Result<u32> {
if hour > MAX_HOURS {
Err(invalid_type!(
"invalid hour value: {} larger than {}",
hour,
MAX_HOURS
))
} else {
Ok(hour)
}
}
#[inline]
fn check_minute(minute: u32) -> Result<u32> {
if minute > MAX_MINUTES {
Err(invalid_type!(
"invalid minute value: {} larger than {}",
minute,
MAX_MINUTES
))
} else {
Ok(minute)
}
}
#[inline]
fn check_second(second: u32) -> Result<u32> {
if second > MAX_SECONDS {
Err(invalid_type!(
"invalid second value: {} larger than {}",
second,
MAX_SECONDS
))
} else {
Ok(second)
}
}
#[inline]
fn check_micros(micros: u32) -> Result<u32> {
if micros > MAX_MICROS {
Err(invalid_type!(
"invalid fractional value: {} larger than {}",
micros,
MAX_MICROS
))
} else {
Ok(micros)
}
}
mod parser {
use super::{check_hour, check_minute, check_second, MICRO_WIDTH, TEN_POW};
use nom::character::complete::{digit1, multispace0, multispace1};
use nom::{
alt, call, char, complete, cond, do_parse, eof, map, map_res, opt, peek, preceded, tag,
IResult,
};
#[inline]
fn buf_to_int(buf: &[u8]) -> u32 {
buf.iter().fold(0, |acc, c| acc * 10 + u32::from(c - b'0'))
}
/// Extracts a `u32` from a buffer which matches pattern: `\d+.*`
///
/// ```compile_fail
/// assert_eq!(read_int(b"123abc"), Ok((b"abc", 123)));
/// assert_eq!(read_int(b"12:34"), Ok((b":34", 12)));
/// assert!(read_int(b"12345678:1").is_err());
/// ```
///
/// NOTE:
/// The range of MySQL's TIME is `-838:59:59 ~ 838:59:59`, so we can at most read 7 digits
/// (pattern like `HHHMMSS`)
fn read_int(input: &[u8]) -> IResult<&[u8], u32> {
map_res!(input, digit1, |buf: &[u8]| {
if buf.len() <= 7 {
Ok(buf_to_int(buf))
} else {
Err(invalid_type!("invalid time value, more than {} digits", 7))
}
})
}
/// Extracts a `u32` with length `fsp` from a buffer which matches pattern: `\d+.*`
/// This function assumes that `fsp` is valid
///
/// ```compile_fail
/// assert_eq!(read_int_with_fsp(b"1234567", 3), Ok(b"", 123400000));
/// assert_eq!(read_int_with_fsp(b"1234", 6), Ok(b"", 123400000));
/// ```
///
/// NOTE:
/// 1. The behavior of this function is similar to `read_int` except that it's designed to read the
/// fractional part of a `TIME`
/// 2. The fractional part will be align to a 9-digit number which it's easy to round with `fsp`
///
/// FIXME: the fraction should not be round, it's incompatible with MySQL.
fn read_int_with_fsp(input: &[u8], fsp: u8) -> IResult<&[u8], u32> {
map!(input, digit1, |buf: &[u8]| -> u32 {
let fsp = usize::from(fsp);
let (fraction, len) = if fsp >= buf.len() {
(buf_to_int(buf), buf.len())
} else {
(buf_to_int(&buf[..=fsp]), fsp + 1)
};
fraction * TEN_POW[MICRO_WIDTH.checked_sub(len).unwrap_or(0)]
})
}
/// Parse the sign of `Duration`, return true if it's negative otherwise false
///
/// ```compile_fail
/// assert_eq!(neg(b"- .123"), Ok(b".123", true));
/// assert_eq!(neg(b"-.123"), Ok(b".123", true));
/// assert_eq!(neg(b"- 11:21"), Ok(b"11:21", true));
/// assert_eq!(neg(b"-11:21"), Ok(b"11:21", true));
/// assert_eq!(neg(b"11:21"), Ok(b"11:21", false));
/// ```
fn neg(input: &[u8]) -> IResult<&[u8], bool> {
do_parse!(
input,
neg: map!(opt!(complete!(char!('-'))), |flag| flag.is_some())
>> preceded!(
multispace0,
alt!(complete!(peek!(call!(digit1))) | complete!(peek!(tag!("."))))
)
>> (neg)
)
}
/// Parse the day/block(format like `HHMMSS`) value of the `Duration`,
/// further paring will determine the value we got is a `day` value or `block` value.
///
/// ```compile_fail
/// assert_eq!(day(b"1 1:1"), Ok(b"1:1", Some(1)));
/// assert_eq!(day(b"1234"), Ok(b"", Some(1234)));
/// assert_eq!(day(b"1234.123"), Ok(b".123", Some(1234)));
/// assert_eq!(day(b"1:2:3"), Ok(b"1:2:3", None));
/// assert_eq!(day(b".123"), Ok(b".123", None));
/// ```
fn day(input: &[u8]) -> IResult<&[u8], Option<u32>> {
opt!(
input,
do_parse!(
day: read_int
>> alt!(
complete!(preceded!(multispace1, peek!(call!(digit1))))
| complete!(preceded!(
multispace0,
alt!(complete!(peek!(tag!("."))) | complete!(eof!()))
))
)
>> (day)
)
)
}
/// Parse a separator ':'
///
/// ```compile_fail
/// assert_eq!(separator(b" : "), Ok(b"", true));
/// assert_eq!(separator(b":"), Ok(b"", true));
/// assert_eq!(separator(b";"), Ok(b";", false));
/// ```
fn separator(input: &[u8]) -> IResult<&[u8], bool> {
do_parse!(
input,
multispace0
>> has_separator: map!(opt!(complete!(char!(':'))), |flag| flag.is_some())
>> multispace0
>> (has_separator)
)
}
/// Parse format like: `hh:mm` `hh:mm:ss`
///
/// ```compile_fail
/// assert_eq!(hhmmss(b"12:34:56"), Ok(b"", [12, 34, 56]));
/// assert_eq!(hhmmss(b"12:34"), Ok(b"", [12, 34, None]));
/// assert_eq!(hhmmss(b"1234"), Ok(b"", [None, None, None]));
/// ```
fn hhmmss(input: &[u8]) -> IResult<&[u8], [Option<u32>; 3]> {
do_parse!(
input,
hour: opt!(map_res!(read_int, check_hour))
>> has_mintue: separator
>> minute: cond!(has_mintue, map_res!(read_int, check_minute))
>> has_second: separator
>> second: cond!(has_second, map_res!(read_int, check_second))
>> ([hour, minute, second])
)
}
/// Parse fractional part.
///
/// ```compile_fail
/// assert_eq!(fraction(" .123", 3), Ok(b"", Some(123)));
/// assert_eq!(fraction("123", 3), Ok(b"", None));
/// ```
fn fraction(input: &[u8], fsp: u8) -> IResult<&[u8], Option<u32>> {
do_parse!(
input,
multispace0
>> opt!(complete!(char!('.')))
>> fraction: opt!(call!(read_int_with_fsp, fsp))
>> multispace0
>> (fraction)
)
}
/// Parse `Duration`
pub fn parse(input: &[u8], fsp: u8) -> IResult<&[u8], (bool, [Option<u32>; 5])> {
do_parse!(
input,
multispace0
>> neg: neg
>> day: day
>> hhmmss: hhmmss
>> fraction: call!(fraction, fsp)
>> eof!()
>> (neg, [day, hhmmss[0], hhmmss[1], hhmmss[2], fraction])
)
}
} /* parser */
bitfield! {
#[derive(Clone, Copy)]
pub struct Duration(u64);
impl Debug;
#[inline]
bool, get_neg, set_neg: 63;
#[inline]
bool, get_reserved, set_reserved: 62;
#[inline]
u32, get_hours, set_hours: 61, 48;
#[inline]
u32, get_minutes, set_minutes: 47, 40;
#[inline]
u32, get_secs, set_secs: 39, 32;
#[inline]
u32, get_micros, set_micros: 31, 8;
#[inline]
u8, get_fsp, set_fsp: 7, 0;
}
/// Rounds `micros` with `fsp` and handles the carry.
#[inline]
fn round(
hours: &mut u32,
minutes: &mut u32,
secs: &mut u32,
micros: &mut u32,
fsp: u8,
) -> Result<()> {
if *micros < 1_000_000 {
*micros *= 10;
}
let fsp = usize::from(fsp);
*micros = if fsp == MICRO_WIDTH {
(*micros + 5) / 10
} else {
let mask = TEN_POW[MICRO_WIDTH - fsp];
(*micros / mask + 5) / 10 * mask
};
if *micros >= 1_000_000 {
*micros -= 1_000_000;
*secs += 1;
if *secs >= 60 {
*secs -= 60;
*minutes += 1;
}
if *minutes >= 60 {
*minutes -= 60;
*hours += 1;
}
}
check_hour(*hours)?;
Ok(())
}
impl Duration {
/// Raw transmutation to u64.
#[inline]
pub fn to_bits(self) -> u64 {
self.0
}
#[inline]
pub fn neg(self) -> bool {
self.get_neg()
}
#[inline]
pub fn hours(self) -> u32 {
self.get_hours()
}
#[inline]
pub fn minutes(self) -> u32 {
self.get_minutes()
}
#[inline]
pub fn secs(self) -> u32 {
self.get_secs()
}
#[inline]
pub fn micros(self) -> u32 {
self.get_micros()
}
#[inline]
pub fn fsp(self) -> u8 {
self.get_fsp()
}
#[inline]
pub fn maximize_fsp(mut self) -> Self {
self.set_fsp(MAX_FSP as u8);
self
}
/// Raw transmutation from u64.
pub fn from_bits(v: u64) -> Result<Duration> {
let mut duration = Duration(v);
check_micros(duration.micros())?;
check_second(duration.secs())?;
check_minute(duration.minutes())?;
check_hour(duration.hours())?;
duration.set_reserved(false);
Ok(duration)
}
/// Returns the identity element of `Duration`
pub fn zero() -> Duration {
Duration(0)
}
/// Returns true if self is equal to the additive identity.
pub fn is_zero(mut self) -> bool {
self.set_neg(false);
self.set_fsp(0);
self.to_bits() == 0
}
/// Returns the absolute value of `Duration`
pub fn abs(mut self) -> Self {
self.set_neg(false);
self
}
/// Returns the fractional part of `Duration`, in whole microseconds.
pub fn subsec_micros(self) -> u32 {
self.micros()
}
/// Returns the number of whole seconds contained by this Duration.
pub fn to_secs(self) -> i32 {
let secs =
(self.hours() * SECS_PER_HOUR + self.minutes() * SECS_PER_MINUTE + self.secs()) as i32;
if self.get_neg() {
-secs
} else {
secs
}
}
/// Returns the number of seconds contained by this Duration as f64.
/// The returned value does include the fractional (nanosecond) part of the duration.
pub fn to_secs_f64(self) -> f64 {
let secs = f64::from(self.to_secs());
let micros = f64::from(self.subsec_micros()) * 1e-6;
secs + if self.get_neg() { -micros } else { micros }
}
/// Returns the `Duration` in whole nanoseconds
pub fn to_nanos(self) -> i64 {
let secs = i64::from(self.to_secs()) * NANOS_PER_SEC;
let micros = i64::from(self.subsec_micros());
secs + if self.get_neg() { -micros } else { micros } * 1000
}
/// Constructs a `Duration` from `nanos` with `fsp`
pub fn from_nanos(nanos: i64, fsp: i8) -> Result<Duration> {
Duration::from_micros(nanos / 1000, fsp)
}
pub fn from_micros(micros: i64, fsp: i8) -> Result<Duration> {
let fsp = check_fsp(fsp)?;
let neg = micros < 0;
let secs = (micros / MICROS_PER_SEC).abs();
let mut micros = (micros % MICROS_PER_SEC).abs() as u32;
let mut hours = (secs / i64::from(SECS_PER_HOUR)) as u32;
let mut minutes = (secs % i64::from(SECS_PER_HOUR) / i64::from(SECS_PER_MINUTE)) as u32;
let mut secs = (secs % 60) as u32;
round(&mut hours, &mut minutes, &mut secs, &mut micros, fsp)?;
Ok(Duration::new(neg, hours, minutes, secs, micros, fsp))
}
pub fn from_millis(millis: i64, fsp: i8) -> Result<Duration> {
Duration::from_micros(
millis
.checked_mul(1000)
.ok_or(invalid_type!("micros overflow"))?,
fsp,
)
}
/// Constructs a `Duration` from with details without validation
fn new(neg: bool, hours: u32, minutes: u32, secs: u32, micros: u32, fsp: u8) -> Duration {
let mut duration = Duration(0);
duration.set_neg(neg);
duration.set_hours(hours);
duration.set_minutes(minutes);
duration.set_secs(secs);
duration.set_micros(micros);
duration.set_fsp(fsp);
duration
}
/// Parses the time form a formatted string with a fractional seconds part,
/// returns the duration type `Time` value.
/// See: http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
pub fn parse(input: &[u8], fsp: i8) -> Result<Duration> {
let fsp = check_fsp(fsp)?;
if input.is_empty() {
return Ok(Duration::zero());
}
let (mut neg, [mut day, mut hour, mut minute, mut second, micros]) =
self::parser::parse(input, fsp)
.map_err(|_| invalid_type!("invalid time format"))?
.1;
if day.is_some() && hour.is_none() {
let block = day.take().unwrap();
hour = Some(block / 10_000);
minute = Some(block / 100 % 100);
second = Some(block % 100);
}
let (mut hour, mut minute, mut second, mut micros) = (
hour.unwrap_or(0) + day.unwrap_or(0) * 24,
minute.unwrap_or(0),
second.unwrap_or(0),
micros.unwrap_or(0),
);
if hour == 0 && minute == 0 && second == 0 && micros == 0 {
neg = false;
}
round(&mut hour, &mut minute, &mut second, &mut micros, fsp)?;
Ok(Duration::new(neg, hour, minute, second, micros, fsp))
}
/// Rounds fractional seconds precision with new FSP and returns a new one.
/// We will use the “round half up” rule, e.g, >= 0.5 -> 1, < 0.5 -> 0,
/// so 10:10:10.999999 round with fsp: 1 -> 10:10:11.0
/// and 10:10:10.000000 round with fsp: 0 -> 10:10:11
pub fn round_frac(mut self, fsp: i8) -> Result<Self> {
let fsp = check_fsp(fsp)?;
if fsp >= self.fsp() {
self.set_fsp(fsp);
return Ok(self);
}
let mut hours = self.hours();
let mut minutes = self.minutes();
let mut secs = self.secs();
let mut micros = self.micros();
round(&mut hours, &mut minutes, &mut secs, &mut micros, fsp)?;
Ok(Duration::new(
self.get_neg(),
hours,
minutes,
secs,
micros,
fsp,
))
}
/// Checked duration addition. Computes self + rhs, returning None if overflow occurred.
pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
match (self.get_neg(), rhs.get_neg()) {
(false, true) => self.checked_sub(rhs.abs()),
(true, false) => rhs.checked_sub(self.abs()),
(true, true) => self.abs().checked_add(rhs.abs()).map(|mut res| {
res.set_neg(true);
res
}),
(false, false) => {
let mut micros = self.micros() + rhs.micros();
let mut secs = self.secs() + rhs.secs();
let mut minutes = self.minutes() + rhs.minutes();
let mut hours = self.hours() + rhs.hours();
if i64::from(micros) >= MICROS_PER_SEC {
micros -= MICROS_PER_SEC as u32;
secs += 1;
}
if secs >= 60 {
secs -= 60;
minutes += 1;
}
if minutes >= 60 {
minutes -= 60;
hours += 1;
}
check_hour(hours).ok()?;
Some(Duration::new(
false,
hours,
minutes,
secs,
micros,
self.fsp().max(rhs.fsp()),
))
}
}
}
/// Checked duration subtraction. Computes self - rhs, returning None if overflow occurred.
pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
match (self.get_neg(), rhs.get_neg()) {
(false, true) => self.checked_add(rhs.abs()),
(true, false) => self.abs().checked_add(rhs.abs()).map(|mut res| {
res.set_neg(true);
res
}),
(true, true) => rhs.abs().checked_sub(self.abs()),
(false, false) => {
let neg = self < rhs;
let (l, r) = if neg { (rhs, self) } else { (self, rhs) };
let mut micros = l.micros() as i32 - r.micros() as i32;
let mut secs = l.secs() as i32 - r.secs() as i32;
let mut minutes = l.minutes() as i32 - r.minutes() as i32;
let mut hours = l.hours() as i32 - r.hours() as i32;
if micros < 0 {
micros += MICROS_PER_SEC as i32;
secs -= 1;
}
if secs < 0 {
secs += 60;
minutes -= 1;
}
if minutes < 0 {
minutes += 60;
hours -= 1;
}
Some(Duration::new(
neg,
hours as u32,
minutes as u32,
secs as u32,
micros as u32,
self.fsp().max(rhs.fsp()),
))
}
}
}
fn format(self, sep: &str) -> String {
use std::fmt::Write;
let mut string = String::new();
if self.get_neg() {
string.push('-');
}
write!(
&mut string,
"{:02}{}{:02}{}{:02}",
self.hours(),
sep,
self.minutes(),
sep,
self.secs()
)
.unwrap();
let fsp = usize::from(self.fsp());
if self.fsp() > 0 {
write!(
&mut string,
".{:0width$}",
self.micros() / TEN_POW[MICRO_WIDTH - fsp],
width = fsp
)
.unwrap();
}
string
}
/// Converts a `Duration` to printable numeric string representation
#[inline]
pub fn to_numeric_string(self) -> String {
use std::fmt::Write;
let mut buf = String::with_capacity(13);
if self.neg() {
buf.push('-');
}
write!(
buf,
"{:02}{:02}{:02}",
self.hours(),
self.minutes(),
self.secs(),
)
.unwrap();
let fsp = self.get_fsp();
if fsp > 0 {
let nanos = self.subsec_micros() / (TEN_POW[MICRO_WIDTH - usize::from(fsp)]) as u32;
write!(buf, ".{:01$}", nanos, fsp as usize).unwrap();
}
buf
}
}
// TODO: define a convert::Convert trait for all conversion
impl TryFrom<Duration> for Decimal {
type Error = crate::coprocessor::codec::Error;
fn try_from(duration: Duration) -> Result<Decimal> {
duration.to_numeric_string().parse()
}
}
impl Display for Duration {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", self.format(":"))
}
}
impl PartialEq for Duration {
fn eq(&self, dur: &Duration) -> bool {
let (mut a, mut b) = (*self, *dur);
a.set_fsp(0);
b.set_fsp(0);
a.0 == b.0
}
}
impl std::hash::Hash for Duration {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let mut inner = *self;
inner.set_fsp(0);
inner.to_bits().hash(state)
}
}
impl PartialOrd for Duration {
fn partial_cmp(&self, dur: &Duration) -> Option<Ordering> {
let mut a = *self;
let mut b = *dur;
a.set_fsp(0);
b.set_fsp(0);
let ordering = a.0.cmp(&b.0);
Some(if a.get_neg() || b.get_neg() {
ordering.reverse()
} else {
ordering
})
}
}
impl Eq for Duration {}
impl Ord for Duration {
fn cmp(&self, dur: &Duration) -> Ordering {
self.partial_cmp(dur).unwrap()
}
}
impl<T: Write> DurationEncoder for T {}
pub trait DurationEncoder: NumberEncoder {
fn encode_duration(&mut self, v: Duration) -> Result<()> {
self.encode_i64(v.to_nanos())?;
self.encode_i64(i64::from(v.get_fsp())).map_err(From::from)
}
}
impl Duration {
/// `decode` decodes duration encoded by `encode_duration`.
pub fn decode(data: &mut BytesSlice<'_>) -> Result<Duration> {
let nanos = number::decode_i64(data)?;
let fsp = number::decode_i64(data)?;
Duration::from_nanos(nanos, fsp as i8)
}
}
impl crate::coprocessor::codec::data_type::AsMySQLBool for Duration {
#[inline]
fn as_mysql_bool(
&self,
_context: &mut crate::coprocessor::dag::expr::EvalContext,
) -> crate::coprocessor::Result<bool> {
Ok(!self.is_zero())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::coprocessor::codec::convert::convert_bytes_to_decimal;
use crate::coprocessor::codec::data_type::DateTime;
use crate::coprocessor::dag::expr::EvalContext;
#[test]
fn test_hours() {
let cases: Vec<(&str, i8, u32)> = vec![
("31 11:30:45", 0, 31 * 24 + 11),
("11:30:45", 0, 11),
("-11:30:45.9233456", 0, 11),
("272:59:59", 0, 272),
];
for (input, fsp, exp) in cases {
let dur = Duration::parse(input.as_bytes(), fsp).unwrap();
let res = dur.hours();
assert_eq!(exp, res);
}
}
#[test]
fn test_minutes() {
let cases: Vec<(&str, i8, u32)> = vec![
("31 11:30:45", 0, 30),
("11:30:45", 0, 30),
("-11:30:45.9233456", 0, 30),
];
for (input, fsp, exp) in cases {
let dur = Duration::parse(input.as_bytes(), fsp).unwrap();
let res = dur.minutes();
assert_eq!(exp, res);
}
}
#[test]
fn test_secs() {
let cases: Vec<(&str, i8, u32)> = vec![
("31 11:30:45", 0, 45),
("11:30:45", 0, 45),
("-11:30:45.9233456", 1, 45),
("-11:30:45.9233456", 0, 46),
];
for (input, fsp, exp) in cases {
let dur = Duration::parse(input.as_bytes(), fsp).unwrap();
let res = dur.secs();
assert_eq!(exp, res);
}
}
#[test]
fn test_micros() {
let cases: Vec<(&str, i8, u32)> = vec![
("31 11:30:45.123", 6, 123000),
("11:30:45.123345", 3, 123000),
("11:30:45.123345", 5, 123350),
("11:30:45.123345", 6, 123345),
("11:30:45.1233456", 6, 123346),
("11:30:45.9233456", 0, 0),
("11:30:45.000010", 6, 10),
("11:30:45.00010", 5, 100),
];
for (input, fsp, exp) in cases {
let dur = Duration::parse(input.as_bytes(), fsp).unwrap();
let res = dur.micros();
assert_eq!(exp, res);
}
}
#[test]
fn test_parse() {
let cases: Vec<(&'static [u8], i8, Option<&'static str>)> = vec![
(b"10:11:12", 0, Some("10:11:12")),
(b"101112", 0, Some("10:11:12")),
(b"10:11", 0, Some("10:11:00")),
(b"101112.123456", 0, Some("10:11:12")),
(b"1112", 0, Some("00:11:12")),
(b"12", 0, Some("00:00:12")),
(b"1 12", 0, Some("36:00:00")),
(b"1 10:11:12", 0, Some("34:11:12")),
(b"1 10:11:12.123456", 0, Some("34:11:12")),
(b"1 10:11:12.123456", 4, Some("34:11:12.1235")),
(b"1 10:11:12.12", 4, Some("34:11:12.1200")),
(b"1 10:11:12.1234565", 6, Some("34:11:12.123457")),
(b"1 10:11:12.9999995", 6, Some("34:11:13.000000")),
(b"1 10:11:12.123456", 7, None),
(b"10:11:12.123456", 0, Some("10:11:12")),
(b"1 10:11", 0, Some("34:11:00")),
(b"1 10", 0, Some("34:00:00")),
(b"24 10", 0, Some("586:00:00")),
(b"-24 10", 0, Some("-586:00:00")),
(b"0 10", 0, Some("10:00:00")),
(b"-10:10:10", 0, Some("-10:10:10")),
(b"-838:59:59", 0, Some("-838:59:59")),
(b"838:59:59", 0, Some("838:59:59")),
(b"23:60:59", 0, None),
(b"54:59:59", 0, Some("54:59:59")),
(b"2011-11-11 00:00:01", 0, None),
(b"2011-11-11", 0, None),
(b"--23", 0, None),
(b"232 10", 0, None),
(b"-232 10", 0, None),
(b"00:00:00.1", 0, Some("00:00:00")),
(b"00:00:00.1", 1, Some("00:00:00.1")),
(b"00:00:00.777777", 2, Some("00:00:00.78")),
(b"00:00:00.777777", 6, Some("00:00:00.777777")),
(b"00:00:00.001", 3, Some("00:00:00.001")),
// NOTE: The following case is easy to fail.
(b"- 1 ", 0, Some("-00:00:01")),
(b"1:2:3", 0, Some("01:02:03")),
(b"1 1:2:3", 0, Some("25:02:03")),
(b"-1 1:2:3.123", 3, Some("-25:02:03.123")),
(b"-.123", 3, Some("-00:00:00.123")),
(b"12345", 0, Some("01:23:45")),
(b"-123", 0, Some("-00:01:23")),
(b"-23", 0, Some("-00:00:23")),
(b"- 1 1", 0, Some("-25:00:00")),
(b"-1 1", 0, Some("-25:00:00")),
(b" - 1:2:3 .123 ", 3, Some("-01:02:03.123")),
(b" - 1 :2 :3 .123 ", 3, Some("-01:02:03.123")),
(b" - 1 : 2 :3 .123 ", 3, Some("-01:02:03.123")),
(b" - 1 : 2 : 3 .123 ", 3, Some("-01:02:03.123")),
(b" - 1 .123 ", 3, Some("-00:00:01.123")),
(b"-", 0, None),
(b"", 0, Some("00:00:00")),
(b"", 7, None),
(b"18446744073709551615:59:59", 0, None),
(b"1::2:3", 0, None),
(b"1.23 3", 0, None),
];
for (input, fsp, expect) in cases {
let got = Duration::parse(input, fsp);
if let Some(expect) = expect {
assert_eq!(
expect,
&format!(
"{}",
got.unwrap_or_else(|_| panic!(std::str::from_utf8(input)
.unwrap()
.to_string()))
)
);
} else {
assert!(
got.is_err(),
format!(
"{} should not be passed, got {:?}",
std::str::from_utf8(input).unwrap(),
got
)
);
}
}
}
#[test]
fn test_to_numeric_string() {
let cases: Vec<(&[u8], i8, &str)> = vec![
(b"11:30:45.123456", 4, "113045.1235"),
(b"11:30:45.123456", 6, "113045.123456"),
(b"11:30:45.123456", 0, "113045"),
(b"11:30:45.999999", 0, "113046"),
(b"08:40:59.575601", 0, "084100"),
(b"23:59:59.575601", 0, "240000"),
(b"00:00:00", 0, "000000"),
(b"00:00:00", 6, "000000.000000"),
];
for (s, fsp, expect) in cases {
let du = Duration::parse(s, fsp).unwrap();
let get = du.to_numeric_string();
assert_eq!(get, expect.to_string());
}
}
#[test]
fn test_to_decimal() {
let cases = vec![
("31 11:30:45", 0, "7553045"),
("31 11:30:45", 6, "7553045.000000"),
("31 11:30:45", 0, "7553045"),
("31 11:30:45.123", 6, "7553045.123000"),
("11:30:45", 0, "113045"),
("11:30:45", 6, "113045.000000"),
("11:30:45.123", 6, "113045.123000"),
("11:30:45.123345", 0, "113045"),
("11:30:45.123345", 3, "113045.123"),
("11:30:45.123345", 5, "113045.12335"),
("11:30:45.123345", 6, "113045.123345"),
("11:30:45.1233456", 6, "113045.123346"),
("11:30:45.9233456", 0, "113046"),
("-11:30:45.9233456", 0, "-113046"),
];
for (input, fsp, exp) in cases {
let t = Duration::parse(input.as_bytes(), fsp).unwrap();
let res = format!("{}", Decimal::try_from(t).unwrap());
assert_eq!(exp, res);
}
let cases = vec![
("2012-12-31 11:30:45.123456", 4, "113045.1235"),
("2012-12-31 11:30:45.123456", 6, "113045.123456"),
("2012-12-31 11:30:45.123456", 0, "113045"),
("2012-12-31 11:30:45.999999", 0, "113046"),
("2017-01-05 08:40:59.575601", 0, "084100"),
("2017-01-05 23:59:59.575601", 0, "000000"),
("0000-00-00 00:00:00", 6, "000000"),
];
let mut ctx = EvalContext::default();
for (s, fsp, expect) in cases {
let t = DateTime::parse_utc_datetime(s, fsp).unwrap();
let du = t.to_duration().unwrap();
let get = Decimal::try_from(du).unwrap();
assert_eq!(
get,
convert_bytes_to_decimal(&mut ctx, expect.as_bytes()).unwrap(),
"convert duration {} to decimal",
s
);
}
}
#[test]
fn test_round_frac() {
let cases = vec![
("11:30:45.123456", 4, "11:30:45.1235"),
("11:30:45.123456", 6, "11:30:45.123456"),
("11:30:45.123456", 0, "11:30:45"),
("11:59:59.999999", 3, "12:00:00.000"),
("1 11:30:45.123456", 1, "35:30:45.1"),
("1 11:30:45.999999", 4, "35:30:46.0000"),
("-1 11:30:45.999999", 0, "-35:30:46"),
("-1 11:59:59.9999", 2, "-36:00:00.00"),
];
for (input, fsp, exp) in cases {
let t = Duration::parse(input.as_bytes(), MAX_FSP)
.unwrap()
.round_frac(fsp)
.unwrap();
let res = format!("{}", t);
assert_eq!(exp, res);
}
}
#[test]
fn test_codec() {
let cases = vec![
("11:30:45.123456", 4),
("11:30:45.123456", 6),
("11:30:45.123456", 0),
("11:59:59.999999", 3),
("1 11:30:45.123456", 1),
("1 11:30:45.999999", 4),
("-1 11:30:45.999999", 0),
("-1 11:59:59.9999", 2),
];
for (input, fsp) in cases {
let t = Duration::parse(input.as_bytes(), fsp).unwrap();
let mut buf = vec![];
buf.encode_duration(t).unwrap();
let got = Duration::decode(&mut buf.as_slice()).unwrap();
assert_eq!(t, got);
}
}
#[test]
fn test_checked_add_and_sub_duration() {
/// `MAX_TIME_IN_SECS` is the maximum for mysql time type.
const MAX_TIME_IN_SECS: i64 =
(MAX_HOURS * SECS_PER_HOUR + MAX_MINUTES * SECS_PER_MINUTE + MAX_SECONDS) as i64;
let cases = vec![
("11:30:45.123456", "00:00:14.876545", "11:31:00.000001"),
("11:30:45.123456", "00:30:00", "12:00:45.123456"),
("11:30:45.123456", "12:30:00", "1 00:00:45.123456"),
("11:30:45.123456", "1 12:30:00", "2 00:00:45.123456"),
];
for (lhs, rhs, exp) in cases.clone() {
let lhs = Duration::parse(lhs.as_bytes(), 6).unwrap();
let rhs = Duration::parse(rhs.as_bytes(), 6).unwrap();
let res = lhs.checked_add(rhs).unwrap();
let exp = Duration::parse(exp.as_bytes(), 6).unwrap();
assert_eq!(res, exp);
}
for (exp, rhs, lhs) in cases {
let lhs = Duration::parse(lhs.as_bytes(), 6).unwrap();
let rhs = Duration::parse(rhs.as_bytes(), 6).unwrap();
let res = lhs.checked_sub(rhs).unwrap();
let exp = Duration::parse(exp.as_bytes(), 6).unwrap();
assert_eq!(res, exp);
}
let lhs = Duration::parse(b"00:00:01", 6).unwrap();
let rhs = Duration::from_nanos(MAX_TIME_IN_SECS * NANOS_PER_SEC, 6).unwrap();
assert_eq!(lhs.checked_add(rhs), None);
let lhs = Duration::parse(b"-00:00:01", 6).unwrap();
let rhs = Duration::from_nanos(MAX_TIME_IN_SECS * NANOS_PER_SEC, 6).unwrap();
assert_eq!(lhs.checked_sub(rhs), None);
}
}
#[cfg(test)]
mod benches {
use super::*;
use crate::coprocessor::codec::mysql::MAX_FSP;
#[bench]
fn bench_parse(b: &mut test::Bencher) {
let cases = vec![
("12:34:56.1234", 0),
("12:34:56.789", 1),
("10:20:30.189", 2),
("2 27:54:32.828", 3),
("2 33:44:55.666777", 4),
("112233.445566", 5),
("1 23:12.1234567", 6),
];
b.iter(|| {
let cases = test::black_box(&cases);
for &(s, fsp) in cases {
let _ = test::black_box(Duration::parse(s.as_bytes(), fsp).unwrap());
}
})
}
#[bench]
fn bench_hours(b: &mut test::Bencher) {
let cases = &(3600..=7200)
.map(|second| Duration::from_millis(second * 1000, MAX_FSP).unwrap())
.collect::<Vec<Duration>>();
b.iter(|| {
for duration in cases {
let duration = test::black_box(duration);
let _ = test::black_box(duration.hours());
}
})
}
#[bench]
fn bench_to_decimal(b: &mut test::Bencher) {
let duration = Duration::parse(b"-12:34:56.123456", 6).unwrap();
b.iter(|| {
let duration = test::black_box(duration);
let _ = test::black_box(Decimal::try_from(duration).unwrap());
})
}
#[bench]
fn bench_round_frac(b: &mut test::Bencher) {
let (duration, fsp) = (Duration::parse(b"12:34:56.789", 3).unwrap(), 2);
b.iter(|| {
let (duration, fsp) = (test::black_box(duration), test::black_box(fsp));
let _ = test::black_box(duration.round_frac(fsp).unwrap());
})
}
#[bench]
fn bench_codec(b: &mut test::Bencher) {
let cases: Vec<_> = vec![
("12:34:56.1234", 0),
("12:34:56.789", 1),
("10:20:30.189", 2),
("2 27:54:32.828", 3),
("2 33:44:55.666777", 4),
("112233.445566", 5),
("1 23", 5),
("1 23:12.1234567", 6),
]
.into_iter()
.map(|(s, fsp)| Duration::parse(s.as_bytes(), fsp).unwrap())
.collect();
b.iter(|| {
let cases = test::black_box(&cases);
for &duration in cases {
let t = test::black_box(duration);
let mut buf = vec![];
buf.encode_duration(t).unwrap();
let got = test::black_box(Duration::decode(&mut buf.as_slice()).unwrap());
assert_eq!(t, got);
}
})
}
#[bench]
fn bench_checked_add_and_sub_duration(b: &mut test::Bencher) {
let cases: Vec<_> = vec![
("11:30:45.123456", "00:00:14.876545"),
("11:30:45.123456", "00:30:00"),
("11:30:45.123456", "12:30:00"),
("11:30:45.123456", "1 12:30:00"),
]
.into_iter()
.map(|(lhs, rhs)| {
(
Duration::parse(lhs.as_bytes(), MAX_FSP).unwrap(),
Duration::parse(rhs.as_bytes(), MAX_FSP).unwrap(),
)
})
.collect();
b.iter(|| {
let cases = test::black_box(&cases);
for &(lhs, rhs) in cases {
let _ = test::black_box(lhs.checked_add(rhs).unwrap());
let _ = test::black_box(lhs.checked_sub(rhs).unwrap());
}
})
}
}
| 31.42132 | 103 | 0.473183 |
76704d6febad99560df838c051b2f60cd03542a2 | 82 | // -w
#pragma version(1)
#pragma rs java_package_name(foo)
static int foo() {
}
| 10.25 | 33 | 0.670732 |
1d47111ede491c3e785568c751d5a51abbdf52d4 | 3,337 | use std::fmt;
use std::rc::Rc;
use anyhow::{Context, Result};
use clap::crate_version;
use serde::de::DeserializeOwned;
use serde_derive::Deserialize;
use thiserror::Error;
use curl_http::{Client, Response};
use crate::models::*;
const API_URL: &str = "https://api.anyshortcut.com";
thread_local! {
static API: Rc<Api> = Rc::new(Api::new());
}
#[derive(Deserialize, Debug)]
pub struct ApiResponse<T> {
pub code: u32,
pub data: T,
pub message: String,
}
#[derive(Debug, Error)]
pub struct ApiError {
pub code: u32,
pub message: String,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Error)]
pub enum ApiErrorKind {
#[error("Access token required.")]
AccessTokenRequired,
#[error("Invalid access token.")]
InvalidToken,
#[error("Unknown error.")]
UnknownError,
}
impl<T: fmt::Display> fmt::Display for ApiResponse<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{")?;
write!(f, "\n code: {},", self.code)?;
write!(f, "\n data: {},", self.data)?;
write!(f, "\n message: {}", self.message)?;
write!(f, "\n}}")?;
Ok(())
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{")?;
write!(f, "\n code: {},", self.code)?;
write!(f, "\n message: {}", self.message)?;
write!(f, "\n}}")?;
Ok(())
}
}
impl<T> From<ApiResponse<T>> for ApiError {
fn from(response: ApiResponse<T>) -> ApiError {
ApiError {
code: response.code,
message: response.message,
}
}
}
pub struct Api {
client: Client,
}
impl Api {
pub fn new() -> Api {
let mut client = Client::new(API_URL);
client.set_user_agent(&format!("anyshortcut-cli/{}", crate_version!()));
Api { client }
}
/// Returns the current api for the thread.
pub fn get_current() -> Rc<Api> {
API.with(std::clone::Clone::clone)
}
pub fn login_with_access_token(&self, access_token: &str) -> Result<serde_json::Value> {
let response = self
.client
.get(&format!("/user/login?access_token={}", access_token))?;
self.handle_http_response(&response)
}
pub fn get_all_shortcuts(&self) -> Result<ShortcutData> {
let access_token = Meta::get_token();
let response = self.client.get(&format!(
"/shortcuts/all?nested=false&access_token={}",
access_token
))?;
self.handle_http_response(&response)
}
/// Handle http response internally to return correct api error according to api response code.
fn handle_http_response<T: DeserializeOwned>(&self, response: &Response) -> Result<T> {
let api_response = response.deserialize::<ApiResponse<serde_json::Value>>()?;
match api_response.code {
200 => {
let response = response.deserialize::<ApiResponse<T>>()?;
Ok(response.data)
}
1000 => Err(ApiError::from(api_response)).context(ApiErrorKind::AccessTokenRequired),
1001 | 1002 => Err(ApiError::from(api_response)).context(ApiErrorKind::InvalidToken),
_ => Err(ApiError::from(api_response)).context(ApiErrorKind::UnknownError),
}
}
}
| 28.042017 | 99 | 0.585856 |
dbac610dc6e5f9be68076c4317177d024f4a269f | 29 | pub mod format;
pub mod tga;
| 9.666667 | 15 | 0.724138 |
e49c4bff16ce0d2f39638c94b892cf1f4833c501 | 81 | use yew_email_password_example::App;
fn main() {
yew::start_app::<App>();
}
| 13.5 | 36 | 0.654321 |
217fc8cc0369ecf89438a6c3b1929e51ee7f2d00 | 11,052 | use algebra::{
bls12_377::{Bls12_377, Parameters},
bw6_761::Fr,
One, PairingEngine,
};
use bls_gadgets::{utils::is_setup, HashToGroupGadget, YToBitGadget};
use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::{
bls12_377::{G1Gadget, G2Gadget},
fields::fp::FpGadget,
prelude::*,
Assignment,
};
use bls_crypto::{hash_to_curve::try_and_increment::COMPOSITE_HASH_TO_G1, SIG_DOMAIN};
use super::{fr_to_bits, g2_to_bits, to_fr};
use tracing::{span, trace, Level};
type FrGadget = FpGadget<Fr>;
/// An epoch block using optional types so that it can be used to instantiate the
/// trusted setup. Its non-gadget compatible equivalent is [`EpochBlock`]
///
/// [`EpochBlock`]: struct.EpochBlock.html
#[derive(Clone, Debug, Default)]
pub struct EpochData<E: PairingEngine> {
/// The allowed non-signers for the epoch + 1
pub maximum_non_signers: u32,
/// The index of the initial epoch
pub index: Option<u16>,
/// The public keys at the epoch
pub public_keys: Vec<Option<E::G2Projective>>,
}
/// [`EpochData`] is constrained to a `ConstrainedEpochData` via [`EpochData.constrain`]
///
/// [`EpochData`]: struct.EpochData.html
/// [`EpochData.constrain`]: struct.EpochData.html#method.constrain
pub struct ConstrainedEpochData {
/// The epoch's index
pub index: FrGadget,
/// The new threshold needed for signatures
pub maximum_non_signers: FrGadget,
/// The epoch's G1 Hash
pub message_hash: G1Gadget,
/// The new validators for this epoch
pub pubkeys: Vec<G2Gadget>,
/// Serialized epoch data containing the index, max non signers, aggregated pubkey and the pubkeys array
pub bits: Vec<Boolean>,
/// Aux data for proving the CRH->XOF hash outside of BW6_761
pub crh_bits: Vec<Boolean>,
/// Aux data for proving the CRH->XOF hash outside of BW6_761
pub xof_bits: Vec<Boolean>,
}
impl<E: PairingEngine> EpochData<E> {
/// Initializes an empty epoch, to be used for the setup
pub fn empty(num_validators: usize, maximum_non_signers: usize) -> Self {
EpochData::<E> {
index: None,
maximum_non_signers: maximum_non_signers as u32,
public_keys: vec![None; num_validators],
}
}
}
impl EpochData<Bls12_377> {
/// Ensures that the epoch's index is equal to `previous_index + 1`. Enforces that
/// the epoch's G1 hash is correctly calculated, and also provides auxiliary data for
/// verifying the CRH->XOF hash outside of BW6_761.
pub fn constrain<CS: ConstraintSystem<Fr>>(
&self,
cs: &mut CS,
previous_index: &FrGadget,
generate_constraints_for_hash: bool,
) -> Result<ConstrainedEpochData, SynthesisError> {
let span = span!(Level::TRACE, "EpochData");
let _enter = span.enter();
let (bits, index, maximum_non_signers, pubkeys) = self.to_bits(cs)?;
Self::enforce_next_epoch(&mut cs.ns(|| "enforce next epoch"), previous_index, &index)?;
// Hash to G1
let (message_hash, crh_bits, xof_bits) = Self::hash_bits_to_g1(
&mut cs.ns(|| "hash epoch to g1 bits"),
&bits,
generate_constraints_for_hash,
)?;
Ok(ConstrainedEpochData {
bits,
index,
maximum_non_signers,
pubkeys,
message_hash,
crh_bits,
xof_bits,
})
}
/// Encodes the epoch to bits (index and non-signers encoded as LE)
pub fn to_bits<CS: ConstraintSystem<Fr>>(
&self,
cs: &mut CS,
) -> Result<(Vec<Boolean>, FrGadget, FrGadget, Vec<G2Gadget>), SynthesisError> {
let index = to_fr(&mut cs.ns(|| "index"), self.index)?;
let index_bits = fr_to_bits(&mut cs.ns(|| "index bits"), &index, 16)?;
let maximum_non_signers = to_fr(
&mut cs.ns(|| "max non signers"),
Some(self.maximum_non_signers),
)?;
let maximum_non_signers_bits = fr_to_bits(
&mut cs.ns(|| "max non signers bits"),
&maximum_non_signers,
32,
)?;
let mut epoch_bits: Vec<Boolean> = [index_bits, maximum_non_signers_bits].concat();
let mut pubkey_vars = Vec::with_capacity(self.public_keys.len());
for (j, maybe_pk) in self.public_keys.iter().enumerate() {
let pk_var = G2Gadget::alloc(cs.ns(|| format!("pub key {}", j)), || maybe_pk.get())?;
// extend our epoch bits by the pubkeys
let pk_bits = g2_to_bits(&mut cs.ns(|| format!("pubkey to bits {}", j)), &pk_var)?;
epoch_bits.extend_from_slice(&pk_bits);
// save the allocated pubkeys
pubkey_vars.push(pk_var);
}
Ok((epoch_bits, index, maximum_non_signers, pubkey_vars))
}
/// Enforces that `index = previous_index + 1`
fn enforce_next_epoch<CS: ConstraintSystem<Fr>>(
cs: &mut CS,
previous_index: &FrGadget,
index: &FrGadget,
) -> Result<(), SynthesisError> {
trace!("enforcing next epoch");
let previous_plus_one =
previous_index.add_constant(cs.ns(|| "previous plus_one"), &Fr::one())?;
let index_bit =
YToBitGadget::<Parameters>::is_eq_zero(&mut cs.ns(|| "is index zero"), index)?.not();
index.conditional_enforce_equal(
cs.ns(|| "index enforce equal"),
&previous_plus_one,
&index_bit,
)?;
Ok(())
}
/// Packs the provided bits in U8s, and calculates the hash and the counter
/// Also returns the auxiliary CRH and XOF bits for potential compression from consumers
fn hash_bits_to_g1<CS: ConstraintSystem<Fr>>(
cs: &mut CS,
epoch_bits: &[Boolean],
generate_constraints_for_hash: bool,
) -> Result<(G1Gadget, Vec<Boolean>, Vec<Boolean>), SynthesisError> {
trace!("hashing epoch to g1");
// Reverse to LE
let mut epoch_bits = epoch_bits.to_vec();
epoch_bits.reverse();
let is_setup = is_setup(&epoch_bits);
// Pack them to Uint8s
let input_bytes_var: Vec<UInt8> = epoch_bits
.chunks(8)
.map(|chunk| {
let mut chunk = chunk.to_vec();
if chunk.len() < 8 {
chunk.resize(8, Boolean::constant(false));
}
UInt8::from_bits_le(&chunk)
})
.collect();
// Get the inner values
let counter = if is_setup {
0
} else {
// find the counter value for the hash
let input_bytes = input_bytes_var
.iter()
.map(|b| b.get_value().get())
.collect::<Result<Vec<_>, _>>()?;
let (_, counter) = COMPOSITE_HASH_TO_G1
.hash_with_attempt(SIG_DOMAIN, &input_bytes, &[])
.map_err(|_| SynthesisError::Unsatisfiable)?;
counter
};
let counter_var = UInt8::alloc(&mut cs.ns(|| "alloc counter"), || Ok(counter as u8))?;
HashToGroupGadget::<Parameters>::enforce_hash_to_group(
&mut cs.ns(|| "hash to group"),
counter_var,
&input_bytes_var,
generate_constraints_for_hash,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use algebra::{
bls12_377::{Bls12_377, G2Projective as Bls12_377G2Projective},
UniformRand,
};
use r1cs_core::ConstraintSystem;
use r1cs_std::test_constraint_system::TestConstraintSystem;
use crate::epoch_block::EpochBlock;
use bls_crypto::PublicKey;
fn test_epoch(index: u16) -> EpochData<Bls12_377> {
let rng = &mut rand::thread_rng();
let pubkeys = (0..10)
.map(|_| Some(Bls12_377G2Projective::rand(rng)))
.collect::<Vec<_>>();
EpochData::<Bls12_377> {
index: Some(index),
maximum_non_signers: 12,
public_keys: pubkeys,
}
}
#[test]
fn test_enforce() {
let epoch = test_epoch(10);
let mut cs = TestConstraintSystem::<Fr>::new();
let index = to_fr(&mut cs.ns(|| "index"), Some(9u32)).unwrap();
epoch
.constrain(&mut cs.ns(|| "constraint"), &index, false)
.unwrap();
assert!(cs.is_satisfied());
}
#[test]
fn test_hash_epoch_to_g1() {
let epoch = test_epoch(10);
let mut pubkeys = Vec::new();
for pk in &epoch.public_keys {
pubkeys.push(PublicKey::from(pk.unwrap()));
}
// Calculate the hash from our to_bytes function
let epoch_bytes = EpochBlock::new(epoch.index.unwrap(), epoch.maximum_non_signers, pubkeys)
.encode_to_bytes()
.unwrap();
let (hash, _) = COMPOSITE_HASH_TO_G1
.hash_with_attempt(SIG_DOMAIN, &epoch_bytes, &[])
.unwrap();
// compare it with the one calculated in the circuit from its bytes
let mut cs = TestConstraintSystem::<Fr>::new();
let bits = epoch.to_bits(&mut cs.ns(|| "epoch2bits")).unwrap().0;
let ret =
EpochData::hash_bits_to_g1(&mut cs.ns(|| "hash epoch bits"), &bits, false).unwrap();
assert_eq!(ret.0.get_value().unwrap(), hash);
}
#[test]
fn enforce_next_epoch() {
for (index1, index2, expected) in &[
(0u16, 1u16, true),
(1, 3, false),
(3, 1, false),
(100, 101, true),
(1, 0, true),
(5, 0, true),
] {
let mut cs = TestConstraintSystem::<Fr>::new();
let epoch1 = to_fr(&mut cs.ns(|| "1"), Some(*index1)).unwrap();
let epoch2 = to_fr(&mut cs.ns(|| "2"), Some(*index2)).unwrap();
EpochData::enforce_next_epoch(&mut cs, &epoch1, &epoch2).unwrap();
assert_eq!(cs.is_satisfied(), *expected);
}
}
#[test]
fn epoch_to_bits_ok() {
let epoch = test_epoch(18);
let mut pubkeys = Vec::new();
for pk in &epoch.public_keys {
pubkeys.push(PublicKey::from(pk.unwrap()));
}
// calculate the bits from our helper function
let bits = EpochBlock::new(
epoch.index.unwrap(),
epoch.maximum_non_signers,
pubkeys.clone(),
)
.encode_to_bits()
.unwrap();
// calculate wrong bits
let bits_wrong = EpochBlock::new(epoch.index.unwrap(), epoch.maximum_non_signers, pubkeys)
.encode_to_bits_with_aggregated_pk()
.unwrap();
// calculate the bits from the epoch
let mut cs = TestConstraintSystem::<Fr>::new();
let ret = epoch.to_bits(&mut cs).unwrap();
// compare with the result
let bits_inner = ret
.0
.iter()
.map(|x| x.get_value().unwrap())
.collect::<Vec<_>>();
assert_eq!(bits_inner, bits);
assert_ne!(bits_inner, bits_wrong);
}
}
| 34.322981 | 108 | 0.581162 |
ff8184e14688a091778607f8c3992577441c02b6 | 1,017 | use std::time::Duration;
use gtk::prelude::*;
use gtk::{self, Application, ApplicationWindow, Button};
fn main() {
// Create a new application
let app = Application::new(Some("org.gtk.example"), Default::default());
app.connect_activate(build_ui);
// Run the application
app.run();
}
fn build_ui(application: &Application) {
// Create a window
let window = ApplicationWindow::builder()
.application(application)
.title("My GTK App")
.build();
// Create a button
let button = Button::builder()
.label("Press me!")
.margin_top(12)
.margin_bottom(12)
.margin_start(12)
.margin_end(12)
.build();
// Connect callback
button.connect_clicked(move |_| {
// GUI is blocked for 5 seconds after the button is pressed
let five_seconds = Duration::from_secs(5);
std::thread::sleep(five_seconds);
});
// Add button
window.set_child(Some(&button));
window.present();
}
| 24.214286 | 76 | 0.608653 |
7af22688c633b56d731cb70214ba348fd226d2eb | 4,652 | #![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignmentFilter {
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[serde(rename = "canDelegate", default, skip_serializing_if = "Option::is_none")]
pub can_delegate: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignmentPropertiesWithScope {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
#[serde(rename = "roleDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub role_definition_id: Option<String>,
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[serde(rename = "principalType", default, skip_serializing_if = "Option::is_none")]
pub principal_type: Option<role_assignment_properties_with_scope::PrincipalType>,
#[serde(rename = "canDelegate", default, skip_serializing_if = "Option::is_none")]
pub can_delegate: Option<bool>,
}
pub mod role_assignment_properties_with_scope {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PrincipalType {
User,
Group,
ServicePrincipal,
Unknown,
DirectoryRoleTemplate,
ForeignGroup,
Application,
#[serde(rename = "MSI")]
Msi,
DirectoryObjectOrGroup,
Everyone,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignment {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<RoleAssignmentPropertiesWithScope>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignmentListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<RoleAssignment>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignmentProperties {
#[serde(rename = "roleDefinitionId")]
pub role_definition_id: String,
#[serde(rename = "principalId")]
pub principal_id: String,
#[serde(rename = "principalType", default, skip_serializing_if = "Option::is_none")]
pub principal_type: Option<role_assignment_properties::PrincipalType>,
#[serde(rename = "canDelegate", default, skip_serializing_if = "Option::is_none")]
pub can_delegate: Option<bool>,
}
pub mod role_assignment_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PrincipalType {
User,
Group,
ServicePrincipal,
Unknown,
DirectoryRoleTemplate,
ForeignGroup,
Application,
#[serde(rename = "MSI")]
Msi,
DirectoryObjectOrGroup,
Everyone,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignmentCreateParameters {
pub properties: RoleAssignmentProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDetail>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetail {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorDetail>,
#[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")]
pub additional_info: Vec<ErrorAdditionalInfo>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorAdditionalInfo {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub info: Option<serde_json::Value>,
}
| 39.760684 | 91 | 0.698624 |
0ecc8f356f55c143744da6b1e245edd1145db297 | 19,188 | #[doc = "Register `XTAL_32K_N` reader"]
pub struct R(crate::R<XTAL_32K_N_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<XTAL_32K_N_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<XTAL_32K_N_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<XTAL_32K_N_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `XTAL_32K_N` writer"]
pub struct W(crate::W<XTAL_32K_N_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<XTAL_32K_N_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<XTAL_32K_N_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<XTAL_32K_N_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `MCU_OE` reader - Output enable of the pad in sleep mode. 1: Output enabled. 0: Output disabled."]
pub struct MCU_OE_R(crate::FieldReader<bool, bool>);
impl MCU_OE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
MCU_OE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for MCU_OE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MCU_OE` writer - Output enable of the pad in sleep mode. 1: Output enabled. 0: Output disabled."]
pub struct MCU_OE_W<'a> {
w: &'a mut W,
}
impl<'a> MCU_OE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
#[doc = "Field `SLP_SEL` reader - Sleep mode selection of this pad. Set to 1 to put the pad in sleep mode."]
pub struct SLP_SEL_R(crate::FieldReader<bool, bool>);
impl SLP_SEL_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
SLP_SEL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SLP_SEL_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SLP_SEL` writer - Sleep mode selection of this pad. Set to 1 to put the pad in sleep mode."]
pub struct SLP_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> SLP_SEL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1);
self.w
}
}
#[doc = "Field `MCU_WPD` reader - Pull-down enable of the pad in sleep mode. 1: Internal pull-down enabled. 0: internal pull-down disabled."]
pub struct MCU_WPD_R(crate::FieldReader<bool, bool>);
impl MCU_WPD_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
MCU_WPD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for MCU_WPD_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MCU_WPD` writer - Pull-down enable of the pad in sleep mode. 1: Internal pull-down enabled. 0: internal pull-down disabled."]
pub struct MCU_WPD_W<'a> {
w: &'a mut W,
}
impl<'a> MCU_WPD_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2);
self.w
}
}
#[doc = "Field `MCU_WPU` reader - Pull-up enable of the pad during sleep mode. 1: Internal pull-up enabled. 0: Internal pull-up disabled."]
pub struct MCU_WPU_R(crate::FieldReader<bool, bool>);
impl MCU_WPU_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
MCU_WPU_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for MCU_WPU_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MCU_WPU` writer - Pull-up enable of the pad during sleep mode. 1: Internal pull-up enabled. 0: Internal pull-up disabled."]
pub struct MCU_WPU_W<'a> {
w: &'a mut W,
}
impl<'a> MCU_WPU_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3);
self.w
}
}
#[doc = "Field `MCU_IE` reader - Input enable of the pad during sleep mode. 1: Input enabled. 0: Input disabled."]
pub struct MCU_IE_R(crate::FieldReader<bool, bool>);
impl MCU_IE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
MCU_IE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for MCU_IE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MCU_IE` writer - Input enable of the pad during sleep mode. 1: Input enabled. 0: Input disabled."]
pub struct MCU_IE_W<'a> {
w: &'a mut W,
}
impl<'a> MCU_IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4);
self.w
}
}
#[doc = "Field `FUN_WPD` reader - Pull-down enable of the pad. 1: Internal pull-down enabled. 0: internal pull-down disabled."]
pub struct FUN_WPD_R(crate::FieldReader<bool, bool>);
impl FUN_WPD_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
FUN_WPD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for FUN_WPD_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FUN_WPD` writer - Pull-down enable of the pad. 1: Internal pull-down enabled. 0: internal pull-down disabled."]
pub struct FUN_WPD_W<'a> {
w: &'a mut W,
}
impl<'a> FUN_WPD_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u32 & 0x01) << 7);
self.w
}
}
#[doc = "Field `FUN_WPU` reader - Pull-up enable of the pad. 1: Internal pull-up enabled. 0: Internal pull-up disabled."]
pub struct FUN_WPU_R(crate::FieldReader<bool, bool>);
impl FUN_WPU_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
FUN_WPU_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for FUN_WPU_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FUN_WPU` writer - Pull-up enable of the pad. 1: Internal pull-up enabled. 0: Internal pull-up disabled."]
pub struct FUN_WPU_W<'a> {
w: &'a mut W,
}
impl<'a> FUN_WPU_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | ((value as u32 & 0x01) << 8);
self.w
}
}
#[doc = "Field `FUN_IE` reader - Input enable of the pad. 1: Input enabled. 0: Input disabled."]
pub struct FUN_IE_R(crate::FieldReader<bool, bool>);
impl FUN_IE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
FUN_IE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for FUN_IE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FUN_IE` writer - Input enable of the pad. 1: Input enabled. 0: Input disabled."]
pub struct FUN_IE_W<'a> {
w: &'a mut W,
}
impl<'a> FUN_IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | ((value as u32 & 0x01) << 9);
self.w
}
}
#[doc = "Field `FUN_DRV` reader - Select the drive strength of the pad. 0: ~5 mA. 1: ~10 mA. 2: ~20 mA. 3: ~40 mA."]
pub struct FUN_DRV_R(crate::FieldReader<u8, u8>);
impl FUN_DRV_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
FUN_DRV_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for FUN_DRV_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FUN_DRV` writer - Select the drive strength of the pad. 0: ~5 mA. 1: ~10 mA. 2: ~20 mA. 3: ~40 mA."]
pub struct FUN_DRV_W<'a> {
w: &'a mut W,
}
impl<'a> FUN_DRV_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 10)) | ((value as u32 & 0x03) << 10);
self.w
}
}
#[doc = "Field `MCU_SEL` reader - Select IO MUX function for this signal. 0: Select Function 1. 1: Select Function 2, etc."]
pub struct MCU_SEL_R(crate::FieldReader<u8, u8>);
impl MCU_SEL_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
MCU_SEL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for MCU_SEL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MCU_SEL` writer - Select IO MUX function for this signal. 0: Select Function 1. 1: Select Function 2, etc."]
pub struct MCU_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> MCU_SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 12)) | ((value as u32 & 0x07) << 12);
self.w
}
}
#[doc = "Field `FILTER_EN` reader - Enable filter for pin input signals. 1: Filter enabled. 2: Filter disabled."]
pub struct FILTER_EN_R(crate::FieldReader<bool, bool>);
impl FILTER_EN_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
FILTER_EN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for FILTER_EN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FILTER_EN` writer - Enable filter for pin input signals. 1: Filter enabled. 2: Filter disabled."]
pub struct FILTER_EN_W<'a> {
w: &'a mut W,
}
impl<'a> FILTER_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | ((value as u32 & 0x01) << 15);
self.w
}
}
impl R {
#[doc = "Bit 0 - Output enable of the pad in sleep mode. 1: Output enabled. 0: Output disabled."]
#[inline(always)]
pub fn mcu_oe(&self) -> MCU_OE_R {
MCU_OE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Sleep mode selection of this pad. Set to 1 to put the pad in sleep mode."]
#[inline(always)]
pub fn slp_sel(&self) -> SLP_SEL_R {
SLP_SEL_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Pull-down enable of the pad in sleep mode. 1: Internal pull-down enabled. 0: internal pull-down disabled."]
#[inline(always)]
pub fn mcu_wpd(&self) -> MCU_WPD_R {
MCU_WPD_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Pull-up enable of the pad during sleep mode. 1: Internal pull-up enabled. 0: Internal pull-up disabled."]
#[inline(always)]
pub fn mcu_wpu(&self) -> MCU_WPU_R {
MCU_WPU_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Input enable of the pad during sleep mode. 1: Input enabled. 0: Input disabled."]
#[inline(always)]
pub fn mcu_ie(&self) -> MCU_IE_R {
MCU_IE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 7 - Pull-down enable of the pad. 1: Internal pull-down enabled. 0: internal pull-down disabled."]
#[inline(always)]
pub fn fun_wpd(&self) -> FUN_WPD_R {
FUN_WPD_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Pull-up enable of the pad. 1: Internal pull-up enabled. 0: Internal pull-up disabled."]
#[inline(always)]
pub fn fun_wpu(&self) -> FUN_WPU_R {
FUN_WPU_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Input enable of the pad. 1: Input enabled. 0: Input disabled."]
#[inline(always)]
pub fn fun_ie(&self) -> FUN_IE_R {
FUN_IE_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bits 10:11 - Select the drive strength of the pad. 0: ~5 mA. 1: ~10 mA. 2: ~20 mA. 3: ~40 mA."]
#[inline(always)]
pub fn fun_drv(&self) -> FUN_DRV_R {
FUN_DRV_R::new(((self.bits >> 10) & 0x03) as u8)
}
#[doc = "Bits 12:14 - Select IO MUX function for this signal. 0: Select Function 1. 1: Select Function 2, etc."]
#[inline(always)]
pub fn mcu_sel(&self) -> MCU_SEL_R {
MCU_SEL_R::new(((self.bits >> 12) & 0x07) as u8)
}
#[doc = "Bit 15 - Enable filter for pin input signals. 1: Filter enabled. 2: Filter disabled."]
#[inline(always)]
pub fn filter_en(&self) -> FILTER_EN_R {
FILTER_EN_R::new(((self.bits >> 15) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Output enable of the pad in sleep mode. 1: Output enabled. 0: Output disabled."]
#[inline(always)]
pub fn mcu_oe(&mut self) -> MCU_OE_W {
MCU_OE_W { w: self }
}
#[doc = "Bit 1 - Sleep mode selection of this pad. Set to 1 to put the pad in sleep mode."]
#[inline(always)]
pub fn slp_sel(&mut self) -> SLP_SEL_W {
SLP_SEL_W { w: self }
}
#[doc = "Bit 2 - Pull-down enable of the pad in sleep mode. 1: Internal pull-down enabled. 0: internal pull-down disabled."]
#[inline(always)]
pub fn mcu_wpd(&mut self) -> MCU_WPD_W {
MCU_WPD_W { w: self }
}
#[doc = "Bit 3 - Pull-up enable of the pad during sleep mode. 1: Internal pull-up enabled. 0: Internal pull-up disabled."]
#[inline(always)]
pub fn mcu_wpu(&mut self) -> MCU_WPU_W {
MCU_WPU_W { w: self }
}
#[doc = "Bit 4 - Input enable of the pad during sleep mode. 1: Input enabled. 0: Input disabled."]
#[inline(always)]
pub fn mcu_ie(&mut self) -> MCU_IE_W {
MCU_IE_W { w: self }
}
#[doc = "Bit 7 - Pull-down enable of the pad. 1: Internal pull-down enabled. 0: internal pull-down disabled."]
#[inline(always)]
pub fn fun_wpd(&mut self) -> FUN_WPD_W {
FUN_WPD_W { w: self }
}
#[doc = "Bit 8 - Pull-up enable of the pad. 1: Internal pull-up enabled. 0: Internal pull-up disabled."]
#[inline(always)]
pub fn fun_wpu(&mut self) -> FUN_WPU_W {
FUN_WPU_W { w: self }
}
#[doc = "Bit 9 - Input enable of the pad. 1: Input enabled. 0: Input disabled."]
#[inline(always)]
pub fn fun_ie(&mut self) -> FUN_IE_W {
FUN_IE_W { w: self }
}
#[doc = "Bits 10:11 - Select the drive strength of the pad. 0: ~5 mA. 1: ~10 mA. 2: ~20 mA. 3: ~40 mA."]
#[inline(always)]
pub fn fun_drv(&mut self) -> FUN_DRV_W {
FUN_DRV_W { w: self }
}
#[doc = "Bits 12:14 - Select IO MUX function for this signal. 0: Select Function 1. 1: Select Function 2, etc."]
#[inline(always)]
pub fn mcu_sel(&mut self) -> MCU_SEL_W {
MCU_SEL_W { w: self }
}
#[doc = "Bit 15 - Enable filter for pin input signals. 1: Filter enabled. 2: Filter disabled."]
#[inline(always)]
pub fn filter_en(&mut self) -> FILTER_EN_W {
FILTER_EN_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Configuration register for pad XTAL_32K_N\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [xtal_32k_n](index.html) module"]
pub struct XTAL_32K_N_SPEC;
impl crate::RegisterSpec for XTAL_32K_N_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [xtal_32k_n::R](R) reader structure"]
impl crate::Readable for XTAL_32K_N_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [xtal_32k_n::W](W) writer structure"]
impl crate::Writable for XTAL_32K_N_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets XTAL_32K_N to value 0x0b00"]
impl crate::Resettable for XTAL_32K_N_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x0b00
}
}
| 34.021277 | 432 | 0.588649 |
75c4d5073f03bc4e159b4e48857b296da897c38d | 1,469 | use super::cast::*;
impl Cast<bool> for i8 {
fn to(v: bool) -> Self {
v as Self
}
}
impl Cast<u8> for i8 {
fn to(v: u8) -> Self {
cast!(v, i8)
}
}
impl Cast<i8> for i8 {
fn to(v: i8) -> Self {
v
}
}
impl Cast<u16> for i8 {
fn to(v: u16) -> Self {
cast!(v, i8)
}
}
impl Cast<i16> for i8 {
fn to(v: i16) -> Self {
cast!(v, i8)
}
}
impl Cast<u32> for i8 {
fn to(v: u32) -> Self {
cast!(v, i8)
}
}
impl Cast<i32> for i8 {
fn to(v: i32) -> Self {
cast!(v, i8)
}
}
impl Cast<u64> for i8 {
fn to(v: u64) -> Self {
cast!(v, i8)
}
}
impl Cast<i64> for i8 {
fn to(v: i64) -> Self {
cast!(v, i8)
}
}
impl Cast<u128> for i8 {
fn to(v: u128) -> Self {
cast!(v, i8)
}
}
impl Cast<i128> for i8 {
fn to(v: i128) -> Self {
cast!(v, i8)
}
}
impl Cast<usize> for i8 {
fn to(v: usize) -> Self {
cast!(v, i8)
}
}
impl Cast<isize> for i8 {
fn to(v: isize) -> Self {
cast!(v, i8)
}
}
impl Cast<f16> for i8 {
fn to(v: f16) -> Self {
Self::to(v.to_f32())
}
}
impl Cast<f32> for i8 {
fn to(v: f32) -> Self {
let _check = |v: f32| v.trunc() >= i8::min_value() as f32 && v.trunc() <= i8::max_value() as f32;
ASSERT!(_check(v), "Error casting {} to i8", v);
unsafe { v.to_int_unchecked() }
}
}
impl Cast<f64> for i8 {
fn to(v: f64) -> Self {
let _check = |v: f64| v.trunc() >= i8::min_value() as f64 && v.trunc() <= i8::max_value() as f64;
ASSERT!(_check(v), "Error casting {} to i8", v);
unsafe { v.to_int_unchecked() }
}
}
| 16.885057 | 99 | 0.536419 |
5088af4468303e546413cf64e878bb75b1cb6568 | 8,709 | #[doc = "Register `STATUS` reader"]
pub struct R(crate::R<STATUS_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<STATUS_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<STATUS_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<STATUS_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `STATUS` writer"]
pub struct W(crate::W<STATUS_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<STATUS_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<STATUS_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<STATUS_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `STOP` reader - Stop Status Flag"]
pub struct STOP_R(crate::FieldReader<bool, bool>);
impl STOP_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
STOP_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for STOP_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `STOP` writer - Stop Status Flag"]
pub struct STOP_W<'a> {
w: &'a mut W,
}
impl<'a> STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u8 & 0x01);
self.w
}
}
#[doc = "Field `SLAVE` reader - Slave Status Flag"]
pub struct SLAVE_R(crate::FieldReader<bool, bool>);
impl SLAVE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
SLAVE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SLAVE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SLAVE` writer - Slave Status Flag"]
pub struct SLAVE_W<'a> {
w: &'a mut W,
}
impl<'a> SLAVE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u8 & 0x01) << 1);
self.w
}
}
#[doc = "Field `PERBUFV` reader - Synchronization Busy Status"]
pub struct PERBUFV_R(crate::FieldReader<bool, bool>);
impl PERBUFV_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
PERBUFV_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for PERBUFV_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `PERBUFV` writer - Synchronization Busy Status"]
pub struct PERBUFV_W<'a> {
w: &'a mut W,
}
impl<'a> PERBUFV_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u8 & 0x01) << 3);
self.w
}
}
#[doc = "Field `CCBUFV0` reader - Compare channel buffer 0 valid"]
pub struct CCBUFV0_R(crate::FieldReader<bool, bool>);
impl CCBUFV0_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CCBUFV0_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CCBUFV0_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CCBUFV0` writer - Compare channel buffer 0 valid"]
pub struct CCBUFV0_W<'a> {
w: &'a mut W,
}
impl<'a> CCBUFV0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u8 & 0x01) << 4);
self.w
}
}
#[doc = "Field `CCBUFV1` reader - Compare channel buffer 1 valid"]
pub struct CCBUFV1_R(crate::FieldReader<bool, bool>);
impl CCBUFV1_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CCBUFV1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CCBUFV1_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CCBUFV1` writer - Compare channel buffer 1 valid"]
pub struct CCBUFV1_W<'a> {
w: &'a mut W,
}
impl<'a> CCBUFV1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u8 & 0x01) << 5);
self.w
}
}
impl R {
#[doc = "Bit 0 - Stop Status Flag"]
#[inline(always)]
pub fn stop(&self) -> STOP_R {
STOP_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Slave Status Flag"]
#[inline(always)]
pub fn slave(&self) -> SLAVE_R {
SLAVE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 3 - Synchronization Busy Status"]
#[inline(always)]
pub fn perbufv(&self) -> PERBUFV_R {
PERBUFV_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Compare channel buffer 0 valid"]
#[inline(always)]
pub fn ccbufv0(&self) -> CCBUFV0_R {
CCBUFV0_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Compare channel buffer 1 valid"]
#[inline(always)]
pub fn ccbufv1(&self) -> CCBUFV1_R {
CCBUFV1_R::new(((self.bits >> 5) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Stop Status Flag"]
#[inline(always)]
pub fn stop(&mut self) -> STOP_W {
STOP_W { w: self }
}
#[doc = "Bit 1 - Slave Status Flag"]
#[inline(always)]
pub fn slave(&mut self) -> SLAVE_W {
SLAVE_W { w: self }
}
#[doc = "Bit 3 - Synchronization Busy Status"]
#[inline(always)]
pub fn perbufv(&mut self) -> PERBUFV_W {
PERBUFV_W { w: self }
}
#[doc = "Bit 4 - Compare channel buffer 0 valid"]
#[inline(always)]
pub fn ccbufv0(&mut self) -> CCBUFV0_W {
CCBUFV0_W { w: self }
}
#[doc = "Bit 5 - Compare channel buffer 1 valid"]
#[inline(always)]
pub fn ccbufv1(&mut self) -> CCBUFV1_W {
CCBUFV1_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u8) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Status\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [status](index.html) module"]
pub struct STATUS_SPEC;
impl crate::RegisterSpec for STATUS_SPEC {
type Ux = u8;
}
#[doc = "`read()` method returns [status::R](R) reader structure"]
impl crate::Readable for STATUS_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [status::W](W) writer structure"]
impl crate::Writable for STATUS_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets STATUS to value 0x01"]
impl crate::Resettable for STATUS_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x01
}
}
| 28.837748 | 393 | 0.568148 |
56040384eac9490f24d8cfbc8583f5ed45a7ab27 | 1,661 | use super::{Open, Sink, SinkAsBytes};
use crate::config::AudioFormat;
use crate::convert::Converter;
use crate::decoder::AudioPacket;
use std::fs::OpenOptions;
use std::io::{self, Write};
pub struct StdoutSink {
output: Option<Box<dyn Write>>,
path: Option<String>,
format: AudioFormat,
}
impl Open for StdoutSink {
fn open(path: Option<String>, format: AudioFormat) -> Self {
info!("Using pipe sink with format: {:?}", format);
Self {
output: None,
path,
format,
}
}
}
impl Sink for StdoutSink {
fn start(&mut self) -> io::Result<()> {
if self.output.is_none() {
let output: Box<dyn Write> = match self.path.as_deref() {
Some(path) => {
let open_op = OpenOptions::new()
.write(true)
.open(path)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Box::new(open_op)
}
None => Box::new(io::stdout()),
};
self.output = Some(output);
}
Ok(())
}
sink_as_bytes!();
}
impl SinkAsBytes for StdoutSink {
fn write_bytes(&mut self, data: &[u8]) -> io::Result<()> {
match self.output.as_deref_mut() {
Some(output) => {
output.write_all(data)?;
output.flush()?;
}
None => {
return Err(io::Error::new(io::ErrorKind::Other, "Output is None"));
}
}
Ok(())
}
}
impl StdoutSink {
pub const NAME: &'static str = "pipe";
}
| 24.791045 | 83 | 0.486454 |
90e06221db2ae983187263981be92ed8a47bbea0 | 8,268 | //! Completes keywords, except:
//! - `self`, `super` and `crate`, as these are considered part of path completions.
//! - `await`, as this is a postfix completion we handle this in the postfix completions.
use syntax::{SyntaxKind, T};
use crate::{
context::{PathCompletionContext, PathKind},
patterns::ImmediateLocation,
CompletionContext, CompletionItem, CompletionItemKind, Completions,
};
pub(crate) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionContext) {
if ctx.token.kind() == SyntaxKind::COMMENT {
cov_mark::hit!(no_keyword_completion_in_comments);
return;
}
if matches!(ctx.completion_location, Some(ImmediateLocation::RecordExpr(_))) {
cov_mark::hit!(no_keyword_completion_in_record_lit);
return;
}
if ctx.attribute_under_caret.is_some() {
cov_mark::hit!(no_keyword_completion_in_attr_of_expr);
return;
}
if ctx.is_non_trivial_path() {
cov_mark::hit!(no_keyword_completion_in_non_trivial_path);
return;
}
let mut add_keyword = |kw, snippet| add_keyword(acc, ctx, kw, snippet);
let expects_assoc_item = ctx.expects_assoc_item();
let has_block_expr_parent = ctx.has_block_expr_parent();
let expects_item = ctx.expects_item();
if let Some(PathKind::Vis { has_in_token }) = ctx.path_kind() {
if !has_in_token {
cov_mark::hit!(kw_completion_in);
add_keyword("in", "in");
}
return;
}
if ctx.has_impl_or_trait_prev_sibling() {
add_keyword("where", "where");
if ctx.has_impl_prev_sibling() {
add_keyword("for", "for");
}
return;
}
if ctx.previous_token_is(T![unsafe]) {
if expects_item || expects_assoc_item || has_block_expr_parent {
add_keyword("fn", "fn $1($2) {\n $0\n}")
}
if expects_item || has_block_expr_parent {
add_keyword("trait", "trait $1 {\n $0\n}");
add_keyword("impl", "impl $1 {\n $0\n}");
}
return;
}
if !ctx.has_visibility_prev_sibling()
&& (expects_item || ctx.expects_non_trait_assoc_item() || ctx.expect_field())
{
add_keyword("pub(crate)", "pub(crate)");
add_keyword("pub(super)", "pub(super)");
add_keyword("pub", "pub");
}
if expects_item || expects_assoc_item || has_block_expr_parent {
add_keyword("unsafe", "unsafe");
add_keyword("fn", "fn $1($2) {\n $0\n}");
add_keyword("const", "const $0");
add_keyword("type", "type $0");
}
if expects_item || has_block_expr_parent {
if !ctx.has_visibility_prev_sibling() {
add_keyword("impl", "impl $1 {\n $0\n}");
add_keyword("extern", "extern $0");
}
add_keyword("use", "use $0");
add_keyword("trait", "trait $1 {\n $0\n}");
add_keyword("static", "static $0");
add_keyword("mod", "mod $0");
}
if expects_item {
add_keyword("enum", "enum $1 {\n $0\n}");
add_keyword("struct", "struct $0");
add_keyword("union", "union $1 {\n $0\n}");
}
if ctx.expects_type() {
return;
}
if ctx.expects_expression() {
if !has_block_expr_parent {
add_keyword("unsafe", "unsafe {\n $0\n}");
}
add_keyword("match", "match $1 {\n $0\n}");
add_keyword("while", "while $1 {\n $0\n}");
add_keyword("while let", "while let $1 = $2 {\n $0\n}");
add_keyword("loop", "loop {\n $0\n}");
add_keyword("if", "if $1 {\n $0\n}");
add_keyword("if let", "if let $1 = $2 {\n $0\n}");
add_keyword("for", "for $1 in $2 {\n $0\n}");
add_keyword("true", "true");
add_keyword("false", "false");
}
if ctx.previous_token_is(T![if]) || ctx.previous_token_is(T![while]) || has_block_expr_parent {
add_keyword("let", "let");
}
if ctx.after_if() {
add_keyword("else", "else {\n $0\n}");
add_keyword("else if", "else if $1 {\n $0\n}");
}
if ctx.expects_ident_pat_or_ref_expr() {
add_keyword("mut", "mut ");
}
let (can_be_stmt, in_loop_body) = match ctx.path_context {
Some(PathCompletionContext {
is_trivial_path: true, can_be_stmt, in_loop_body, ..
}) => (can_be_stmt, in_loop_body),
_ => return,
};
if in_loop_body {
if can_be_stmt {
add_keyword("continue", "continue;");
add_keyword("break", "break;");
} else {
add_keyword("continue", "continue");
add_keyword("break", "break");
}
}
let fn_def = match &ctx.function_def {
Some(it) => it,
None => return,
};
add_keyword(
"return",
match (can_be_stmt, fn_def.ret_type().is_some()) {
(true, true) => "return $0;",
(true, false) => "return;",
(false, true) => "return $0",
(false, false) => "return",
},
)
}
fn add_keyword(acc: &mut Completions, ctx: &CompletionContext, kw: &str, snippet: &str) {
let mut item = CompletionItem::new(CompletionItemKind::Keyword, ctx.source_range(), kw);
match ctx.config.snippet_cap {
Some(cap) => {
if snippet.ends_with('}') && ctx.incomplete_let {
cov_mark::hit!(let_semi);
item.insert_snippet(cap, format!("{};", snippet));
} else {
item.insert_snippet(cap, snippet);
}
}
None => {
item.insert_text(if snippet.contains('$') { kw } else { snippet });
}
};
item.add_to(acc);
}
#[cfg(test)]
mod tests {
use expect_test::{expect, Expect};
use crate::tests::{check_edit, completion_list};
fn check(ra_fixture: &str, expect: Expect) {
let actual = completion_list(ra_fixture);
expect.assert_eq(&actual)
}
#[test]
fn test_else_edit_after_if() {
check_edit(
"else",
r#"fn quux() { if true { () } $0 }"#,
r#"fn quux() { if true { () } else {
$0
} }"#,
);
}
#[test]
fn test_keywords_after_unsafe_in_block_expr() {
check(
r"fn my_fn() { unsafe $0 }",
expect![[r#"
kw fn
kw trait
kw impl
sn pd
sn ppd
"#]],
);
}
#[test]
fn test_completion_await_impls_future() {
check(
r#"
//- minicore: future
use core::future::*;
struct A {}
impl Future for A {}
fn foo(a: A) { a.$0 }
"#,
expect![[r#"
kw await expr.await
sn ref &expr
sn refm &mut expr
sn match match expr {}
sn box Box::new(expr)
sn dbg dbg!(expr)
sn dbgr dbg!(&expr)
sn call function(expr)
sn let let
sn letm let mut
"#]],
);
check(
r#"
//- minicore: future
use std::future::*;
fn foo() {
let a = async {};
a.$0
}
"#,
expect![[r#"
kw await expr.await
sn ref &expr
sn refm &mut expr
sn match match expr {}
sn box Box::new(expr)
sn dbg dbg!(expr)
sn dbgr dbg!(&expr)
sn call function(expr)
sn let let
sn letm let mut
"#]],
)
}
#[test]
fn let_semi() {
cov_mark::check!(let_semi);
check_edit(
"match",
r#"
fn main() { let x = $0 }
"#,
r#"
fn main() { let x = match $1 {
$0
}; }
"#,
);
check_edit(
"if",
r#"
fn main() {
let x = $0
let y = 92;
}
"#,
r#"
fn main() {
let x = if $1 {
$0
};
let y = 92;
}
"#,
);
check_edit(
"loop",
r#"
fn main() {
let x = $0
bar();
}
"#,
r#"
fn main() {
let x = loop {
$0
};
bar();
}
"#,
);
}
}
| 26.164557 | 99 | 0.499032 |
fc341751a1153e01c1762b4bc63ae831c3d3504d | 19,251 | // Copyright 2018 Developers of the Rand project.
// Copyright 2017-2018 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Random number generation traits
//!
//! This crate is mainly of interest to crates publishing implementations of
//! [`RngCore`]. Other users are encouraged to use the [`rand`] crate instead
//! which re-exports the main traits and error types.
//!
//! [`RngCore`] is the core trait implemented by algorithmic pseudo-random number
//! generators and external random-number sources.
//!
//! [`SeedableRng`] is an extension trait for construction from fixed seeds and
//! other random number generators.
//!
//! [`Error`] is provided for error-handling. It is safe to use in `no_std`
//! environments.
//!
//! The [`impls`] and [`le`] sub-modules include a few small functions to assist
//! implementation of [`RngCore`].
//!
//! [`rand`]: https://docs.rs/rand
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://rust-random.github.io/rand/"
)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![doc(test(attr(allow(unused_variables), deny(warnings))))]
#![allow(clippy::unreadable_literal)]
#![cfg_attr(not(feature = "std"), no_std)]
use core::convert::AsMut;
use core::default::Default;
#[cfg(all(feature = "alloc", not(feature = "std")))] extern crate alloc;
#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::boxed::Box;
pub use error::Error;
#[cfg(feature = "getrandom")] pub use os::OsRng;
pub mod block;
mod error;
pub mod impls;
pub mod le;
#[cfg(feature = "getrandom")] mod os;
/// The core of a random number generator.
///
/// This trait encapsulates the low-level functionality common to all
/// generators, and is the "back end", to be implemented by generators.
/// End users should normally use the `Rng` trait from the [`rand`] crate,
/// which is automatically implemented for every type implementing `RngCore`.
///
/// Three different methods for generating random data are provided since the
/// optimal implementation of each is dependent on the type of generator. There
/// is no required relationship between the output of each; e.g. many
/// implementations of [`fill_bytes`] consume a whole number of `u32` or `u64`
/// values and drop any remaining unused bytes. The same can happen with the
/// [`next_u32`] and [`next_u64`] methods, implementations may discard some
/// random bits for efficiency.
///
/// The [`try_fill_bytes`] method is a variant of [`fill_bytes`] allowing error
/// handling; it is not deemed sufficiently useful to add equivalents for
/// [`next_u32`] or [`next_u64`] since the latter methods are almost always used
/// with algorithmic generators (PRNGs), which are normally infallible.
///
/// Algorithmic generators implementing [`SeedableRng`] should normally have
/// *portable, reproducible* output, i.e. fix Endianness when converting values
/// to avoid platform differences, and avoid making any changes which affect
/// output (except by communicating that the release has breaking changes).
///
/// Typically implementators will implement only one of the methods available
/// in this trait directly, then use the helper functions from the
/// [`impls`] module to implement the other methods.
///
/// It is recommended that implementations also implement:
///
/// - `Debug` with a custom implementation which *does not* print any internal
/// state (at least, [`CryptoRng`]s should not risk leaking state through
/// `Debug`).
/// - `Serialize` and `Deserialize` (from Serde), preferably making Serde
/// support optional at the crate level in PRNG libs.
/// - `Clone`, if possible.
/// - *never* implement `Copy` (accidental copies may cause repeated values).
/// - *do not* implement `Default` for pseudorandom generators, but instead
/// implement [`SeedableRng`], to guide users towards proper seeding.
/// External / hardware RNGs can choose to implement `Default`.
/// - `Eq` and `PartialEq` could be implemented, but are probably not useful.
///
/// # Example
///
/// A simple example, obviously not generating very *random* output:
///
/// ```
/// #![allow(dead_code)]
/// use rand_core::{RngCore, Error, impls};
///
/// struct CountingRng(u64);
///
/// impl RngCore for CountingRng {
/// fn next_u32(&mut self) -> u32 {
/// self.next_u64() as u32
/// }
///
/// fn next_u64(&mut self) -> u64 {
/// self.0 += 1;
/// self.0
/// }
///
/// fn fill_bytes(&mut self, dest: &mut [u8]) {
/// impls::fill_bytes_via_next(self, dest)
/// }
///
/// fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
/// Ok(self.fill_bytes(dest))
/// }
/// }
/// ```
///
/// [`rand`]: https://docs.rs/rand
/// [`try_fill_bytes`]: RngCore::try_fill_bytes
/// [`fill_bytes`]: RngCore::fill_bytes
/// [`next_u32`]: RngCore::next_u32
/// [`next_u64`]: RngCore::next_u64
pub trait RngCore {
/// Return the next random `u32`.
///
/// RNGs must implement at least one method from this trait directly. In
/// the case this method is not implemented directly, it can be implemented
/// using `self.next_u64() as u32` or via [`impls::next_u32_via_fill`].
fn next_u32(&mut self) -> u32;
/// Return the next random `u64`.
///
/// RNGs must implement at least one method from this trait directly. In
/// the case this method is not implemented directly, it can be implemented
/// via [`impls::next_u64_via_u32`] or via [`impls::next_u64_via_fill`].
fn next_u64(&mut self) -> u64;
/// Fill `dest` with random data.
///
/// RNGs must implement at least one method from this trait directly. In
/// the case this method is not implemented directly, it can be implemented
/// via [`impls::fill_bytes_via_next`] or
/// via [`RngCore::try_fill_bytes`]; if this generator can
/// fail the implementation must choose how best to handle errors here
/// (e.g. panic with a descriptive message or log a warning and retry a few
/// times).
///
/// This method should guarantee that `dest` is entirely filled
/// with new data, and may panic if this is impossible
/// (e.g. reading past the end of a file that is being used as the
/// source of randomness).
fn fill_bytes(&mut self, dest: &mut [u8]);
/// Fill `dest` entirely with random data.
///
/// This is the only method which allows an RNG to report errors while
/// generating random data thus making this the primary method implemented
/// by external (true) RNGs (e.g. `OsRng`) which can fail. It may be used
/// directly to generate keys and to seed (infallible) PRNGs.
///
/// Other than error handling, this method is identical to [`RngCore::fill_bytes`];
/// thus this may be implemented using `Ok(self.fill_bytes(dest))` or
/// `fill_bytes` may be implemented with
/// `self.try_fill_bytes(dest).unwrap()` or more specific error handling.
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>;
}
/// A marker trait used to indicate that an [`RngCore`] or [`BlockRngCore`]
/// implementation is supposed to be cryptographically secure.
///
/// *Cryptographically secure generators*, also known as *CSPRNGs*, should
/// satisfy an additional properties over other generators: given the first
/// *k* bits of an algorithm's output
/// sequence, it should not be possible using polynomial-time algorithms to
/// predict the next bit with probability significantly greater than 50%.
///
/// Some generators may satisfy an additional property, however this is not
/// required by this trait: if the CSPRNG's state is revealed, it should not be
/// computationally-feasible to reconstruct output prior to this. Some other
/// generators allow backwards-computation and are consided *reversible*.
///
/// Note that this trait is provided for guidance only and cannot guarantee
/// suitability for cryptographic applications. In general it should only be
/// implemented for well-reviewed code implementing well-regarded algorithms.
///
/// Note also that use of a `CryptoRng` does not protect against other
/// weaknesses such as seeding from a weak entropy source or leaking state.
///
/// [`BlockRngCore`]: block::BlockRngCore
pub trait CryptoRng {}
/// A random number generator that can be explicitly seeded.
///
/// This trait encapsulates the low-level functionality common to all
/// pseudo-random number generators (PRNGs, or algorithmic generators).
///
/// [`rand`]: https://docs.rs/rand
pub trait SeedableRng: Sized {
/// Seed type, which is restricted to types mutably-dereferencable as `u8`
/// arrays (we recommend `[u8; N]` for some `N`).
///
/// It is recommended to seed PRNGs with a seed of at least circa 100 bits,
/// which means an array of `[u8; 12]` or greater to avoid picking RNGs with
/// partially overlapping periods.
///
/// For cryptographic RNG's a seed of 256 bits is recommended, `[u8; 32]`.
///
///
/// # Implementing `SeedableRng` for RNGs with large seeds
///
/// Note that the required traits `core::default::Default` and
/// `core::convert::AsMut<u8>` are not implemented for large arrays
/// `[u8; N]` with `N` > 32. To be able to implement the traits required by
/// `SeedableRng` for RNGs with such large seeds, the newtype pattern can be
/// used:
///
/// ```
/// use rand_core::SeedableRng;
///
/// const N: usize = 64;
/// pub struct MyRngSeed(pub [u8; N]);
/// pub struct MyRng(MyRngSeed);
///
/// impl Default for MyRngSeed {
/// fn default() -> MyRngSeed {
/// MyRngSeed([0; N])
/// }
/// }
///
/// impl AsMut<[u8]> for MyRngSeed {
/// fn as_mut(&mut self) -> &mut [u8] {
/// &mut self.0
/// }
/// }
///
/// impl SeedableRng for MyRng {
/// type Seed = MyRngSeed;
///
/// fn from_seed(seed: MyRngSeed) -> MyRng {
/// MyRng(seed)
/// }
/// }
/// ```
type Seed: Sized + Default + AsMut<[u8]>;
/// Create a new PRNG using the given seed.
///
/// PRNG implementations are allowed to assume that bits in the seed are
/// well distributed. That means usually that the number of one and zero
/// bits are roughly equal, and values like 0, 1 and (size - 1) are unlikely.
/// Note that many non-cryptographic PRNGs will show poor quality output
/// if this is not adhered to. If you wish to seed from simple numbers, use
/// `seed_from_u64` instead.
///
/// All PRNG implementations should be reproducible unless otherwise noted:
/// given a fixed `seed`, the same sequence of output should be produced
/// on all runs, library versions and architectures (e.g. check endianness).
/// Any "value-breaking" changes to the generator should require bumping at
/// least the minor version and documentation of the change.
///
/// It is not required that this function yield the same state as a
/// reference implementation of the PRNG given equivalent seed; if necessary
/// another constructor replicating behaviour from a reference
/// implementation can be added.
///
/// PRNG implementations should make sure `from_seed` never panics. In the
/// case that some special values (like an all zero seed) are not viable
/// seeds it is preferable to map these to alternative constant value(s),
/// for example `0xBAD5EEDu32` or `0x0DDB1A5E5BAD5EEDu64` ("odd biases? bad
/// seed"). This is assuming only a small number of values must be rejected.
fn from_seed(seed: Self::Seed) -> Self;
/// Create a new PRNG using a `u64` seed.
///
/// This is a convenience-wrapper around `from_seed` to allow construction
/// of any `SeedableRng` from a simple `u64` value. It is designed such that
/// low Hamming Weight numbers like 0 and 1 can be used and should still
/// result in good, independent seeds to the PRNG which is returned.
///
/// This **is not suitable for cryptography**, as should be clear given that
/// the input size is only 64 bits.
///
/// Implementations for PRNGs *may* provide their own implementations of
/// this function, but the default implementation should be good enough for
/// all purposes. *Changing* the implementation of this function should be
/// considered a value-breaking change.
fn seed_from_u64(mut state: u64) -> Self {
// We use PCG32 to generate a u32 sequence, and copy to the seed
const MUL: u64 = 6364136223846793005;
const INC: u64 = 11634580027462260723;
let mut seed = Self::Seed::default();
for chunk in seed.as_mut().chunks_mut(4) {
// We advance the state first (to get away from the input value,
// in case it has low Hamming Weight).
state = state.wrapping_mul(MUL).wrapping_add(INC);
// Use PCG output function with to_le to generate x:
let xorshifted = (((state >> 18) ^ state) >> 27) as u32;
let rot = (state >> 59) as u32;
let x = xorshifted.rotate_right(rot);
chunk.copy_from_slice(&x.to_le_bytes());
}
Self::from_seed(seed)
}
/// Create a new PRNG seeded from another `Rng`.
///
/// This may be useful when needing to rapidly seed many PRNGs from a master
/// PRNG, and to allow forking of PRNGs. It may be considered deterministic.
///
/// The master PRNG should be at least as high quality as the child PRNGs.
/// When seeding non-cryptographic child PRNGs, we recommend using a
/// different algorithm for the master PRNG (ideally a CSPRNG) to avoid
/// correlations between the child PRNGs. If this is not possible (e.g.
/// forking using small non-crypto PRNGs) ensure that your PRNG has a good
/// mixing function on the output or consider use of a hash function with
/// `from_seed`.
///
/// Note that seeding `XorShiftRng` from another `XorShiftRng` provides an
/// extreme example of what can go wrong: the new PRNG will be a clone
/// of the parent.
///
/// PRNG implementations are allowed to assume that a good RNG is provided
/// for seeding, and that it is cryptographically secure when appropriate.
/// As of `rand` 0.7 / `rand_core` 0.5, implementations overriding this
/// method should ensure the implementation satisfies reproducibility
/// (in prior versions this was not required).
///
/// [`rand`]: https://docs.rs/rand
fn from_rng<R: RngCore>(mut rng: R) -> Result<Self, Error> {
let mut seed = Self::Seed::default();
rng.try_fill_bytes(seed.as_mut())?;
Ok(Self::from_seed(seed))
}
/// Creates a new instance of the RNG seeded via [`getrandom`].
///
/// This method is the recommended way to construct non-deterministic PRNGs
/// since it is convenient and secure.
///
/// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
/// issue, one may prefer to seed from a local PRNG, e.g.
/// `from_rng(thread_rng()).unwrap()`.
///
/// # Panics
///
/// If [`getrandom`] is unable to provide secure entropy this method will panic.
///
/// [`getrandom`]: https://docs.rs/getrandom
#[cfg(feature = "getrandom")]
fn from_entropy() -> Self {
let mut seed = Self::Seed::default();
if let Err(err) = getrandom::getrandom(seed.as_mut()) {
panic!("from_entropy failed: {}", err);
}
Self::from_seed(seed)
}
}
// Implement `RngCore` for references to an `RngCore`.
// Force inlining all functions, so that it is up to the `RngCore`
// implementation and the optimizer to decide on inlining.
impl<'a, R: RngCore + ?Sized> RngCore for &'a mut R {
#[inline(always)]
fn next_u32(&mut self) -> u32 {
(**self).next_u32()
}
#[inline(always)]
fn next_u64(&mut self) -> u64 {
(**self).next_u64()
}
#[inline(always)]
fn fill_bytes(&mut self, dest: &mut [u8]) {
(**self).fill_bytes(dest)
}
#[inline(always)]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
(**self).try_fill_bytes(dest)
}
}
// Implement `RngCore` for boxed references to an `RngCore`.
// Force inlining all functions, so that it is up to the `RngCore`
// implementation and the optimizer to decide on inlining.
#[cfg(feature = "alloc")]
impl<R: RngCore + ?Sized> RngCore for Box<R> {
#[inline(always)]
fn next_u32(&mut self) -> u32 {
(**self).next_u32()
}
#[inline(always)]
fn next_u64(&mut self) -> u64 {
(**self).next_u64()
}
#[inline(always)]
fn fill_bytes(&mut self, dest: &mut [u8]) {
(**self).fill_bytes(dest)
}
#[inline(always)]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
(**self).try_fill_bytes(dest)
}
}
#[cfg(feature = "std")]
impl std::io::Read for dyn RngCore {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
self.try_fill_bytes(buf)?;
Ok(buf.len())
}
}
// Implement `CryptoRng` for references to an `CryptoRng`.
impl<'a, R: CryptoRng + ?Sized> CryptoRng for &'a mut R {}
// Implement `CryptoRng` for boxed references to an `CryptoRng`.
#[cfg(feature = "alloc")]
impl<R: CryptoRng + ?Sized> CryptoRng for Box<R> {}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_seed_from_u64() {
struct SeedableNum(u64);
impl SeedableRng for SeedableNum {
type Seed = [u8; 8];
fn from_seed(seed: Self::Seed) -> Self {
let mut x = [0u64; 1];
le::read_u64_into(&seed, &mut x);
SeedableNum(x[0])
}
}
const N: usize = 8;
const SEEDS: [u64; N] = [0u64, 1, 2, 3, 4, 8, 16, -1i64 as u64];
let mut results = [0u64; N];
for (i, seed) in SEEDS.iter().enumerate() {
let SeedableNum(x) = SeedableNum::seed_from_u64(*seed);
results[i] = x;
}
for (i1, r1) in results.iter().enumerate() {
let weight = r1.count_ones();
// This is the binomial distribution B(64, 0.5), so chance of
// weight < 20 is binocdf(19, 64, 0.5) = 7.8e-4, and same for
// weight > 44.
assert!(weight >= 20 && weight <= 44);
for (i2, r2) in results.iter().enumerate() {
if i1 == i2 {
continue;
}
let diff_weight = (r1 ^ r2).count_ones();
assert!(diff_weight >= 20);
}
}
// value-breakage test:
assert_eq!(results[0], 5029875928683246316);
}
}
| 39.529774 | 87 | 0.641058 |
ab7dd541558797c438dd4f4f13ed2f10a09905f3 | 4,014 | // Copyright 2020 Netwarps Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use async_std::task;
use libp2prs_core::{identity, PeerId};
use libp2prs_noise::{Keypair, NoiseConfig, X25519Spec};
use libp2prs_traits::{ReadEx, WriteEx};
use log::info;
use log::LevelFilter;
use std::string::ToString;
fn main() {
env_logger::builder().filter_level(LevelFilter::Info).init();
if std::env::args().nth(1) == Some("server".to_string()) {
info!("Starting server ......");
run_server();
} else {
info!("Starting client .......");
run_client();
}
}
fn run_server() {
task::block_on(async {
let server_id = identity::Keypair::generate_ed25519_fixed();
// let server_id_public = server_id.public();
let pid = PeerId::from(server_id.public());
info!("I am {}", pid);
let listener = async_std::net::TcpListener::bind("127.0.0.1:3214").await.unwrap();
while let Ok((socket, _)) = listener.accept().await {
let server_id = server_id.clone();
task::spawn(async move {
let server_dh = Keypair::<X25519Spec>::new().into_authentic(&server_id).unwrap();
let config = NoiseConfig::xx(server_dh, server_id);
let (_a, mut b) = config.handshake(socket, false).await.unwrap();
info!("handshake finished");
let mut buf = [0; 100];
loop {
info!("outside loop");
if let Ok(_n) = b.read2(&mut buf).await {
// info!("public key is {:?}", b.remote_pub_key());
info!("data is {:?}", buf.to_vec());
// let mut buffer = Vec::from(buf[..11]);
let u = b"!";
// buffer.push(u[0]);
buf[11] = u[0];
if b.write_all2(&buf).await.is_err() {
break;
}
} else {
break;
}
}
});
}
})
}
fn run_client() {
task::block_on(async {
let socket = async_std::net::TcpStream::connect("127.0.0.1:3214").await.unwrap();
info!("[client] connected to server: {:?}", socket.peer_addr());
let client_id = identity::Keypair::generate_ed25519();
// let client_id_public = client_id.public();
let client_dh = Keypair::<X25519Spec>::new().into_authentic(&client_id).unwrap();
let config = NoiseConfig::xx(client_dh, client_id);
let (_a, mut b) = config.handshake(socket, true).await.unwrap();
info!("Handshake finished");
let data = b"hello world";
let _ = b.write_all2(data).await;
info!("write finished");
let mut buf = vec![0u8; 100];
let nr = b.read2(buf.as_mut()).await.unwrap();
info!("read finished, {:?}", &buf[..nr]);
})
}
| 37.867925 | 97 | 0.579472 |
ed56789ef73eb0ec99d0b6b60b00b72800cb59e0 | 686 | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
mod addable_directory;
mod capability;
mod component;
pub mod dir_tree;
pub mod error;
mod exposed_dir;
pub mod framework_services;
pub mod hub;
mod model;
mod moniker;
mod namespace;
mod resolver;
mod routing;
pub mod routing_facade;
mod runner;
pub mod testing;
#[cfg(test)]
pub(crate) mod tests;
pub use self::{
capability::*, component::*, dir_tree::*, error::*, exposed_dir::*, framework_services::*,
hub::*, model::*, moniker::*, namespace::*, resolver::*, routing::*, routing_facade::*,
runner::*,
};
| 23.655172 | 94 | 0.709913 |
295f3afa54dd8d755a2c56238833ff83d4edbdaf | 3,936 | use std::io;
use crossterm_terminal::{Terminal, ClearType};
use termimad::{Area, MadView};
use crate::app::{AppState, AppStateCmdResult};
use crate::app_context::AppContext;
use crate::commands::{Action, Command};
use crate::conf::Conf;
use crate::help_content;
use crate::screens::Screen;
use crate::status::Status;
use crate::task_sync::TaskLifetime;
use crate::verb_store::PrefixSearchResult;
use crate::verbs::VerbExecutor;
/// an application state dedicated to help
pub struct HelpState {
pub view: MadView,
}
impl HelpState {
pub fn new(screen: &Screen, con: &AppContext) -> HelpState {
let area = Area::uninitialized(); // will be fixed at drawing time
Terminal::new().clear(ClearType::All).unwrap();
let markdown = help_content::build_markdown(con);
let view = MadView::from(markdown, area, screen.skin.to_mad_skin());
HelpState { view }
}
fn resize_area(&mut self, screen: &Screen) {
let mut area = Area::new(0, 0, screen.w, screen.h - 2);
area.pad_for_max_width(110);
self.view.resize(&area);
}
}
impl AppState for HelpState {
fn apply(
&mut self,
cmd: &mut Command,
screen: &mut Screen,
con: &AppContext,
) -> io::Result<AppStateCmdResult> {
self.resize_area(screen);
Ok(match &cmd.action {
Action::Back => AppStateCmdResult::PopState,
Action::VerbIndex(index) => {
let verb = &con.verb_store.verbs[*index];
self.execute_verb(verb, &verb.invocation, screen, con)?
},
Action::VerbInvocate(invocation) => match con.verb_store.search(&invocation.key) {
PrefixSearchResult::Match(verb) => {
self.execute_verb(verb, &invocation, screen, con)?
}
_ => AppStateCmdResult::verb_not_found(&invocation.key),
},
Action::MoveSelection(dy) => {
self.view.try_scroll_lines(*dy);
AppStateCmdResult::Keep
}
_ => AppStateCmdResult::Keep,
})
}
fn refresh(&mut self, _screen: &Screen, _con: &AppContext) -> Command {
Command::new()
}
fn has_pending_tasks(&self) -> bool {
false
}
fn do_pending_task(&mut self, _screen: &mut Screen, _tl: &TaskLifetime) {
unreachable!();
}
fn display(&mut self, screen: &mut Screen, _con: &AppContext) -> io::Result<()> {
self.resize_area(screen);
self.view.write()
}
fn write_status(&self, screen: &mut Screen, cmd: &Command, con: &AppContext) -> io::Result<()> {
match &cmd.action {
Action::VerbEdit(invocation) => match con.verb_store.search(&invocation.key) {
PrefixSearchResult::NoMatch => screen.write_status_err("No matching verb"),
PrefixSearchResult::Match(verb) => {
if let Some(err) = verb.match_error(invocation) {
screen.write_status_err(&err)
} else {
screen.write_status_text(
&format!(
"Hit <enter> to {} : {}",
&verb.invocation.key,
&verb.description_for(Conf::default_location(), &invocation.args)
)
.to_string(),
)
}
}
PrefixSearchResult::TooManyMatches => {
screen.write_status_text("Type a verb then <enter> to execute it")
}
},
_ => screen
.write_status_text("Hit <esc> to get back to the tree, or a space to start a verb"),
}
}
fn write_flags(&self, _screen: &mut Screen, _con: &AppContext) -> io::Result<()> {
Ok(())
}
}
| 34.526316 | 100 | 0.544461 |
3814159ebf7411f05a883739e55e2c9e3bd87dbe | 768 | use crate::error::NisporError;
use crate::ifaces::get_ifaces;
use crate::ifaces::Iface;
use crate::route::get_routes;
use crate::route::Route;
use crate::route_rule::get_route_rules;
use crate::route_rule::RouteRule;
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct NetState {
pub ifaces: HashMap<String, Iface>,
pub routes: Vec<Route>,
pub rules: Vec<RouteRule>,
}
impl NetState {
pub fn retrieve() -> Result<NetState, NisporError> {
let ifaces = get_ifaces()?;
let routes = get_routes(&ifaces)?;
let rules = get_route_rules()?;
Ok(NetState {
ifaces,
routes,
rules,
})
}
}
| 25.6 | 58 | 0.647135 |
092299880e2dc3e34ea2c89988b8bf64cbfaaa1e | 351 | // run-pass
// ignore-emscripten apparently only works in optimized mode
const TEST_DATA: [u8; 32 * 1024 * 1024] = [42; 32 * 1024 * 1024];
// Check that the promoted copy of TEST_DATA doesn't
// leave an alloca from an unused temp behind, which,
// without optimizations, can still blow the stack.
fn main() {
println!("{}", TEST_DATA.len());
}
| 29.25 | 65 | 0.68661 |
d65bc820f8fb161ec5510b5aee6f20f9ea00347a | 28,139 | use rustc_ast as ast;
use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
use rustc_ast::{AssocTyConstraint, AssocTyConstraintKind, NodeId};
use rustc_ast::{PatKind, RangeEnd, VariantData};
use rustc_errors::struct_span_err;
use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP};
use rustc_feature::{Features, GateIssue};
use rustc_session::parse::{feature_err, feature_err_issue};
use rustc_session::Session;
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{sym, Symbol};
use rustc_span::Span;
use tracing::debug;
macro_rules! gate_feature_fn {
($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $help: expr) => {{
let (visitor, has_feature, span, name, explain, help) =
(&*$visitor, $has_feature, $span, $name, $explain, $help);
let has_feature: bool = has_feature(visitor.features);
debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
if !has_feature && !span.allows_unstable($name) {
feature_err_issue(&visitor.sess.parse_sess, name, span, GateIssue::Language, explain)
.help(help)
.emit();
}
}};
($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{
let (visitor, has_feature, span, name, explain) =
(&*$visitor, $has_feature, $span, $name, $explain);
let has_feature: bool = has_feature(visitor.features);
debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
if !has_feature && !span.allows_unstable($name) {
feature_err_issue(&visitor.sess.parse_sess, name, span, GateIssue::Language, explain)
.emit();
}
}};
}
macro_rules! gate_feature_post {
($visitor: expr, $feature: ident, $span: expr, $explain: expr, $help: expr) => {
gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain, $help)
};
($visitor: expr, $feature: ident, $span: expr, $explain: expr) => {
gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain)
};
}
pub fn check_attribute(attr: &ast::Attribute, sess: &Session, features: &Features) {
PostExpansionVisitor { sess, features }.visit_attribute(attr)
}
struct PostExpansionVisitor<'a> {
sess: &'a Session,
// `sess` contains a `Features`, but this might not be that one.
features: &'a Features,
}
impl<'a> PostExpansionVisitor<'a> {
fn check_abi(&self, abi: ast::StrLit) {
let ast::StrLit { symbol_unescaped, span, .. } = abi;
match &*symbol_unescaped.as_str() {
// Stable
"Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64"
| "system" => {}
"rust-intrinsic" => {
gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change");
}
"platform-intrinsic" => {
gate_feature_post!(
&self,
platform_intrinsics,
span,
"platform intrinsics are experimental and possibly buggy"
);
}
"vectorcall" => {
gate_feature_post!(
&self,
abi_vectorcall,
span,
"vectorcall is experimental and subject to change"
);
}
"thiscall" => {
gate_feature_post!(
&self,
abi_thiscall,
span,
"thiscall is experimental and subject to change"
);
}
"rust-call" => {
gate_feature_post!(
&self,
unboxed_closures,
span,
"rust-call ABI is subject to change"
);
}
"ptx-kernel" => {
gate_feature_post!(
&self,
abi_ptx,
span,
"PTX ABIs are experimental and subject to change"
);
}
"unadjusted" => {
gate_feature_post!(
&self,
abi_unadjusted,
span,
"unadjusted ABI is an implementation detail and perma-unstable"
);
}
"msp430-interrupt" => {
gate_feature_post!(
&self,
abi_msp430_interrupt,
span,
"msp430-interrupt ABI is experimental and subject to change"
);
}
"x86-interrupt" => {
gate_feature_post!(
&self,
abi_x86_interrupt,
span,
"x86-interrupt ABI is experimental and subject to change"
);
}
"amdgpu-kernel" => {
gate_feature_post!(
&self,
abi_amdgpu_kernel,
span,
"amdgpu-kernel ABI is experimental and subject to change"
);
}
"avr-interrupt" | "avr-non-blocking-interrupt" => {
gate_feature_post!(
&self,
abi_avr_interrupt,
span,
"avr-interrupt and avr-non-blocking-interrupt ABIs are experimental and subject to change"
);
}
"efiapi" => {
gate_feature_post!(
&self,
abi_efiapi,
span,
"efiapi ABI is experimental and subject to change"
);
}
abi => self
.sess
.parse_sess
.span_diagnostic
.delay_span_bug(span, &format!("unrecognized ABI not caught in lowering: {}", abi)),
}
}
fn check_extern(&self, ext: ast::Extern) {
if let ast::Extern::Explicit(abi) = ext {
self.check_abi(abi);
}
}
fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
let has_fields = variants.iter().any(|variant| match variant.data {
VariantData::Tuple(..) | VariantData::Struct(..) => true,
VariantData::Unit(..) => false,
});
let discriminant_spans = variants
.iter()
.filter(|variant| match variant.data {
VariantData::Tuple(..) | VariantData::Struct(..) => false,
VariantData::Unit(..) => true,
})
.filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
.collect::<Vec<_>>();
if !discriminant_spans.is_empty() && has_fields {
let mut err = feature_err(
&self.sess.parse_sess,
sym::arbitrary_enum_discriminant,
discriminant_spans.clone(),
"custom discriminant values are not allowed in enums with tuple or struct variants",
);
for sp in discriminant_spans {
err.span_label(sp, "disallowed custom discriminant");
}
for variant in variants.iter() {
match &variant.data {
VariantData::Struct(..) => {
err.span_label(variant.span, "struct variant defined here");
}
VariantData::Tuple(..) => {
err.span_label(variant.span, "tuple variant defined here");
}
VariantData::Unit(..) => {}
}
}
err.emit();
}
}
fn check_gat(&self, generics: &ast::Generics, span: Span) {
if !generics.params.is_empty() {
gate_feature_post!(
&self,
generic_associated_types,
span,
"generic associated types are unstable"
);
}
if !generics.where_clause.predicates.is_empty() {
gate_feature_post!(
&self,
generic_associated_types,
span,
"where clauses on associated types are unstable"
);
}
}
/// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
fn check_impl_trait(&self, ty: &ast::Ty) {
struct ImplTraitVisitor<'a> {
vis: &'a PostExpansionVisitor<'a>,
}
impl Visitor<'_> for ImplTraitVisitor<'_> {
fn visit_ty(&mut self, ty: &ast::Ty) {
if let ast::TyKind::ImplTrait(..) = ty.kind {
gate_feature_post!(
&self.vis,
type_alias_impl_trait,
ty.span,
"`impl Trait` in type aliases is unstable"
);
}
visit::walk_ty(self, ty);
}
}
ImplTraitVisitor { vis: self }.visit_ty(ty);
}
}
impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
fn visit_attribute(&mut self, attr: &ast::Attribute) {
let attr_info =
attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
// Check feature gates for built-in attributes.
if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
gate_feature_fn!(self, has_feature, attr.span, name, descr);
}
// Check unstable flavors of the `#[doc]` attribute.
if self.sess.check_name(attr, sym::doc) {
for nested_meta in attr.meta_item_list().unwrap_or_default() {
macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
$(if nested_meta.has_name(sym::$name) {
let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
gate_feature_post!(self, $feature, attr.span, msg);
})*
}}
gate_doc!(
include => external_doc
cfg => doc_cfg
masked => doc_masked
spotlight => doc_spotlight
keyword => doc_keyword
);
}
}
}
fn visit_name(&mut self, sp: Span, name: Symbol) {
if !name.as_str().is_ascii() {
gate_feature_post!(
&self,
non_ascii_idents,
self.sess.parse_sess.source_map().guess_head_span(sp),
"non-ascii idents are not fully supported"
);
}
}
fn visit_item(&mut self, i: &'a ast::Item) {
match i.kind {
ast::ItemKind::ForeignMod(ref foreign_module) => {
if let Some(abi) = foreign_module.abi {
self.check_abi(abi);
}
}
ast::ItemKind::Fn(..) => {
if self.sess.contains_name(&i.attrs[..], sym::plugin_registrar) {
gate_feature_post!(
&self,
plugin_registrar,
i.span,
"compiler plugins are experimental and possibly buggy"
);
}
if self.sess.contains_name(&i.attrs[..], sym::start) {
gate_feature_post!(
&self,
start,
i.span,
"`#[start]` functions are experimental \
and their signature may change \
over time"
);
}
if self.sess.contains_name(&i.attrs[..], sym::main) {
gate_feature_post!(
&self,
main,
i.span,
"declaration of a non-standard `#[main]` \
function may change over time, for now \
a top-level `fn main()` is required"
);
}
}
ast::ItemKind::Struct(..) => {
for attr in self.sess.filter_by_name(&i.attrs[..], sym::repr) {
for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.has_name(sym::simd) {
gate_feature_post!(
&self,
repr_simd,
attr.span,
"SIMD types are experimental and possibly buggy"
);
}
}
}
}
ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
for variant in variants {
match (&variant.data, &variant.disr_expr) {
(ast::VariantData::Unit(..), _) => {}
(_, Some(disr_expr)) => gate_feature_post!(
&self,
arbitrary_enum_discriminant,
disr_expr.value.span,
"discriminants on non-unit variants are experimental"
),
_ => {}
}
}
let has_feature = self.features.arbitrary_enum_discriminant;
if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
self.maybe_report_invalid_custom_discriminants(&variants);
}
}
ast::ItemKind::Impl { polarity, defaultness, ref of_trait, .. } => {
if let ast::ImplPolarity::Negative(span) = polarity {
gate_feature_post!(
&self,
negative_impls,
span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(span)),
"negative trait bounds are not yet fully implemented; \
use marker types for now"
);
}
if let ast::Defaultness::Default(_) = defaultness {
gate_feature_post!(&self, specialization, i.span, "specialization is unstable");
}
}
ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
gate_feature_post!(
&self,
auto_traits,
i.span,
"auto traits are experimental and possibly buggy"
);
}
ast::ItemKind::TraitAlias(..) => {
gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
}
ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
let msg = "`macro` is experimental";
gate_feature_post!(&self, decl_macro, i.span, msg);
}
ast::ItemKind::TyAlias(_, _, _, Some(ref ty)) => self.check_impl_trait(&ty),
_ => {}
}
visit::walk_item(self, i);
}
fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
match i.kind {
ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
let link_name = self.sess.first_attr_value_str_by_name(&i.attrs, sym::link_name);
let links_to_llvm =
link_name.map_or(false, |val| val.as_str().starts_with("llvm."));
if links_to_llvm {
gate_feature_post!(
&self,
link_llvm_intrinsics,
i.span,
"linking to LLVM intrinsics is experimental"
);
}
}
ast::ForeignItemKind::TyAlias(..) => {
gate_feature_post!(&self, extern_types, i.span, "extern types are experimental");
}
ast::ForeignItemKind::MacCall(..) => {}
}
visit::walk_foreign_item(self, i)
}
fn visit_ty(&mut self, ty: &'a ast::Ty) {
match ty.kind {
ast::TyKind::BareFn(ref bare_fn_ty) => {
self.check_extern(bare_fn_ty.ext);
}
ast::TyKind::Never => {
gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental");
}
_ => {}
}
visit::walk_ty(self, ty)
}
fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
if let ast::FnRetTy::Ty(ref output_ty) = *ret_ty {
if let ast::TyKind::Never = output_ty.kind {
// Do nothing.
} else {
self.visit_ty(output_ty)
}
}
}
fn visit_expr(&mut self, e: &'a ast::Expr) {
match e.kind {
ast::ExprKind::Box(_) => {
gate_feature_post!(
&self,
box_syntax,
e.span,
"box expression syntax is experimental; you can call `Box::new` instead"
);
}
ast::ExprKind::Type(..) => {
// To avoid noise about type ascription in common syntax errors, only emit if it
// is the *only* error.
if self.sess.parse_sess.span_diagnostic.err_count() == 0 {
gate_feature_post!(
&self,
type_ascription,
e.span,
"type ascription is experimental"
);
}
}
ast::ExprKind::TryBlock(_) => {
gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
}
ast::ExprKind::Block(_, opt_label) => {
if let Some(label) = opt_label {
gate_feature_post!(
&self,
label_break_value,
label.ident.span,
"labels on blocks are unstable"
);
}
}
_ => {}
}
visit::walk_expr(self, e)
}
fn visit_pat(&mut self, pattern: &'a ast::Pat) {
match &pattern.kind {
PatKind::Box(..) => {
gate_feature_post!(
&self,
box_patterns,
pattern.span,
"box pattern syntax is experimental"
);
}
PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
gate_feature_post!(
&self,
exclusive_range_pattern,
pattern.span,
"exclusive range pattern syntax is experimental"
);
}
_ => {}
}
visit::walk_pat(self, pattern)
}
fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
if let Some(header) = fn_kind.header() {
// Stability of const fn methods are covered in `visit_assoc_item` below.
self.check_extern(header.ext);
if let (ast::Const::Yes(_), ast::Extern::Implicit)
| (ast::Const::Yes(_), ast::Extern::Explicit(_)) = (header.constness, header.ext)
{
gate_feature_post!(
&self,
const_extern_fn,
span,
"`const extern fn` definitions are unstable"
);
}
}
if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
}
visit::walk_fn(self, fn_kind, span)
}
fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
if let AssocTyConstraintKind::Bound { .. } = constraint.kind {
gate_feature_post!(
&self,
associated_type_bounds,
constraint.span,
"associated type bounds are unstable"
)
}
visit::walk_assoc_ty_constraint(self, constraint)
}
fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
let is_fn = match i.kind {
ast::AssocItemKind::Fn(_, ref sig, _, _) => {
if let (ast::Const::Yes(_), AssocCtxt::Trait) = (sig.header.constness, ctxt) {
gate_feature_post!(&self, const_fn, i.span, "const fn is unstable");
}
true
}
ast::AssocItemKind::TyAlias(_, ref generics, _, ref ty) => {
if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
gate_feature_post!(
&self,
associated_type_defaults,
i.span,
"associated type defaults are unstable"
);
}
if let Some(ty) = ty {
self.check_impl_trait(ty);
}
self.check_gat(generics, i.span);
false
}
_ => false,
};
if let ast::Defaultness::Default(_) = i.kind.defaultness() {
// Limit `min_specialization` to only specializing functions.
gate_feature_fn!(
&self,
|x: &Features| x.specialization || (is_fn && x.min_specialization),
i.span,
sym::specialization,
"specialization is unstable"
);
}
visit::walk_assoc_item(self, i, ctxt)
}
fn visit_vis(&mut self, vis: &'a ast::Visibility) {
if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.kind {
gate_feature_post!(
&self,
crate_visibility_modifier,
vis.span,
"`crate` visibility modifier is experimental"
);
}
visit::walk_vis(self, vis)
}
}
pub fn check_crate(krate: &ast::Crate, sess: &Session) {
maybe_stage_features(sess, krate);
check_incompatible_features(sess);
let mut visitor = PostExpansionVisitor { sess, features: &sess.features_untracked() };
let spans = sess.parse_sess.gated_spans.spans.borrow();
macro_rules! gate_all {
($gate:ident, $msg:literal, $help:literal) => {
if let Some(spans) = spans.get(&sym::$gate) {
for span in spans {
gate_feature_post!(&visitor, $gate, *span, $msg, $help);
}
}
};
($gate:ident, $msg:literal) => {
if let Some(spans) = spans.get(&sym::$gate) {
for span in spans {
gate_feature_post!(&visitor, $gate, *span, $msg);
}
}
};
}
gate_all!(if_let_guard, "`if let` guards are experimental");
gate_all!(let_chains, "`let` expressions in this position are experimental");
gate_all!(
async_closure,
"async closures are unstable",
"to use an async block, remove the `||`: `async {`"
);
gate_all!(generators, "yield syntax is experimental");
gate_all!(or_patterns, "or-patterns syntax is experimental");
gate_all!(raw_ref_op, "raw address of syntax is experimental");
gate_all!(const_trait_bound_opt_out, "`?const` on trait bounds is experimental");
gate_all!(const_trait_impl, "const trait impls are experimental");
gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
gate_all!(inline_const, "inline-const is experimental");
gate_all!(
extended_key_value_attributes,
"arbitrary expressions in key-value attributes are unstable"
);
gate_all!(
const_generics_defaults,
"default values for const generic parameters are experimental"
);
if sess.parse_sess.span_diagnostic.err_count() == 0 {
// Errors for `destructuring_assignment` can get quite noisy, especially where `_` is
// involved, so we only emit errors where there are no other parsing errors.
gate_all!(destructuring_assignment, "destructuring assignments are unstable");
}
// All uses of `gate_all!` below this point were added in #65742,
// and subsequently disabled (with the non-early gating readded).
macro_rules! gate_all {
($gate:ident, $msg:literal) => {
// FIXME(eddyb) do something more useful than always
// disabling these uses of early feature-gatings.
if false {
for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
gate_feature_post!(&visitor, $gate, *span, $msg);
}
}
};
}
gate_all!(trait_alias, "trait aliases are experimental");
gate_all!(associated_type_bounds, "associated type bounds are unstable");
gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
gate_all!(const_generics, "const generics are unstable");
gate_all!(decl_macro, "`macro` is experimental");
gate_all!(box_patterns, "box pattern syntax is experimental");
gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
gate_all!(try_blocks, "`try` blocks are unstable");
gate_all!(label_break_value, "labels on blocks are unstable");
gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
// To avoid noise about type ascription in common syntax errors,
// only emit if it is the *only* error. (Also check it last.)
if sess.parse_sess.span_diagnostic.err_count() == 0 {
gate_all!(type_ascription, "type ascription is experimental");
}
visit::walk_crate(&mut visitor, krate);
}
fn maybe_stage_features(sess: &Session, krate: &ast::Crate) {
if !sess.opts.unstable_features.is_nightly_build() {
for attr in krate.attrs.iter().filter(|attr| sess.check_name(attr, sym::feature)) {
struct_span_err!(
sess.parse_sess.span_diagnostic,
attr.span,
E0554,
"`#![feature]` may not be used on the {} release channel",
option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")
)
.emit();
}
}
}
fn check_incompatible_features(sess: &Session) {
let features = sess.features_untracked();
let declared_features = features
.declared_lang_features
.iter()
.copied()
.map(|(name, span, _)| (name, span))
.chain(features.declared_lib_features.iter().copied());
for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES
.iter()
.filter(|&&(f1, f2)| features.enabled(f1) && features.enabled(f2))
{
if let Some((f1_name, f1_span)) = declared_features.clone().find(|(name, _)| name == f1) {
if let Some((f2_name, f2_span)) = declared_features.clone().find(|(name, _)| name == f2)
{
let spans = vec![f1_span, f2_span];
sess.struct_span_err(
spans.clone(),
&format!(
"features `{}` and `{}` are incompatible, using them at the same time \
is not allowed",
f1_name, f2_name
),
)
.help("remove one of these features")
.emit();
}
}
}
}
| 38.180461 | 110 | 0.489321 |
5bb1d8a4b94768814c7f53004625db8dabf4b746 | 47,076 | //! A MutVisitor represents an AST modification; it accepts an AST piece and
//! and mutates it in place. So, for instance, macro expansion is a MutVisitor
//! that walks over an AST and modifies it.
//!
//! Note: using a MutVisitor (other than the MacroExpander MutVisitor) on
//! an AST before macro expansion is probably a bad idea. For instance,
//! a MutVisitor renaming item names in a module will miss all of those
//! that are created by the expansion of a macro.
use crate::ast::*;
use crate::source_map::{Spanned, respan};
use crate::parse::token::{self, Token};
use crate::ptr::P;
use crate::symbol::keywords;
use crate::ThinVec;
use crate::tokenstream::*;
use crate::util::map_in_place::MapInPlace;
use smallvec::{smallvec, Array, SmallVec};
use syntax_pos::Span;
use rustc_data_structures::sync::Lrc;
use std::ops::DerefMut;
use std::{panic, process, ptr};
pub trait ExpectOne<A: Array> {
fn expect_one(self, err: &'static str) -> A::Item;
}
impl<A: Array> ExpectOne<A> for SmallVec<A> {
fn expect_one(self, err: &'static str) -> A::Item {
assert!(self.len() == 1, err);
self.into_iter().next().unwrap()
}
}
pub trait MutVisitor: Sized {
// Methods in this trait have one of three forms:
//
// fn visit_t(&mut self, t: &mut T); // common
// fn flat_map_t(&mut self, t: T) -> SmallVec<[T; 1]>; // rare
// fn filter_map_t(&mut self, t: T) -> Option<T>; // rarest
//
// Any additions to this trait should happen in form of a call to a public
// `noop_*` function that only calls out to the visitor again, not other
// `noop_*` functions. This is a necessary API workaround to the problem of
// not being able to call out to the super default method in an overridden
// default method.
//
// When writing these methods, it is better to use destructuring like this:
//
// fn visit_abc(&mut self, ABC { a, b, c: _ }: &mut ABC) {
// visit_a(a);
// visit_b(b);
// }
//
// than to use field access like this:
//
// fn visit_abc(&mut self, abc: &mut ABC) {
// visit_a(&mut abc.a);
// visit_b(&mut abc.b);
// // ignore abc.c
// }
//
// As well as being more concise, the former is explicit about which fields
// are skipped. Furthermore, if a new field is added, the destructuring
// version will cause a compile error, which is good. In comparison, the
// field access version will continue working and it would be easy to
// forget to add handling for it.
fn visit_crate(&mut self, c: &mut Crate) {
noop_visit_crate(c, self)
}
fn visit_meta_list_item(&mut self, list_item: &mut NestedMetaItem) {
noop_visit_meta_list_item(list_item, self);
}
fn visit_meta_item(&mut self, meta_item: &mut MetaItem) {
noop_visit_meta_item(meta_item, self);
}
fn visit_use_tree(&mut self, use_tree: &mut UseTree) {
noop_visit_use_tree(use_tree, self);
}
fn flat_map_foreign_item(&mut self, ni: ForeignItem) -> SmallVec<[ForeignItem; 1]> {
noop_flat_map_foreign_item(ni, self)
}
fn flat_map_item(&mut self, i: P<Item>) -> SmallVec<[P<Item>; 1]> {
noop_flat_map_item(i, self)
}
fn visit_fn_header(&mut self, header: &mut FnHeader) {
noop_visit_fn_header(header, self);
}
fn visit_struct_field(&mut self, sf: &mut StructField) {
noop_visit_struct_field(sf, self);
}
fn visit_item_kind(&mut self, i: &mut ItemKind) {
noop_visit_item_kind(i, self);
}
fn flat_map_trait_item(&mut self, i: TraitItem) -> SmallVec<[TraitItem; 1]> {
noop_flat_map_trait_item(i, self)
}
fn flat_map_impl_item(&mut self, i: ImplItem) -> SmallVec<[ImplItem; 1]> {
noop_flat_map_impl_item(i, self)
}
fn visit_fn_decl(&mut self, d: &mut P<FnDecl>) {
noop_visit_fn_decl(d, self);
}
fn visit_asyncness(&mut self, a: &mut IsAsync) {
noop_visit_asyncness(a, self);
}
fn visit_block(&mut self, b: &mut P<Block>) {
noop_visit_block(b, self);
}
fn flat_map_stmt(&mut self, s: Stmt) -> SmallVec<[Stmt; 1]> {
noop_flat_map_stmt(s, self)
}
fn visit_arm(&mut self, a: &mut Arm) {
noop_visit_arm(a, self);
}
fn visit_guard(&mut self, g: &mut Guard) {
noop_visit_guard(g, self);
}
fn visit_pat(&mut self, p: &mut P<Pat>) {
noop_visit_pat(p, self);
}
fn visit_anon_const(&mut self, c: &mut AnonConst) {
noop_visit_anon_const(c, self);
}
fn visit_expr(&mut self, e: &mut P<Expr>) {
noop_visit_expr(e, self);
}
fn filter_map_expr(&mut self, e: P<Expr>) -> Option<P<Expr>> {
noop_filter_map_expr(e, self)
}
fn visit_generic_arg(&mut self, arg: &mut GenericArg) {
noop_visit_generic_arg(arg, self);
}
fn visit_ty(&mut self, t: &mut P<Ty>) {
noop_visit_ty(t, self);
}
fn visit_lifetime(&mut self, l: &mut Lifetime) {
noop_visit_lifetime(l, self);
}
fn visit_ty_binding(&mut self, t: &mut TypeBinding) {
noop_visit_ty_binding(t, self);
}
fn visit_mod(&mut self, m: &mut Mod) {
noop_visit_mod(m, self);
}
fn visit_foreign_mod(&mut self, nm: &mut ForeignMod) {
noop_visit_foreign_mod(nm, self);
}
fn visit_variant(&mut self, v: &mut Variant) {
noop_visit_variant(v, self);
}
fn visit_ident(&mut self, i: &mut Ident) {
noop_visit_ident(i, self);
}
fn visit_path(&mut self, p: &mut Path) {
noop_visit_path(p, self);
}
fn visit_qself(&mut self, qs: &mut Option<QSelf>) {
noop_visit_qself(qs, self);
}
fn visit_generic_args(&mut self, p: &mut GenericArgs) {
noop_visit_generic_args(p, self);
}
fn visit_angle_bracketed_parameter_data(&mut self, p: &mut AngleBracketedArgs) {
noop_visit_angle_bracketed_parameter_data(p, self);
}
fn visit_parenthesized_parameter_data(&mut self, p: &mut ParenthesizedArgs) {
noop_visit_parenthesized_parameter_data(p, self);
}
fn visit_local(&mut self, l: &mut P<Local>) {
noop_visit_local(l, self);
}
fn visit_mac(&mut self, _mac: &mut Mac) {
panic!("visit_mac disabled by default");
// N.B., see note about macros above. If you really want a visitor that
// works on macros, use this definition in your trait impl:
// mut_visit::noop_visit_mac(_mac, self);
}
fn visit_macro_def(&mut self, def: &mut MacroDef) {
noop_visit_macro_def(def, self);
}
fn visit_label(&mut self, label: &mut Label) {
noop_visit_label(label, self);
}
fn visit_attribute(&mut self, at: &mut Attribute) {
noop_visit_attribute(at, self);
}
fn visit_arg(&mut self, a: &mut Arg) {
noop_visit_arg(a, self);
}
fn visit_generics(&mut self, generics: &mut Generics) {
noop_visit_generics(generics, self);
}
fn visit_trait_ref(&mut self, tr: &mut TraitRef) {
noop_visit_trait_ref(tr, self);
}
fn visit_poly_trait_ref(&mut self, p: &mut PolyTraitRef) {
noop_visit_poly_trait_ref(p, self);
}
fn visit_variant_data(&mut self, vdata: &mut VariantData) {
noop_visit_variant_data(vdata, self);
}
fn visit_generic_param(&mut self, param: &mut GenericParam) {
noop_visit_generic_param(param, self);
}
fn visit_generic_params(&mut self, params: &mut Vec<GenericParam>) {
noop_visit_generic_params(params, self);
}
fn visit_tt(&mut self, tt: &mut TokenTree) {
noop_visit_tt(tt, self);
}
fn visit_tts(&mut self, tts: &mut TokenStream) {
noop_visit_tts(tts, self);
}
fn visit_token(&mut self, t: &mut Token) {
noop_visit_token(t, self);
}
fn visit_interpolated(&mut self, nt: &mut token::Nonterminal) {
noop_visit_interpolated(nt, self);
}
fn visit_param_bound(&mut self, tpb: &mut GenericBound) {
noop_visit_param_bound(tpb, self);
}
fn visit_mt(&mut self, mt: &mut MutTy) {
noop_visit_mt(mt, self);
}
fn visit_field(&mut self, field: &mut Field) {
noop_visit_field(field, self);
}
fn visit_where_clause(&mut self, where_clause: &mut WhereClause) {
noop_visit_where_clause(where_clause, self);
}
fn visit_where_predicate(&mut self, where_predicate: &mut WherePredicate) {
noop_visit_where_predicate(where_predicate, self);
}
fn visit_vis(&mut self, vis: &mut Visibility) {
noop_visit_vis(vis, self);
}
fn visit_id(&mut self, _id: &mut NodeId) {
// Do nothing.
}
fn visit_span(&mut self, _sp: &mut Span) {
// Do nothing.
}
}
/// Use a map-style function (`FnOnce(T) -> T`) to overwrite a `&mut T`. Useful
/// when using a `flat_map_*` or `filter_map_*` method within a `visit_`
/// method. Abort the program if the closure panics.
//
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
pub fn visit_clobber<T, F>(t: &mut T, f: F) where F: FnOnce(T) -> T {
unsafe {
// Safe because `t` is used in a read-only fashion by `read()` before
// being overwritten by `write()`.
let old_t = ptr::read(t);
let new_t = panic::catch_unwind(panic::AssertUnwindSafe(|| f(old_t)))
.unwrap_or_else(|_| process::abort());
ptr::write(t, new_t);
}
}
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
#[inline]
pub fn visit_vec<T, F>(elems: &mut Vec<T>, mut visit_elem: F) where F: FnMut(&mut T) {
for elem in elems {
visit_elem(elem);
}
}
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
#[inline]
pub fn visit_opt<T, F>(opt: &mut Option<T>, mut visit_elem: F) where F: FnMut(&mut T) {
if let Some(elem) = opt {
visit_elem(elem);
}
}
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
pub fn visit_attrs<T: MutVisitor>(attrs: &mut Vec<Attribute>, vis: &mut T) {
visit_vec(attrs, |attr| vis.visit_attribute(attr));
}
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
pub fn visit_thin_attrs<T: MutVisitor>(attrs: &mut ThinVec<Attribute>, vis: &mut T) {
for attr in attrs.iter_mut() {
vis.visit_attribute(attr);
}
}
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
pub fn visit_exprs<T: MutVisitor>(exprs: &mut Vec<P<Expr>>, vis: &mut T) {
exprs.flat_map_in_place(|expr| vis.filter_map_expr(expr))
}
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
pub fn visit_bounds<T: MutVisitor>(bounds: &mut GenericBounds, vis: &mut T) {
visit_vec(bounds, |bound| vis.visit_param_bound(bound));
}
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
pub fn visit_method_sig<T: MutVisitor>(MethodSig { header, decl }: &mut MethodSig, vis: &mut T) {
vis.visit_fn_header(header);
vis.visit_fn_decl(decl);
}
pub fn noop_visit_use_tree<T: MutVisitor>(use_tree: &mut UseTree, vis: &mut T) {
let UseTree { prefix, kind, span } = use_tree;
vis.visit_path(prefix);
match kind {
UseTreeKind::Simple(rename, id1, id2) => {
visit_opt(rename, |rename| vis.visit_ident(rename));
vis.visit_id(id1);
vis.visit_id(id2);
}
UseTreeKind::Nested(items) => {
for (tree, id) in items {
vis.visit_use_tree(tree);
vis.visit_id(id);
}
}
UseTreeKind::Glob => {}
}
vis.visit_span(span);
}
pub fn noop_visit_arm<T: MutVisitor>(Arm { attrs, pats, guard, body }: &mut Arm, vis: &mut T) {
visit_attrs(attrs, vis);
visit_vec(pats, |pat| vis.visit_pat(pat));
visit_opt(guard, |guard| vis.visit_guard(guard));
vis.visit_expr(body);
}
pub fn noop_visit_guard<T: MutVisitor>(g: &mut Guard, vis: &mut T) {
match g {
Guard::If(e) => vis.visit_expr(e),
}
}
pub fn noop_visit_ty_binding<T: MutVisitor>(TypeBinding { id, ident, ty, span }: &mut TypeBinding,
vis: &mut T) {
vis.visit_id(id);
vis.visit_ident(ident);
vis.visit_ty(ty);
vis.visit_span(span);
}
pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) {
let Ty { id, node, span } = ty.deref_mut();
vis.visit_id(id);
match node {
TyKind::Infer | TyKind::ImplicitSelf | TyKind::Err |
TyKind::Never | TyKind::CVarArgs => {}
TyKind::Slice(ty) => vis.visit_ty(ty),
TyKind::Ptr(mt) => vis.visit_mt(mt),
TyKind::Rptr(lt, mt) => {
visit_opt(lt, |lt| noop_visit_lifetime(lt, vis));
vis.visit_mt(mt);
}
TyKind::BareFn(bft) => {
let BareFnTy { unsafety: _, abi: _, generic_params, decl } = bft.deref_mut();
vis.visit_generic_params(generic_params);
vis.visit_fn_decl(decl);
}
TyKind::Tup(tys) => visit_vec(tys, |ty| vis.visit_ty(ty)),
TyKind::Paren(ty) => vis.visit_ty(ty),
TyKind::Path(qself, path) => {
vis.visit_qself(qself);
vis.visit_path(path);
}
TyKind::Array(ty, length) => {
vis.visit_ty(ty);
vis.visit_anon_const(length);
}
TyKind::Typeof(expr) => vis.visit_anon_const(expr),
TyKind::TraitObject(bounds, _syntax) =>
visit_vec(bounds, |bound| vis.visit_param_bound(bound)),
TyKind::ImplTrait(id, bounds) => {
vis.visit_id(id);
visit_vec(bounds, |bound| vis.visit_param_bound(bound));
}
TyKind::Mac(mac) => vis.visit_mac(mac),
}
vis.visit_span(span);
}
pub fn noop_visit_foreign_mod<T: MutVisitor>(foreign_mod: &mut ForeignMod, vis: &mut T) {
let ForeignMod { abi: _, items} = foreign_mod;
items.flat_map_in_place(|item| vis.flat_map_foreign_item(item));
}
pub fn noop_visit_variant<T: MutVisitor>(variant: &mut Variant, vis: &mut T) {
let Spanned { node: Variant_ { ident, attrs, data, disr_expr }, span } = variant;
vis.visit_ident(ident);
visit_attrs(attrs, vis);
vis.visit_variant_data(data);
visit_opt(disr_expr, |disr_expr| vis.visit_anon_const(disr_expr));
vis.visit_span(span);
}
pub fn noop_visit_ident<T: MutVisitor>(Ident { name: _, span }: &mut Ident, vis: &mut T) {
vis.visit_span(span);
}
pub fn noop_visit_path<T: MutVisitor>(Path { segments, span }: &mut Path, vis: &mut T) {
vis.visit_span(span);
for PathSegment { ident, id, args } in segments {
vis.visit_ident(ident);
vis.visit_id(id);
visit_opt(args, |args| vis.visit_generic_args(args));
}
}
pub fn noop_visit_qself<T: MutVisitor>(qself: &mut Option<QSelf>, vis: &mut T) {
visit_opt(qself, |QSelf { ty, path_span, position: _ }| {
vis.visit_ty(ty);
vis.visit_span(path_span);
})
}
pub fn noop_visit_generic_args<T: MutVisitor>(generic_args: &mut GenericArgs, vis: &mut T) {
match generic_args {
GenericArgs::AngleBracketed(data) => vis.visit_angle_bracketed_parameter_data(data),
GenericArgs::Parenthesized(data) => vis.visit_parenthesized_parameter_data(data),
}
}
pub fn noop_visit_generic_arg<T: MutVisitor>(arg: &mut GenericArg, vis: &mut T) {
match arg {
GenericArg::Lifetime(lt) => vis.visit_lifetime(lt),
GenericArg::Type(ty) => vis.visit_ty(ty),
GenericArg::Const(ct) => vis.visit_anon_const(ct),
}
}
pub fn noop_visit_angle_bracketed_parameter_data<T: MutVisitor>(data: &mut AngleBracketedArgs,
vis: &mut T) {
let AngleBracketedArgs { args, bindings, span } = data;
visit_vec(args, |arg| vis.visit_generic_arg(arg));
visit_vec(bindings, |binding| vis.visit_ty_binding(binding));
vis.visit_span(span);
}
pub fn noop_visit_parenthesized_parameter_data<T: MutVisitor>(args: &mut ParenthesizedArgs,
vis: &mut T) {
let ParenthesizedArgs { inputs, output, span } = args;
visit_vec(inputs, |input| vis.visit_ty(input));
visit_opt(output, |output| vis.visit_ty(output));
vis.visit_span(span);
}
pub fn noop_visit_local<T: MutVisitor>(local: &mut P<Local>, vis: &mut T) {
let Local { id, pat, ty, init, span, attrs } = local.deref_mut();
vis.visit_id(id);
vis.visit_pat(pat);
visit_opt(ty, |ty| vis.visit_ty(ty));
visit_opt(init, |init| vis.visit_expr(init));
vis.visit_span(span);
visit_thin_attrs(attrs, vis);
}
pub fn noop_visit_attribute<T: MutVisitor>(attr: &mut Attribute, vis: &mut T) {
let Attribute { id: _, style: _, path, tokens, is_sugared_doc: _, span } = attr;
vis.visit_path(path);
vis.visit_tts(tokens);
vis.visit_span(span);
}
pub fn noop_visit_mac<T: MutVisitor>(Spanned { node, span }: &mut Mac, vis: &mut T) {
let Mac_ { path, delim: _, tts } = node;
vis.visit_path(path);
vis.visit_tts(tts);
vis.visit_span(span);
}
pub fn noop_visit_macro_def<T: MutVisitor>(macro_def: &mut MacroDef, vis: &mut T) {
let MacroDef { tokens, legacy: _ } = macro_def;
vis.visit_tts(tokens);
}
pub fn noop_visit_meta_list_item<T: MutVisitor>(li: &mut NestedMetaItem, vis: &mut T) {
match li {
NestedMetaItem::MetaItem(mi) => vis.visit_meta_item(mi),
NestedMetaItem::Literal(_lit) => {}
}
}
pub fn noop_visit_meta_item<T: MutVisitor>(mi: &mut MetaItem, vis: &mut T) {
let MetaItem { path: _, node, span } = mi;
match node {
MetaItemKind::Word => {}
MetaItemKind::List(mis) => visit_vec(mis, |mi| vis.visit_meta_list_item(mi)),
MetaItemKind::NameValue(_s) => {}
}
vis.visit_span(span);
}
pub fn noop_visit_arg<T: MutVisitor>(Arg { id, pat, ty }: &mut Arg, vis: &mut T) {
vis.visit_id(id);
vis.visit_pat(pat);
vis.visit_ty(ty);
}
pub fn noop_visit_tt<T: MutVisitor>(tt: &mut TokenTree, vis: &mut T) {
match tt {
TokenTree::Token(span, tok) => {
vis.visit_span(span);
vis.visit_token(tok);
}
TokenTree::Delimited(DelimSpan { open, close }, _delim, tts) => {
vis.visit_span(open);
vis.visit_span(close);
vis.visit_tts(tts);
}
}
}
pub fn noop_visit_tts<T: MutVisitor>(TokenStream(tts): &mut TokenStream, vis: &mut T) {
visit_opt(tts, |tts| {
let tts = Lrc::make_mut(tts);
visit_vec(tts, |(tree, _is_joint)| vis.visit_tt(tree));
})
}
// apply ident visitor if it's an ident, apply other visits to interpolated nodes
pub fn noop_visit_token<T: MutVisitor>(t: &mut Token, vis: &mut T) {
match t {
token::Ident(id, _is_raw) => vis.visit_ident(id),
token::Lifetime(id) => vis.visit_ident(id),
token::Interpolated(nt) => {
let mut nt = Lrc::make_mut(nt);
vis.visit_interpolated(&mut nt);
}
_ => {}
}
}
/// Apply visitor to elements of interpolated nodes.
//
// N.B., this can occur only when applying a visitor to partially expanded
// code, where parsed pieces have gotten implanted ito *other* macro
// invocations. This is relevant for macro hygiene, but possibly not elsewhere.
//
// One problem here occurs because the types for flat_map_item, flat_map_stmt,
// etc. allow the visitor to return *multiple* items; this is a problem for the
// nodes here, because they insist on having exactly one piece. One solution
// would be to mangle the MutVisitor trait to include one-to-many and
// one-to-one versions of these entry points, but that would probably confuse a
// lot of people and help very few. Instead, I'm just going to put in dynamic
// checks. I think the performance impact of this will be pretty much
// nonexistent. The danger is that someone will apply a MutVisitor to a
// partially expanded node, and will be confused by the fact that their
// "flat_map_item" or "flat_map_stmt" isn't getting called on NtItem or NtStmt
// nodes. Hopefully they'll wind up reading this comment, and doing something
// appropriate.
//
// BTW, design choice: I considered just changing the type of, e.g., NtItem to
// contain multiple items, but decided against it when I looked at
// parse_item_or_view_item and tried to figure out what I would do with
// multiple items there....
pub fn noop_visit_interpolated<T: MutVisitor>(nt: &mut token::Nonterminal, vis: &mut T) {
match nt {
token::NtItem(item) =>
visit_clobber(item, |item| {
// This is probably okay, because the only visitors likely to
// peek inside interpolated nodes will be renamings/markings,
// which map single items to single items.
vis.flat_map_item(item).expect_one("expected visitor to produce exactly one item")
}),
token::NtBlock(block) => vis.visit_block(block),
token::NtStmt(stmt) =>
visit_clobber(stmt, |stmt| {
// See reasoning above.
vis.flat_map_stmt(stmt).expect_one("expected visitor to produce exactly one item")
}),
token::NtPat(pat) => vis.visit_pat(pat),
token::NtExpr(expr) => vis.visit_expr(expr),
token::NtTy(ty) => vis.visit_ty(ty),
token::NtIdent(ident, _is_raw) => vis.visit_ident(ident),
token::NtLifetime(ident) => vis.visit_ident(ident),
token::NtLiteral(expr) => vis.visit_expr(expr),
token::NtMeta(meta) => vis.visit_meta_item(meta),
token::NtPath(path) => vis.visit_path(path),
token::NtTT(tt) => vis.visit_tt(tt),
token::NtArm(arm) => vis.visit_arm(arm),
token::NtImplItem(item) =>
visit_clobber(item, |item| {
// See reasoning above.
vis.flat_map_impl_item(item)
.expect_one("expected visitor to produce exactly one item")
}),
token::NtTraitItem(item) =>
visit_clobber(item, |item| {
// See reasoning above.
vis.flat_map_trait_item(item)
.expect_one("expected visitor to produce exactly one item")
}),
token::NtGenerics(generics) => vis.visit_generics(generics),
token::NtWhereClause(where_clause) => vis.visit_where_clause(where_clause),
token::NtArg(arg) => vis.visit_arg(arg),
token::NtVis(visib) => vis.visit_vis(visib),
token::NtForeignItem(item) =>
visit_clobber(item, |item| {
// See reasoning above.
vis.flat_map_foreign_item(item)
.expect_one("expected visitor to produce exactly one item")
}),
}
}
pub fn noop_visit_asyncness<T: MutVisitor>(asyncness: &mut IsAsync, vis: &mut T) {
match asyncness {
IsAsync::Async { closure_id, return_impl_trait_id } => {
vis.visit_id(closure_id);
vis.visit_id(return_impl_trait_id);
}
IsAsync::NotAsync => {}
}
}
pub fn noop_visit_fn_decl<T: MutVisitor>(decl: &mut P<FnDecl>, vis: &mut T) {
let FnDecl { inputs, output, c_variadic: _ } = decl.deref_mut();
visit_vec(inputs, |input| vis.visit_arg(input));
match output {
FunctionRetTy::Default(span) => vis.visit_span(span),
FunctionRetTy::Ty(ty) => vis.visit_ty(ty),
}
}
pub fn noop_visit_param_bound<T: MutVisitor>(pb: &mut GenericBound, vis: &mut T) {
match pb {
GenericBound::Trait(ty, _modifier) => vis.visit_poly_trait_ref(ty),
GenericBound::Outlives(lifetime) => noop_visit_lifetime(lifetime, vis),
}
}
pub fn noop_visit_generic_param<T: MutVisitor>(param: &mut GenericParam, vis: &mut T) {
let GenericParam { id, ident, attrs, bounds, kind } = param;
vis.visit_id(id);
vis.visit_ident(ident);
visit_thin_attrs(attrs, vis);
visit_vec(bounds, |bound| noop_visit_param_bound(bound, vis));
match kind {
GenericParamKind::Lifetime => {}
GenericParamKind::Type { default } => {
visit_opt(default, |default| vis.visit_ty(default));
}
GenericParamKind::Const { ty } => {
vis.visit_ty(ty);
}
}
}
pub fn noop_visit_generic_params<T: MutVisitor>(params: &mut Vec<GenericParam>, vis: &mut T){
visit_vec(params, |param| vis.visit_generic_param(param));
}
pub fn noop_visit_label<T: MutVisitor>(Label { ident }: &mut Label, vis: &mut T) {
vis.visit_ident(ident);
}
fn noop_visit_lifetime<T: MutVisitor>(Lifetime { id, ident }: &mut Lifetime, vis: &mut T) {
vis.visit_id(id);
vis.visit_ident(ident);
}
pub fn noop_visit_generics<T: MutVisitor>(generics: &mut Generics, vis: &mut T) {
let Generics { params, where_clause, span } = generics;
vis.visit_generic_params(params);
vis.visit_where_clause(where_clause);
vis.visit_span(span);
}
pub fn noop_visit_where_clause<T: MutVisitor>(wc: &mut WhereClause, vis: &mut T) {
let WhereClause { id, predicates, span } = wc;
vis.visit_id(id);
visit_vec(predicates, |predicate| vis.visit_where_predicate(predicate));
vis.visit_span(span);
}
pub fn noop_visit_where_predicate<T: MutVisitor>(pred: &mut WherePredicate, vis: &mut T) {
match pred {
WherePredicate::BoundPredicate(bp) => {
let WhereBoundPredicate { span, bound_generic_params, bounded_ty, bounds } = bp;
vis.visit_span(span);
vis.visit_generic_params(bound_generic_params);
vis.visit_ty(bounded_ty);
visit_vec(bounds, |bound| vis.visit_param_bound(bound));
}
WherePredicate::RegionPredicate(rp) => {
let WhereRegionPredicate { span, lifetime, bounds } = rp;
vis.visit_span(span);
noop_visit_lifetime(lifetime, vis);
visit_vec(bounds, |bound| noop_visit_param_bound(bound, vis));
}
WherePredicate::EqPredicate(ep) => {
let WhereEqPredicate { id, span, lhs_ty, rhs_ty } = ep;
vis.visit_id(id);
vis.visit_span(span);
vis.visit_ty(lhs_ty);
vis.visit_ty(rhs_ty);
}
}
}
pub fn noop_visit_variant_data<T: MutVisitor>(vdata: &mut VariantData, vis: &mut T) {
match vdata {
VariantData::Struct(fields, id, _) |
VariantData::Tuple(fields, id) => {
visit_vec(fields, |field| vis.visit_struct_field(field));
vis.visit_id(id);
}
VariantData::Unit(id) => vis.visit_id(id),
}
}
pub fn noop_visit_trait_ref<T: MutVisitor>(TraitRef { path, ref_id }: &mut TraitRef, vis: &mut T) {
vis.visit_path(path);
vis.visit_id(ref_id);
}
pub fn noop_visit_poly_trait_ref<T: MutVisitor>(p: &mut PolyTraitRef, vis: &mut T) {
let PolyTraitRef { bound_generic_params, trait_ref, span } = p;
vis.visit_generic_params(bound_generic_params);
vis.visit_trait_ref(trait_ref);
vis.visit_span(span);
}
pub fn noop_visit_struct_field<T: MutVisitor>(f: &mut StructField, visitor: &mut T) {
let StructField { span, ident, vis, id, ty, attrs } = f;
visitor.visit_span(span);
visit_opt(ident, |ident| visitor.visit_ident(ident));
visitor.visit_vis(vis);
visitor.visit_id(id);
visitor.visit_ty(ty);
visit_attrs(attrs, visitor);
}
pub fn noop_visit_field<T: MutVisitor>(f: &mut Field, vis: &mut T) {
let Field { ident, expr, span, is_shorthand: _, attrs } = f;
vis.visit_ident(ident);
vis.visit_expr(expr);
vis.visit_span(span);
visit_thin_attrs(attrs, vis);
}
pub fn noop_visit_mt<T: MutVisitor>(MutTy { ty, mutbl: _ }: &mut MutTy, vis: &mut T) {
vis.visit_ty(ty);
}
pub fn noop_visit_block<T: MutVisitor>(block: &mut P<Block>, vis: &mut T) {
let Block { id, stmts, rules: _, span } = block.deref_mut();
vis.visit_id(id);
stmts.flat_map_in_place(|stmt| vis.flat_map_stmt(stmt));
vis.visit_span(span);
}
pub fn noop_visit_item_kind<T: MutVisitor>(kind: &mut ItemKind, vis: &mut T) {
match kind {
ItemKind::ExternCrate(_orig_name) => {}
ItemKind::Use(use_tree) => vis.visit_use_tree(use_tree),
ItemKind::Static(ty, _mut, expr) => {
vis.visit_ty(ty);
vis.visit_expr(expr);
}
ItemKind::Const(ty, expr) => {
vis.visit_ty(ty);
vis.visit_expr(expr);
}
ItemKind::Fn(decl, header, generics, body) => {
vis.visit_fn_decl(decl);
vis.visit_fn_header(header);
vis.visit_generics(generics);
vis.visit_block(body);
}
ItemKind::Mod(m) => vis.visit_mod(m),
ItemKind::ForeignMod(nm) => vis.visit_foreign_mod(nm),
ItemKind::GlobalAsm(_ga) => {}
ItemKind::Ty(ty, generics) => {
vis.visit_ty(ty);
vis.visit_generics(generics);
}
ItemKind::Existential(bounds, generics) => {
visit_bounds(bounds, vis);
vis.visit_generics(generics);
}
ItemKind::Enum(EnumDef { variants }, generics) => {
visit_vec(variants, |variant| vis.visit_variant(variant));
vis.visit_generics(generics);
}
ItemKind::Struct(variant_data, generics) |
ItemKind::Union(variant_data, generics) => {
vis.visit_variant_data(variant_data);
vis.visit_generics(generics);
}
ItemKind::Impl(_unsafety, _polarity, _defaultness, generics, trait_ref, ty, items) => {
vis.visit_generics(generics);
visit_opt(trait_ref, |trait_ref| vis.visit_trait_ref(trait_ref));
vis.visit_ty(ty);
items.flat_map_in_place(|item| vis.flat_map_impl_item(item));
}
ItemKind::Trait(_is_auto, _unsafety, generics, bounds, items) => {
vis.visit_generics(generics);
visit_bounds(bounds, vis);
items.flat_map_in_place(|item| vis.flat_map_trait_item(item));
}
ItemKind::TraitAlias(generics, bounds) => {
vis.visit_generics(generics);
visit_bounds(bounds, vis);
}
ItemKind::Mac(m) => vis.visit_mac(m),
ItemKind::MacroDef(def) => vis.visit_macro_def(def),
}
}
pub fn noop_flat_map_trait_item<T: MutVisitor>(mut item: TraitItem, vis: &mut T)
-> SmallVec<[TraitItem; 1]>
{
let TraitItem { id, ident, attrs, generics, node, span, tokens: _ } = &mut item;
vis.visit_id(id);
vis.visit_ident(ident);
visit_attrs(attrs, vis);
vis.visit_generics(generics);
match node {
TraitItemKind::Const(ty, default) => {
vis.visit_ty(ty);
visit_opt(default, |default| vis.visit_expr(default));
}
TraitItemKind::Method(sig, body) => {
visit_method_sig(sig, vis);
visit_opt(body, |body| vis.visit_block(body));
}
TraitItemKind::Type(bounds, default) => {
visit_bounds(bounds, vis);
visit_opt(default, |default| vis.visit_ty(default));
}
TraitItemKind::Macro(mac) => {
vis.visit_mac(mac);
}
}
vis.visit_span(span);
smallvec![item]
}
pub fn noop_flat_map_impl_item<T: MutVisitor>(mut item: ImplItem, visitor: &mut T)
-> SmallVec<[ImplItem; 1]>
{
let ImplItem { id, ident, vis, defaultness: _, attrs, generics, node, span, tokens: _ } =
&mut item;
visitor.visit_id(id);
visitor.visit_ident(ident);
visitor.visit_vis(vis);
visit_attrs(attrs, visitor);
visitor.visit_generics(generics);
match node {
ImplItemKind::Const(ty, expr) => {
visitor.visit_ty(ty);
visitor.visit_expr(expr);
}
ImplItemKind::Method(sig, body) => {
visit_method_sig(sig, visitor);
visitor.visit_block(body);
}
ImplItemKind::Type(ty) => visitor.visit_ty(ty),
ImplItemKind::Existential(bounds) => visit_bounds(bounds, visitor),
ImplItemKind::Macro(mac) => visitor.visit_mac(mac),
}
visitor.visit_span(span);
smallvec![item]
}
pub fn noop_visit_fn_header<T: MutVisitor>(header: &mut FnHeader, vis: &mut T) {
let FnHeader { unsafety: _, asyncness, constness: _, abi: _ } = header;
vis.visit_asyncness(&mut asyncness.node);
}
pub fn noop_visit_mod<T: MutVisitor>(Mod { inner, items, inline: _ }: &mut Mod, vis: &mut T) {
vis.visit_span(inner);
items.flat_map_in_place(|item| vis.flat_map_item(item));
}
pub fn noop_visit_crate<T: MutVisitor>(krate: &mut Crate, vis: &mut T) {
visit_clobber(krate, |Crate { module, attrs, span }| {
let item = P(Item {
ident: keywords::Invalid.ident(),
attrs,
id: DUMMY_NODE_ID,
vis: respan(span.shrink_to_lo(), VisibilityKind::Public),
span,
node: ItemKind::Mod(module),
tokens: None,
});
let items = vis.flat_map_item(item);
let len = items.len();
if len == 0 {
let module = Mod { inner: span, items: vec![], inline: true };
Crate { module, attrs: vec![], span }
} else if len == 1 {
let Item { attrs, span, node, .. } = items.into_iter().next().unwrap().into_inner();
match node {
ItemKind::Mod(module) => Crate { module, attrs, span },
_ => panic!("visitor converted a module to not a module"),
}
} else {
panic!("a crate cannot expand to more than one item");
}
});
}
// Mutate one item into possibly many items.
pub fn noop_flat_map_item<T: MutVisitor>(mut item: P<Item>, visitor: &mut T)
-> SmallVec<[P<Item>; 1]> {
let Item { ident, attrs, id, node, vis, span, tokens: _ } = item.deref_mut();
visitor.visit_ident(ident);
visit_attrs(attrs, visitor);
visitor.visit_id(id);
visitor.visit_item_kind(node);
visitor.visit_vis(vis);
visitor.visit_span(span);
// FIXME: if `tokens` is modified with a call to `vis.visit_tts` it causes
// an ICE during resolve... odd!
smallvec![item]
}
pub fn noop_flat_map_foreign_item<T: MutVisitor>(mut item: ForeignItem, visitor: &mut T)
-> SmallVec<[ForeignItem; 1]>
{
let ForeignItem { ident, attrs, node, id, span, vis } = &mut item;
visitor.visit_ident(ident);
visit_attrs(attrs, visitor);
match node {
ForeignItemKind::Fn(fdec, generics) => {
visitor.visit_fn_decl(fdec);
visitor.visit_generics(generics);
}
ForeignItemKind::Static(t, _m) => visitor.visit_ty(t),
ForeignItemKind::Ty => {}
ForeignItemKind::Macro(mac) => visitor.visit_mac(mac),
}
visitor.visit_id(id);
visitor.visit_span(span);
visitor.visit_vis(vis);
smallvec![item]
}
pub fn noop_visit_pat<T: MutVisitor>(pat: &mut P<Pat>, vis: &mut T) {
let Pat { id, node, span } = pat.deref_mut();
vis.visit_id(id);
match node {
PatKind::Wild => {}
PatKind::Ident(_binding_mode, ident, sub) => {
vis.visit_ident(ident);
visit_opt(sub, |sub| vis.visit_pat(sub));
}
PatKind::Lit(e) => vis.visit_expr(e),
PatKind::TupleStruct(path, pats, _ddpos) => {
vis.visit_path(path);
visit_vec(pats, |pat| vis.visit_pat(pat));
}
PatKind::Path(qself, path) => {
vis.visit_qself(qself);
vis.visit_path(path);
}
PatKind::Struct(path, fields, _etc) => {
vis.visit_path(path);
for Spanned { node: FieldPat { ident, pat, is_shorthand: _, attrs }, span } in fields {
vis.visit_ident(ident);
vis.visit_pat(pat);
visit_thin_attrs(attrs, vis);
vis.visit_span(span);
};
}
PatKind::Tuple(elts, _ddpos) => visit_vec(elts, |elt| vis.visit_pat(elt)),
PatKind::Box(inner) => vis.visit_pat(inner),
PatKind::Ref(inner, _mutbl) => vis.visit_pat(inner),
PatKind::Range(e1, e2, Spanned { span: _, node: _ }) => {
vis.visit_expr(e1);
vis.visit_expr(e2);
vis.visit_span(span);
}
PatKind::Slice(before, slice, after) => {
visit_vec(before, |pat| vis.visit_pat(pat));
visit_opt(slice, |slice| vis.visit_pat(slice));
visit_vec(after, |pat| vis.visit_pat(pat));
}
PatKind::Paren(inner) => vis.visit_pat(inner),
PatKind::Mac(mac) => vis.visit_mac(mac),
}
vis.visit_span(span);
}
pub fn noop_visit_anon_const<T: MutVisitor>(AnonConst { id, value }: &mut AnonConst, vis: &mut T) {
vis.visit_id(id);
vis.visit_expr(value);
}
pub fn noop_visit_expr<T: MutVisitor>(Expr { node, id, span, attrs }: &mut Expr, vis: &mut T) {
match node {
ExprKind::Box(expr) => vis.visit_expr(expr),
ExprKind::ObsoleteInPlace(a, b) => {
vis.visit_expr(a);
vis.visit_expr(b);
}
ExprKind::Array(exprs) => visit_exprs(exprs, vis),
ExprKind::Repeat(expr, count) => {
vis.visit_expr(expr);
vis.visit_anon_const(count);
}
ExprKind::Tup(exprs) => visit_exprs(exprs, vis),
ExprKind::Call(f, args) => {
vis.visit_expr(f);
visit_exprs(args, vis);
}
ExprKind::MethodCall(PathSegment { ident, id, args }, exprs) => {
vis.visit_ident(ident);
vis.visit_id(id);
visit_opt(args, |args| vis.visit_generic_args(args));
visit_exprs(exprs, vis);
}
ExprKind::Binary(_binop, lhs, rhs) => {
vis.visit_expr(lhs);
vis.visit_expr(rhs);
}
ExprKind::Unary(_unop, ohs) => vis.visit_expr(ohs),
ExprKind::Lit(_lit) => {}
ExprKind::Cast(expr, ty) => {
vis.visit_expr(expr);
vis.visit_ty(ty);
}
ExprKind::Type(expr, ty) => {
vis.visit_expr(expr);
vis.visit_ty(ty);
}
ExprKind::AddrOf(_m, ohs) => vis.visit_expr(ohs),
ExprKind::If(cond, tr, fl) => {
vis.visit_expr(cond);
vis.visit_block(tr);
visit_opt(fl, |fl| vis.visit_expr(fl));
}
ExprKind::IfLet(pats, expr, tr, fl) => {
visit_vec(pats, |pat| vis.visit_pat(pat));
vis.visit_expr(expr);
vis.visit_block(tr);
visit_opt(fl, |fl| vis.visit_expr(fl));
}
ExprKind::While(cond, body, label) => {
vis.visit_expr(cond);
vis.visit_block(body);
visit_opt(label, |label| vis.visit_label(label));
}
ExprKind::WhileLet(pats, expr, body, label) => {
visit_vec(pats, |pat| vis.visit_pat(pat));
vis.visit_expr(expr);
vis.visit_block(body);
visit_opt(label, |label| vis.visit_label(label));
}
ExprKind::ForLoop(pat, iter, body, label) => {
vis.visit_pat(pat);
vis.visit_expr(iter);
vis.visit_block(body);
visit_opt(label, |label| vis.visit_label(label));
}
ExprKind::Loop(body, label) => {
vis.visit_block(body);
visit_opt(label, |label| vis.visit_label(label));
}
ExprKind::Match(expr, arms) => {
vis.visit_expr(expr);
visit_vec(arms, |arm| vis.visit_arm(arm));
}
ExprKind::Closure(_capture_by, asyncness, _movability, decl, body, span) => {
vis.visit_asyncness(asyncness);
vis.visit_fn_decl(decl);
vis.visit_expr(body);
vis.visit_span(span);
}
ExprKind::Block(blk, label) => {
vis.visit_block(blk);
visit_opt(label, |label| vis.visit_label(label));
}
ExprKind::Async(_capture_by, node_id, body) => {
vis.visit_id(node_id);
vis.visit_block(body);
}
ExprKind::Assign(el, er) => {
vis.visit_expr(el);
vis.visit_expr(er);
}
ExprKind::AssignOp(_op, el, er) => {
vis.visit_expr(el);
vis.visit_expr(er);
}
ExprKind::Field(el, ident) => {
vis.visit_expr(el);
vis.visit_ident(ident);
}
ExprKind::Index(el, er) => {
vis.visit_expr(el);
vis.visit_expr(er);
}
ExprKind::Range(e1, e2, _lim) => {
visit_opt(e1, |e1| vis.visit_expr(e1));
visit_opt(e2, |e2| vis.visit_expr(e2));
}
ExprKind::Path(qself, path) => {
vis.visit_qself(qself);
vis.visit_path(path);
}
ExprKind::Break(label, expr) => {
visit_opt(label, |label| vis.visit_label(label));
visit_opt(expr, |expr| vis.visit_expr(expr));
}
ExprKind::Continue(label) => {
visit_opt(label, |label| vis.visit_label(label));
}
ExprKind::Ret(expr) => {
visit_opt(expr, |expr| vis.visit_expr(expr));
}
ExprKind::InlineAsm(asm) => {
let InlineAsm { asm: _, asm_str_style: _, outputs, inputs, clobbers: _, volatile: _,
alignstack: _, dialect: _, ctxt: _ } = asm.deref_mut();
for out in outputs {
let InlineAsmOutput { constraint: _, expr, is_rw: _, is_indirect: _ } = out;
vis.visit_expr(expr);
}
visit_vec(inputs, |(_c, expr)| vis.visit_expr(expr));
}
ExprKind::Mac(mac) => vis.visit_mac(mac),
ExprKind::Struct(path, fields, expr) => {
vis.visit_path(path);
visit_vec(fields, |field| vis.visit_field(field));
visit_opt(expr, |expr| vis.visit_expr(expr));
},
ExprKind::Paren(expr) => {
vis.visit_expr(expr);
// Nodes that are equal modulo `Paren` sugar no-ops should have the same ids.
*id = expr.id;
vis.visit_span(span);
visit_thin_attrs(attrs, vis);
return;
}
ExprKind::Yield(expr) => {
visit_opt(expr, |expr| vis.visit_expr(expr));
}
ExprKind::Try(expr) => vis.visit_expr(expr),
ExprKind::TryBlock(body) => vis.visit_block(body),
ExprKind::Err => {}
}
vis.visit_id(id);
vis.visit_span(span);
visit_thin_attrs(attrs, vis);
}
pub fn noop_filter_map_expr<T: MutVisitor>(mut e: P<Expr>, vis: &mut T) -> Option<P<Expr>> {
Some({ vis.visit_expr(&mut e); e })
}
pub fn noop_flat_map_stmt<T: MutVisitor>(Stmt { node, mut span, mut id }: Stmt, vis: &mut T)
-> SmallVec<[Stmt; 1]>
{
vis.visit_id(&mut id);
vis.visit_span(&mut span);
noop_flat_map_stmt_kind(node, vis).into_iter().map(|node| {
Stmt { id, node, span }
}).collect()
}
pub fn noop_flat_map_stmt_kind<T: MutVisitor>(node: StmtKind, vis: &mut T)
-> SmallVec<[StmtKind; 1]> {
match node {
StmtKind::Local(mut local) =>
smallvec![StmtKind::Local({ vis.visit_local(&mut local); local })],
StmtKind::Item(item) => vis.flat_map_item(item).into_iter().map(StmtKind::Item).collect(),
StmtKind::Expr(expr) => {
vis.filter_map_expr(expr).into_iter().map(StmtKind::Expr).collect()
}
StmtKind::Semi(expr) => {
vis.filter_map_expr(expr).into_iter().map(StmtKind::Semi).collect()
}
StmtKind::Mac(mut mac) => {
let (mac_, _semi, attrs) = mac.deref_mut();
vis.visit_mac(mac_);
visit_thin_attrs(attrs, vis);
smallvec![StmtKind::Mac(mac)]
}
}
}
pub fn noop_visit_vis<T: MutVisitor>(Spanned { node, span }: &mut Visibility, vis: &mut T) {
match node {
VisibilityKind::Public | VisibilityKind::Crate(_) | VisibilityKind::Inherited => {}
VisibilityKind::Restricted { path, id } => {
vis.visit_path(path);
vis.visit_id(id);
}
}
vis.visit_span(span);
}
#[cfg(test)]
mod tests {
use std::io;
use crate::ast::{self, Ident};
use crate::util::parser_testing::{string_to_crate, matches_codepattern};
use crate::print::pprust;
use crate::mut_visit;
use crate::with_globals;
use super::*;
// this version doesn't care about getting comments or docstrings in.
fn fake_print_crate(s: &mut pprust::State<'_>,
krate: &ast::Crate) -> io::Result<()> {
s.print_mod(&krate.module, &krate.attrs)
}
// change every identifier to "zz"
struct ToZzIdentMutVisitor;
impl MutVisitor for ToZzIdentMutVisitor {
fn visit_ident(&mut self, ident: &mut ast::Ident) {
*ident = Ident::from_str("zz");
}
fn visit_mac(&mut self, mac: &mut ast::Mac) {
mut_visit::noop_visit_mac(mac, self)
}
}
// maybe add to expand.rs...
macro_rules! assert_pred {
($pred:expr, $predname:expr, $a:expr , $b:expr) => (
{
let pred_val = $pred;
let a_val = $a;
let b_val = $b;
if !(pred_val(&a_val, &b_val)) {
panic!("expected args satisfying {}, got {} and {}",
$predname, a_val, b_val);
}
}
)
}
// make sure idents get transformed everywhere
#[test] fn ident_transformation () {
with_globals(|| {
let mut zz_visitor = ToZzIdentMutVisitor;
let mut krate = string_to_crate(
"#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
zz_visitor.visit_crate(&mut krate);
assert_pred!(
matches_codepattern,
"matches_codepattern",
pprust::to_string(|s| fake_print_crate(s, &krate)),
"#[zz]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string());
})
}
// even inside macro defs....
#[test] fn ident_transformation_in_defs () {
with_globals(|| {
let mut zz_visitor = ToZzIdentMutVisitor;
let mut krate = string_to_crate(
"macro_rules! a {(b $c:expr $(d $e:token)f+ => \
(g $(d $d $e)+))} ".to_string());
zz_visitor.visit_crate(&mut krate);
assert_pred!(
matches_codepattern,
"matches_codepattern",
pprust::to_string(|s| fake_print_crate(s, &krate)),
"macro_rules! zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)));".to_string());
})
}
}
| 35.105145 | 99 | 0.595505 |
dd6dc0ddf86f32f2b3882f75a5b11e7ad122c783 | 1,713 | //! Program processor
mod process_create_realm;
mod process_deposit_governing_tokens;
mod process_set_vote_authority;
mod process_withdraw_governing_tokens;
use crate::instruction::GovernanceInstruction;
use borsh::BorshDeserialize;
use process_create_realm::*;
use process_deposit_governing_tokens::*;
use process_set_vote_authority::*;
use process_withdraw_governing_tokens::*;
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, msg, program_error::ProgramError,
pubkey::Pubkey,
};
/// Processes an instruction
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
input: &[u8],
) -> ProgramResult {
let instruction = GovernanceInstruction::try_from_slice(input)
.map_err(|_| ProgramError::InvalidInstructionData)?;
msg!("Instruction: {:?}", instruction);
match instruction {
GovernanceInstruction::CreateRealm { name } => {
process_create_realm(program_id, accounts, name)
}
GovernanceInstruction::DepositGoverningTokens {} => {
process_deposit_governing_tokens(program_id, accounts)
}
GovernanceInstruction::WithdrawGoverningTokens {} => {
process_withdraw_governing_tokens(program_id, accounts)
}
GovernanceInstruction::SetVoteAuthority {
realm,
governing_token_mint,
governing_token_owner,
new_vote_authority,
} => process_set_vote_authority(
accounts,
&realm,
&governing_token_mint,
&governing_token_owner,
&new_vote_authority,
),
_ => todo!("Instruction not implemented yet"),
}
}
| 28.55 | 91 | 0.680093 |
1d0489d20736429abf53f86ee7fb71b1f7347b82 | 6,707 | use super::{Context, Module, RootModuleConfig};
use crate::configs::perl::PerlConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current perl version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("perl");
let config: PerlConfig = PerlConfig::try_load(module.config);
let is_perl_project = context
.try_begin_scan()?
.set_extensions(&config.detect_extensions)
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.is_match();
if !is_perl_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|var, _| match var {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let perl_version = context
.exec_cmd("perl", &["-e", "printf q#%vd#,$^V;"])?
.stdout;
VersionFormatter::format_module_version(
module.get_name(),
&perl_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `perl`:\n{}", error);
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_perl_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_makefile_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Makefile.PL"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_buildfile_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Build.PL"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_cpanfile_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("cpanfile"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_cpanfile_snapshot_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("cpanfile.snapshot"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_meta_json_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("META.json"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_meta_yml_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("META.yml"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_perl_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".perl-version"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_perl_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.pl"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_perl_module_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.pm"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_perldoc_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.pod"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
}
| 29.416667 | 76 | 0.513344 |
50720f516e723a6b7718d1d0ecb8db50b115c731 | 15,590 | #[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};
use core::{fmt, marker::PhantomData};
use serde::{de, ser, Deserialize, Serialize};
use serde_json::Value;
use crate::v1::Id;
/// Represents JSON-RPC 1.0 request parameters.
pub type Params = Vec<Value>;
/// Represents JSON-RPC 1.0 request which is a method call.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MethodCall {
/// A String containing the name of the method to be invoked.
///
/// Method names that begin with the word rpc followed by a period character (U+002E or ASCII 46)
/// are reserved for rpc-internal methods and extensions and MUST NOT be used for anything else.
pub method: String,
/// A Structured value that holds the parameter values to be used
/// during the invocation of the method. This member MAY be omitted.
pub params: Params,
/// An identifier established by the Client.
/// If it is not included it is assumed to be a notification.
pub id: Id,
}
impl fmt::Display for MethodCall {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let json = serde_json::to_string(self).expect("`MethodCall` is serializable");
write!(f, "{}", json)
}
}
impl MethodCall {
/// Creates a JSON-RPC 1.0 request which is a method call.
pub fn new<M: Into<String>>(method: M, params: Params, id: Id) -> Self {
Self {
method: method.into(),
params,
id,
}
}
}
/// Represents JSON-RPC 1.0 request which is a notification.
///
/// A Request object that is a Notification signifies the Client's lack of interest in the
/// corresponding Response object, and as such no Response object needs to be returned to the client.
/// As such, the Client would not be aware of any errors (like e.g. "Invalid params","Internal error").
///
/// The Server MUST NOT reply to a Notification, including those that are within a batch request.
///
/// For JSON-RPC 1.0 specification, notification id **MUST** be Null.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Notification {
/// A String containing the name of the method to be invoked.
///
/// Method names that begin with the word rpc followed by a period character (U+002E or ASCII 46)
/// are reserved for rpc-internal methods and extensions and MUST NOT be used for anything else.
pub method: String,
/// A Structured value that holds the parameter values to be used
/// during the invocation of the method.
pub params: Params,
}
impl fmt::Display for Notification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let json = serde_json::to_string(self).expect("`Notification` is serializable");
write!(f, "{}", json)
}
}
impl ser::Serialize for Notification {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
let mut state = ser::Serializer::serialize_struct(serializer, "Notification", 3)?;
ser::SerializeStruct::serialize_field(&mut state, "method", &self.method)?;
ser::SerializeStruct::serialize_field(&mut state, "params", &self.params)?;
ser::SerializeStruct::serialize_field(&mut state, "id", &Option::<Id>::None)?;
ser::SerializeStruct::end(state)
}
}
impl<'de> de::Deserialize<'de> for Notification {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
use self::request_field::{Field, FIELDS};
struct Visitor<'de> {
marker: PhantomData<Notification>,
lifetime: PhantomData<&'de ()>,
}
impl<'de> de::Visitor<'de> for Visitor<'de> {
type Value = Notification;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("struct Notification")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: de::MapAccess<'de>,
{
let mut method = Option::<String>::None;
let mut params = Option::<Params>::None;
let mut id = Option::<Option<Id>>::None;
while let Some(key) = de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Method => {
if method.is_some() {
return Err(de::Error::duplicate_field("method"));
}
method = Some(de::MapAccess::next_value::<String>(&mut map)?)
}
Field::Params => {
if params.is_some() {
return Err(de::Error::duplicate_field("params"));
}
params = Some(de::MapAccess::next_value::<Params>(&mut map)?)
}
Field::Id => {
if id.is_some() {
return Err(de::Error::duplicate_field("id"));
}
id = Some(de::MapAccess::next_value::<Option<Id>>(&mut map)?)
}
}
}
let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
let params = params.ok_or_else(|| de::Error::missing_field("params"))?;
let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
if id.is_some() {
return Err(de::Error::custom("JSON-RPC 1.0 notification id MUST be Null"));
}
Ok(Notification { method, params })
}
}
de::Deserializer::deserialize_struct(
deserializer,
"Notification",
FIELDS,
Visitor {
marker: PhantomData::<Notification>,
lifetime: PhantomData,
},
)
}
}
impl Notification {
/// Creates a JSON-RPC 1.0 request which is a notification.
pub fn new<M: Into<String>>(method: M, params: Params) -> Self {
Self {
method: method.into(),
params,
}
}
}
/// Represents single JSON-RPC 1.0 call.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum Call {
/// Call method
MethodCall(MethodCall),
/// Fire notification
Notification(Notification),
}
impl fmt::Display for Call {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let json = serde_json::to_string(self).expect("`Call` is serializable");
write!(f, "{}", json)
}
}
impl Call {
/// Returns the method of the request call.
pub fn method(&self) -> &str {
match self {
Self::MethodCall(call) => &call.method,
Self::Notification(notification) => ¬ification.method,
}
}
/// Returns the params of the request call.
pub fn params(&self) -> &Params {
match self {
Self::MethodCall(call) => &call.params,
Self::Notification(notification) => ¬ification.params,
}
}
/// Returns the id of the request call.
pub fn id(&self) -> Option<Id> {
match self {
Self::MethodCall(call) => Some(call.id.clone()),
Self::Notification(_notification) => None,
}
}
}
impl From<MethodCall> for Call {
fn from(call: MethodCall) -> Self {
Self::MethodCall(call)
}
}
impl From<Notification> for Call {
fn from(notify: Notification) -> Self {
Self::Notification(notify)
}
}
/// JSON-RPC 2.0 Request object.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum Request {
/// Single call
Single(Call),
/// Batch of calls
Batch(Vec<Call>),
}
impl fmt::Display for Request {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let json = serde_json::to_string(self).expect("`Request` is serializable");
write!(f, "{}", json)
}
}
/// JSON-RPC 1.0 Request object (only for method call).
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum MethodCallRequest {
/// Single method call
Single(MethodCall),
/// Batch of method calls
Batch(Vec<MethodCall>),
}
impl From<MethodCall> for MethodCallRequest {
fn from(call: MethodCall) -> Self {
Self::Single(call)
}
}
impl From<Vec<MethodCall>> for MethodCallRequest {
fn from(calls: Vec<MethodCall>) -> Self {
Self::Batch(calls)
}
}
impl fmt::Display for MethodCallRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let json = serde_json::to_string(self).expect("`MethodCallRequest` is serializable");
write!(f, "{}", json)
}
}
mod request_field {
use super::*;
pub const FIELDS: &[&str] = &["method", "params", "id"];
pub enum Field {
Method,
Params,
Id,
}
impl<'de> de::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
de::Deserializer::deserialize_identifier(deserializer, FieldVisitor)
}
}
struct FieldVisitor;
impl<'de> de::Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
match v {
"method" => Ok(Field::Method),
"params" => Ok(Field::Params),
"id" => Ok(Field::Id),
_ => Err(de::Error::unknown_field(v, &FIELDS)),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn method_call_cases() -> Vec<(MethodCall, &'static str)> {
vec![
(
// JSON-RPC 1.0 request method call
MethodCall {
method: "foo".to_string(),
params: vec![Value::from(1), Value::Bool(true)],
id: Id::Num(1),
},
r#"{"method":"foo","params":[1,true],"id":1}"#,
),
(
// JSON-RPC 1.0 request method call without parameters
MethodCall {
method: "foo".to_string(),
params: vec![],
id: Id::Num(1),
},
r#"{"method":"foo","params":[],"id":1}"#,
),
]
}
fn notification_cases() -> Vec<(Notification, &'static str)> {
vec![
(
// JSON-RPC 1.0 request notification
Notification {
method: "foo".to_string(),
params: vec![Value::from(1), Value::Bool(true)],
},
r#"{"method":"foo","params":[1,true],"id":null}"#,
),
(
// JSON-RPC 1.0 request notification without parameters
Notification {
method: "foo".to_string(),
params: vec![],
},
r#"{"method":"foo","params":[],"id":null}"#,
),
]
}
#[test]
fn method_call_serialization() {
for (method_call, expect) in method_call_cases() {
let ser = serde_json::to_string(&method_call).unwrap();
assert_eq!(ser, expect);
let de = serde_json::from_str::<MethodCall>(expect).unwrap();
assert_eq!(de, method_call);
}
}
#[test]
fn notification_serialization() {
for (notification, expect) in notification_cases() {
let ser = serde_json::to_string(¬ification).unwrap();
assert_eq!(ser, expect);
let de = serde_json::from_str::<Notification>(expect).unwrap();
assert_eq!(de, notification);
}
}
#[test]
fn call_serialization() {
for (method_call, expect) in method_call_cases() {
let call = Call::MethodCall(method_call);
assert_eq!(serde_json::to_string(&call).unwrap(), expect);
assert_eq!(serde_json::from_str::<Call>(expect).unwrap(), call);
}
for (notification, expect) in notification_cases() {
let call = Call::Notification(notification);
assert_eq!(serde_json::to_string(&call).unwrap(), expect);
assert_eq!(serde_json::from_str::<Call>(expect).unwrap(), call);
}
}
#[test]
fn request_serialization() {
for (method_call, expect) in method_call_cases() {
let call_request = Request::Single(Call::MethodCall(method_call));
assert_eq!(serde_json::to_string(&call_request).unwrap(), expect);
assert_eq!(serde_json::from_str::<Request>(expect).unwrap(), call_request);
}
for (notification, expect) in notification_cases() {
let notification_request = Request::Single(Call::Notification(notification));
assert_eq!(serde_json::to_string(¬ification_request).unwrap(), expect);
assert_eq!(serde_json::from_str::<Request>(expect).unwrap(), notification_request);
}
let batch_request = Request::Batch(vec![
Call::MethodCall(MethodCall {
method: "foo".into(),
params: vec![],
id: Id::Num(1),
}),
Call::MethodCall(MethodCall {
method: "bar".into(),
params: vec![],
id: Id::Num(2),
}),
]);
let batch_expect = r#"[{"method":"foo","params":[],"id":1},{"method":"bar","params":[],"id":2}]"#;
assert_eq!(serde_json::to_string(&batch_request).unwrap(), batch_expect);
assert_eq!(serde_json::from_str::<Request>(&batch_expect).unwrap(), batch_request);
}
#[test]
fn invalid_request() {
let cases = vec![
// JSON-RPC 1.0 invalid request
r#"{"method":"foo","params":[1,true],"id":1,"unknown":[]}"#,
r#"{"method":"foo","params":[1,true],"id":1.2}"#,
r#"{"method":"foo","params":[1,true],"id":null,"unknown":[]}"#,
r#"{"method":"foo","params":[1,true],"unknown":[]}"#,
r#"{"method":"foo","params":[1,true]}"#,
r#"{"method":"foo","unknown":[]}"#,
r#"{"method":1,"unknown":[]}"#,
r#"{"unknown":[]}"#,
];
for case in cases {
let request = serde_json::from_str::<Request>(case);
assert!(request.is_err());
}
}
#[test]
fn valid_request() {
let cases = vec![
// JSON-RPC 1.0 valid request
r#"{"method":"foo","params":[1,true],"id":1}"#,
r#"{"method":"foo","params":[],"id":1}"#,
r#"{"method":"foo","params":[1,true],"id":null}"#,
r#"{"method":"foo","params":[],"id":null}"#,
];
for case in cases {
let request = serde_json::from_str::<Request>(case);
assert!(request.is_ok());
}
}
}
| 33.454936 | 106 | 0.535087 |
33f8db98b48fad250b057ad2a1f27740e13f52e7 | 2,526 | //! `tor-linkspec`: Descriptions of Tor relays, as used to connect to them.
//!
//! # Overview
//!
//! The `tor-linkspec` crate provides traits and data structures that
//! describe how to connect to Tor relays.
//!
//! When describing the location of a Tor relay on the network, the
//! Tor protocol uses a set of "link specifiers", each of which
//! corresponds to a single aspect of the relay's location or
//! identity—such as its IP address and port, its Ed25519 identity
//! key, its (legacy) RSA identity fingerprint, or so on. This
//! crate's [`LinkSpec`] type encodes these structures.
//!
//! When a client is building a circuit through the Tor network, it
//! needs to know certain information about the relays in that
//! circuit. This crate's [`ChanTarget`] and [`CircTarget`] traits
//! represent objects that describe a relay on the network that a
//! client can use as the first hop, or as any hop, in a circuit.
//!
//! This crate is part of
//! [Arti](https://gitlab.torproject.org/tpo/core/arti/), a project to
//! implement [Tor](https://www.torproject.org/) in Rust. Several
//! other crates in Arti depend on it. You will probably not need
//! this crate yourselve unless you are ineracting with the Tor
//! protocol at a fairly low level.
//!
//! `tor-linkspec` is a separate crate so that it can be used by other
//! crates that expose link specifiers and by crates that consume
//! them.
//!
//! ## Future work
//!
//! TODO: Possibly we should rename this crate. "Linkspec" is a
//! pretty esoteric term in the Tor protocols.
//!
//! TODO: Possibly the link specifiers and the `*Target` traitts belogn in different crates.
#![deny(missing_docs)]
#![warn(noop_method_call)]
#![deny(unreachable_pub)]
#![deny(clippy::await_holding_lock)]
#![deny(clippy::cargo_common_metadata)]
#![warn(clippy::clone_on_ref_ptr)]
#![warn(clippy::cognitive_complexity)]
#![deny(clippy::debug_assert_with_mut_call)]
#![deny(clippy::exhaustive_enums)]
#![deny(clippy::exhaustive_structs)]
#![deny(clippy::expl_impl_clone_on_copy)]
#![deny(clippy::fallible_impl_from)]
#![deny(clippy::large_stack_arrays)]
#![warn(clippy::manual_ok_or)]
#![deny(clippy::missing_docs_in_private_items)]
#![warn(clippy::option_option)]
#![warn(clippy::rc_buffer)]
#![deny(clippy::ref_option_ref)]
#![warn(clippy::trait_duplication_in_bounds)]
#![warn(clippy::unseparated_literal_suffix)]
mod ls;
mod owned;
mod traits;
pub use ls::LinkSpec;
pub use owned::{OwnedChanTarget, OwnedCircTarget};
pub use traits::{ChanTarget, CircTarget};
| 37.701493 | 92 | 0.726049 |
145ba784f7c66955e5a3a8ee068c9e188388bd8a | 333 | #![feature(type_alias_impl_trait)]
#![deny(improper_ctypes)]
pub trait Baz {}
impl Baz for u32 {}
type Qux = impl Baz;
pub trait Foo {
type Assoc;
}
impl Foo for u32 {
type Assoc = Qux;
}
fn assign() -> Qux {
1
}
extern "C" {
pub fn lint_me() -> <u32 as Foo>::Assoc; //~ ERROR: uses type `Qux`
}
fn main() {}
| 12.333333 | 71 | 0.588589 |
ffa2ce4151aee54f519bdaddae8f2e9f6cf7a518 | 18,900 | use na::{RealField, Unit};
use crate::math::{Point, Real, Vector};
use crate::query::{self, ClosestPoints, NonlinearRigidMotion, QueryDispatcher, TOIStatus, TOI};
use crate::shape::{Shape, SupportMap};
use crate::utils::WCross;
use crate::query::gjk::ConstantPoint;
use num::Bounded;
/// Enum specifying the behavior of TOI computation when there is a penetration at the starting time.
#[derive(Copy, Clone, Debug)]
pub enum NonlinearTOIMode {
/// Stop TOI computation as soon as there is a penetration.
StopAtPenetration,
/// When there is a penetration, don't stop the TOI search if the relative velocity
/// at the penetration points is negative (i.e. if the points are separating).
DirectionalTOI {
/// The sum of the `Shape::ccd_thickness` of both shapes involved in the TOI computation.
sum_linear_thickness: Real,
/// The max of the `Shape::ccd_angular_thickness` of both shapes involved in the TOI computation.
max_angular_thickness: Real,
},
}
impl NonlinearTOIMode {
/// Initializes a directional TOI mode.
///
/// With the "directional" TOI mode, the nonlinear TOI computation won't
/// immediately stop if the shapes are already intersecting at `t = 0`.
/// Instead, it will search for the first time where a contact between
/// the shapes would result in a deeper penetration (with risk of tunnelling).
/// This effectively checks the relative velocity of the shapes at their point
/// of impact.
pub fn directional_toi<S1, S2>(shape1: &S1, shape2: &S2) -> Self
where
S1: ?Sized + Shape,
S2: ?Sized + Shape,
{
let sum_linear_thickness = shape1.ccd_thickness() + shape2.ccd_thickness();
let max_angular_thickness = shape1
.ccd_angular_thickness()
.max(shape2.ccd_angular_thickness());
NonlinearTOIMode::DirectionalTOI {
sum_linear_thickness,
max_angular_thickness,
}
}
}
/// Compute the time of first impact between two support-map shapes following
/// a nonlinear (with translations and rotations) motion.
pub fn nonlinear_time_of_impact_support_map_support_map<D, SM1, SM2>(
dispatcher: &D,
motion1: &NonlinearRigidMotion,
sm1: &SM1,
g1: &dyn Shape,
motion2: &NonlinearRigidMotion,
sm2: &SM2,
g2: &dyn Shape,
start_time: Real,
end_time: Real,
mode: NonlinearTOIMode,
) -> Option<TOI>
where
D: ?Sized + QueryDispatcher,
SM1: ?Sized + SupportMap,
SM2: ?Sized + SupportMap,
{
let sphere1 = g1.compute_local_bounding_sphere();
let sphere2 = g2.compute_local_bounding_sphere();
// Use the shape with the largest radius as the first shape.
// This will give better convergence because everything will
// be expressed in the local-space as that first shape (including
// the separating axes used in the bisection).
if sphere1.radius >= sphere2.radius {
compute_toi(
dispatcher, motion1, sm1, g1, motion2, sm2, g2, start_time, end_time, mode,
)
} else {
compute_toi(
dispatcher, motion2, sm2, g2, motion1, sm1, g1, start_time, end_time, mode,
)
.map(|toi| toi.swapped())
}
}
/// Time of impacts between two support-mapped shapes under a rigid motion.
pub fn compute_toi<D, SM1, SM2>(
dispatcher: &D,
motion1: &NonlinearRigidMotion,
sm1: &SM1,
g1: &dyn Shape,
motion2: &NonlinearRigidMotion,
sm2: &SM2,
g2: &dyn Shape,
start_time: Real,
end_time: Real,
mode: NonlinearTOIMode,
) -> Option<TOI>
where
D: ?Sized + QueryDispatcher,
SM1: ?Sized + SupportMap,
SM2: ?Sized + SupportMap,
{
let mut prev_min_t = start_time;
let abs_tol: Real = query::gjk::eps_tol();
let mut result = TOI {
toi: start_time,
normal1: Vector::<Real>::x_axis(),
normal2: Vector::<Real>::x_axis(),
witness1: Point::<Real>::origin(),
witness2: Point::<Real>::origin(),
status: TOIStatus::Penetrating,
};
loop {
let pos1 = motion1.position_at_time(result.toi);
let pos2 = motion2.position_at_time(result.toi);
let pos12 = pos1.inv_mul(&pos2);
// TODO: use the _with_params version of the closest points query.
match dispatcher
.closest_points(&pos12, g1, g2, Real::max_value())
.ok()?
{
ClosestPoints::Intersecting => {
// println!(">> Intersecting.");
if result.toi == start_time {
result.status = TOIStatus::Penetrating
} else {
result.status = TOIStatus::Failed;
}
break;
}
ClosestPoints::WithinMargin(p1, p2) => {
// println!(">> Within margin.");
result.witness1 = p1;
result.witness2 = p2;
if let Some((normal1, dist)) =
Unit::try_new_and_get(pos12 * p2 - p1, crate::math::DEFAULT_EPSILON)
{
// FIXME: do the "inverse transform unit vector" only when we are about to return.
result.normal1 = normal1;
result.normal2 = pos12.inverse_transform_unit_vector(&-normal1);
let curr_range = BisectionRange {
min_t: result.toi,
max_t: end_time,
curr_t: result.toi,
};
let (new_range, niter) =
bisect(dist, motion1, sm1, motion2, sm2, &normal1, curr_range);
// println!(
// "Bisection result: {:?}, normal1: {:?}, normal2: {:?}",
// new_range, result.normal1, result.normal2
// );
result.toi = new_range.curr_t;
if new_range.min_t - prev_min_t < abs_tol {
if new_range.max_t == end_time {
// Check the configuration at max_t to see if the object are not disjoint.
// NOTE: could we do this earlier, before the above loop?
// It feels like this could prevent catching some corner-cases like
// if one object is rotated by almost 180 degrees while the other is immobile.
let pos1 = motion1.position_at_time(new_range.max_t);
let pos2 = motion2.position_at_time(new_range.max_t);
let pos12 = pos1.inv_mul(&pos2);
let pt1 = sm1.local_support_point_toward(&normal1);
let pt2 = sm2.support_point_toward(&pos12, &-normal1);
if (pt2 - pt1).dot(&normal1) > 0.0 {
// We found an axis that separate both objects at the end configuration.
return None;
}
}
result.status = TOIStatus::Converged;
break;
}
prev_min_t = new_range.min_t;
if niter == 0 {
result.status = TOIStatus::Converged;
break;
}
} else {
result.status = TOIStatus::Failed;
break;
}
}
ClosestPoints::Disjoint => unreachable!(),
}
}
// In we started with a penetration, we need to compute a full contact manifold and
// see if any of these contact points may result in tunnelling. If the is one, return
// that TOI instead. That way, object moving tangentially on a surface (always keeping
// a contact with it) won't report an useless impact.
//
// Note that this must be done here instead of outside of the `nonlinear_time_of_impact`
// function so that this works properly with composite shapes.
match mode {
NonlinearTOIMode::DirectionalTOI {
sum_linear_thickness,
max_angular_thickness,
} => {
if (result.toi - start_time).abs() < 1.0e-5 {
handle_penetration_at_start_time(
dispatcher,
motion1,
sm1,
g1,
motion2,
sm2,
g2,
start_time,
end_time,
sum_linear_thickness,
max_angular_thickness,
)
} else {
Some(result)
}
}
NonlinearTOIMode::StopAtPenetration => Some(result),
}
}
fn handle_penetration_at_start_time<D, SM1, SM2>(
dispatcher: &D,
motion1: &NonlinearRigidMotion,
sm1: &SM1,
g1: &dyn Shape,
motion2: &NonlinearRigidMotion,
sm2: &SM2,
g2: &dyn Shape,
start_time: Real,
end_time: Real,
sum_linear_thickness: Real,
max_angular_thickness: Real,
) -> Option<TOI>
where
D: ?Sized + QueryDispatcher,
SM1: ?Sized + SupportMap,
SM2: ?Sized + SupportMap,
{
// Because we are doing non-linear CCD, we need an iterative methode here.
// First we need to check if the `toi = start_time` is legitimate, i.e.,
// if tunnelling will happen if we don't clamp the motion.
//
// If the contact isn't "legitimate" (i.e. if we have a separating velocity),
// then we need to check by how much the bodies can move without tunnelling.
// With linear CCD it's easy: any linear movement is OK because we have
// a separating velocity.
//
// With non-linear CCD it's more complicated because we need to take the
// angular velocity into account, which will result in new contact points
// that could tunnel (imagine for example 2D cuboid touching the ground at one
// point. By rotating, its second end point will end up touching the ground too,
// and we need to detect that so we don't permit a rotation larger than what's
// needed for this second contact to happen).
//
// The iterative method here will iteratively check multiple rotation angles to
// find new future contact points after some rotation; and check the relative
// velocity at these future contact points.
#[cfg(feature = "dim2")]
let dangvel = (motion2.angvel - motion1.angvel).abs();
#[cfg(feature = "dim3")]
let dangvel = (motion2.angvel - motion1.angvel).norm();
let inv_dangvel = crate::utils::inv(dangvel);
let linear_increment = sum_linear_thickness;
let angular_increment = Real::pi() - max_angular_thickness;
let linear_time_increment =
linear_increment * crate::utils::inv((motion2.linvel - motion1.linvel).norm());
let angular_time_increment = angular_increment * inv_dangvel;
let mut time_increment = angular_time_increment
.min(linear_time_increment)
// This is needed to avoid some tunnelling. But this is
// kind of "brute force" so we should find something better.
.min((end_time - start_time) / 10.0);
// println!(
// "Lin time incr: {}, ang time incr: {}",
// linear_time_increment, angular_time_increment
// );
if time_increment == 0.0 {
time_increment = end_time;
}
let mut next_time = start_time;
// TODO: looping until we reach π sounds enough for most purposes.
// Is there a practical case where we need to loop until we reach 2π ?
while next_time < end_time {
// dbg!("A");
let pos1_at_next_time = motion1.position_at_time(next_time);
let pos2_at_next_time = motion2.position_at_time(next_time);
let pos12_at_next_time = pos1_at_next_time.inv_mul(&pos2_at_next_time);
let contact = dispatcher
.contact(&pos12_at_next_time, g1, g2, Real::MAX)
.ok()??;
{
// dbg!("C");
// 1. Compute the relative velocity at that contact point.
// 2. Check if this results in a potential tunnelling.
// 3. Use bisection to adjust the TOI to the time where a pair
// of contact points potentially causing tunneling hit for the first time.
let r1 = contact.point1 - motion1.local_center;
let r2 = contact.point2 - motion2.local_center;
let vel1 = motion1.linvel + motion1.angvel.gcross(pos1_at_next_time * r1);
let vel2 = motion2.linvel + motion2.angvel.gcross(pos2_at_next_time * r2);
let vel12 = vel2 - vel1;
let normal_vel = -vel12.dot(&(pos1_at_next_time * contact.normal1));
let ccd_threshold = if contact.dist <= 0.0 {
sum_linear_thickness
} else {
contact.dist + sum_linear_thickness
};
// println!(
// "linvel: {:?}, angvel: {:?}, r2: {:?}, angpart: {:?}, vel2: {:?}",
// motion2.linvel,
// motion2.angvel,
// r2,
// motion2.angvel.gcross(pos2_at_next_time * r2),
// vel2,
// );
//
// println!(
// "Found normal vel: {}, dist: {}, threshold: {}, if_value: {}, time: {}",
// normal_vel,
// contact.dist,
// ccd_threshold,
// normal_vel * (end_time - next_time),
// next_time
// );
if normal_vel * (end_time - next_time) > ccd_threshold {
// dbg!("D1");
let mut result = TOI {
toi: next_time,
witness1: contact.point1,
witness2: contact.point2,
normal1: contact.normal1,
normal2: contact.normal2,
status: TOIStatus::Converged,
};
if contact.dist > 0.0 {
// This is an acceptable impact. Now determine when
// the impacts happens exactly.
let curr_range = BisectionRange {
min_t: next_time,
max_t: end_time,
curr_t: next_time,
};
let (new_range, _) = bisect(
contact.dist,
motion1,
sm1,
motion2,
sm2,
&contact.normal1,
curr_range,
);
// TODO: the bisection isn't always enough here. We should check that we
// still have a contact now. If not, we should run the loop from
// nonlinear_time_of_impact_support_map_support_map again from this
// point forward.
result.toi = new_range.curr_t;
} else {
// dbg!("Bissecting points");
// This is an acceptable impact. Now determine when
// the impacts happens exactly.
let curr_range = BisectionRange {
min_t: start_time,
max_t: next_time,
curr_t: next_time,
};
let (new_range, _) = bisect(
contact.dist,
motion1,
&ConstantPoint(contact.point1),
motion2,
&ConstantPoint(contact.point2),
&contact.normal1,
curr_range,
);
// TODO: the bisection isn't always enough here. We should check that we
// still have a contact now. If not, we should run the loop from
// nonlinear_time_of_impact_support_map_support_map again from this
// point forward.
result.toi = new_range.curr_t;
}
// println!("Fount new toi: {}", result.toi);
return Some(result);
}
// dbg!("D2");
}
// If there is no angular velocity, we don't have to
// continue because we can't rotate the object.
if inv_dangvel == 0.0 {
return None;
}
// dbg!("E");
next_time += time_increment;
}
None
}
#[derive(Copy, Clone, Debug)]
struct BisectionRange {
min_t: Real,
curr_t: Real,
max_t: Real,
}
fn bisect<SM1, SM2>(
mut dist: Real,
motion1: &NonlinearRigidMotion,
sm1: &SM1,
motion2: &NonlinearRigidMotion,
sm2: &SM2,
normal1: &Unit<Vector<Real>>,
mut range: BisectionRange,
) -> (BisectionRange, usize)
where
SM1: ?Sized + SupportMap,
SM2: ?Sized + SupportMap,
{
let abs_tol: Real = query::gjk::eps_tol();
let rel_tol = abs_tol; // ComplexField::sqrt(abs_tol);
let mut niter = 0;
// Use the world-space normal so it doesn't move with the shapes.
// This is necessary to reduce the risk of extracting a root that
// is not the root happening at the smallest time.
let pos1 = motion1.position_at_time(range.curr_t);
let world_normal1 = pos1 * normal1;
loop {
// println!("Bisection dist: {}, range: {:?}", dist, range);
// TODO: use the secant method too for finding the next iterate and converge more quickly.
if dist < 0.0 {
// Too close or penetration, go back in time.
range.max_t = range.curr_t;
range.curr_t = (range.min_t + range.curr_t) * 0.5;
} else if dist > rel_tol {
// Too far apart, go forward in time.
range.min_t = range.curr_t;
range.curr_t = (range.curr_t + range.max_t) * 0.5;
} else {
// Reached tolerance, break.
// println!("Bisection, break on dist tolerance.");
break;
}
if range.max_t - range.min_t < abs_tol {
range.curr_t = range.max_t;
// println!("Bisection, break on tiny range.");
break;
}
let pos1 = motion1.position_at_time(range.curr_t);
let pos2 = motion2.position_at_time(range.curr_t);
let pos12 = pos1.inv_mul(&pos2);
let normal1 = pos1.inverse_transform_unit_vector(&world_normal1);
let pt1 = sm1.local_support_point_toward(&normal1);
let pt2 = sm2.support_point_toward(&pos12, &-normal1);
dist = pt2.coords.dot(&normal1) - pt1.coords.dot(&normal1);
niter += 1;
}
(range, niter)
}
| 38.028169 | 106 | 0.548942 |
756afa1243ca9c8acbe300e8c7b7b3978cff445b | 9,581 | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* An implementation of the SHA-1 cryptographic hash.
*
* First create a `sha1` object using the `sha1` constructor, then
* feed it input using the `input` or `input_str` methods, which may be
* called any number of times.
*
* After the entire input has been fed to the hash read the result using
* the `result` or `result_str` methods.
*
* The `sha1` object may be reused to create multiple hashes by calling
* the `reset` method.
*/
use cryptoutil::{write_u32_be, read_u32v_be, add_bytes_to_bits, FixedBuffer, FixedBuffer64,
StandardPadding};
use digest::Digest;
/*
* A SHA-1 implementation derived from Paul E. Jones's reference
* implementation, which is written for clarity, not speed. At some
* point this will want to be rewritten.
*/
// Some unexported constants
static DIGEST_BUF_LEN: uint = 5u;
static WORK_BUF_LEN: uint = 80u;
static K0: u32 = 0x5A827999u32;
static K1: u32 = 0x6ED9EBA1u32;
static K2: u32 = 0x8F1BBCDCu32;
static K3: u32 = 0xCA62C1D6u32;
/// Structure representing the state of a Sha1 computation
pub struct Sha1 {
h: [u32, ..DIGEST_BUF_LEN],
length_bits: u64,
buffer: FixedBuffer64,
computed: bool,
}
fn add_input(st: &mut Sha1, msg: &[u8]) {
assert!((!st.computed));
// Assumes that msg.len() can be converted to u64 without overflow
st.length_bits = add_bytes_to_bits(st.length_bits, msg.len() as u64);
let st_h = &mut st.h;
st.buffer.input(msg, |d: &[u8]| {process_msg_block(d, &mut *st_h); });
}
fn process_msg_block(data: &[u8], h: &mut [u32, ..DIGEST_BUF_LEN]) {
let mut t: uint; // Loop counter
let mut w = [0u32, ..WORK_BUF_LEN];
// Initialize the first 16 words of the vector w
read_u32v_be(w.slice_mut(0, 16), data);
// Initialize the rest of vector w
t = 16u;
while t < 80 {
let val = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
w[t] = circular_shift(1, val);
t += 1;
}
let mut a = h[0];
let mut b = h[1];
let mut c = h[2];
let mut d = h[3];
let mut e = h[4];
let mut temp: u32;
t = 0;
while t < 20 {
temp = circular_shift(5, a) + (b & c | !b & d) + e + w[t] + K0;
e = d;
d = c;
c = circular_shift(30, b);
b = a;
a = temp;
t += 1;
}
while t < 40 {
temp = circular_shift(5, a) + (b ^ c ^ d) + e + w[t] + K1;
e = d;
d = c;
c = circular_shift(30, b);
b = a;
a = temp;
t += 1;
}
while t < 60 {
temp =
circular_shift(5, a) + (b & c | b & d | c & d) + e + w[t] +
K2;
e = d;
d = c;
c = circular_shift(30, b);
b = a;
a = temp;
t += 1;
}
while t < 80 {
temp = circular_shift(5, a) + (b ^ c ^ d) + e + w[t] + K3;
e = d;
d = c;
c = circular_shift(30, b);
b = a;
a = temp;
t += 1;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
}
fn circular_shift(bits: u32, word: u32) -> u32 {
return word << bits as uint | word >> (32u32 - bits) as uint;
}
fn mk_result(st: &mut Sha1, rs: &mut [u8]) {
if !st.computed {
let st_h = &mut st.h;
st.buffer.standard_padding(8, |d: &[u8]| { process_msg_block(d, &mut *st_h) });
write_u32_be(st.buffer.next(4), (st.length_bits >> 32) as u32 );
write_u32_be(st.buffer.next(4), st.length_bits as u32);
process_msg_block(st.buffer.full_buffer(), st_h);
st.computed = true;
}
write_u32_be(rs.slice_mut(0, 4), st.h[0]);
write_u32_be(rs.slice_mut(4, 8), st.h[1]);
write_u32_be(rs.slice_mut(8, 12), st.h[2]);
write_u32_be(rs.slice_mut(12, 16), st.h[3]);
write_u32_be(rs.slice_mut(16, 20), st.h[4]);
}
impl Sha1 {
/// Construct a `sha` object
pub fn new() -> Sha1 {
let mut st = Sha1 {
h: [0u32, ..DIGEST_BUF_LEN],
length_bits: 0u64,
buffer: FixedBuffer64::new(),
computed: false,
};
st.reset();
return st;
}
}
impl Digest for Sha1 {
fn reset(&mut self) {
self.length_bits = 0;
self.h[0] = 0x67452301u32;
self.h[1] = 0xEFCDAB89u32;
self.h[2] = 0x98BADCFEu32;
self.h[3] = 0x10325476u32;
self.h[4] = 0xC3D2E1F0u32;
self.buffer.reset();
self.computed = false;
}
fn input(&mut self, msg: &[u8]) { add_input(self, msg); }
fn result(&mut self, out: &mut [u8]) { return mk_result(self, out); }
fn output_bits(&self) -> uint { 160 }
fn block_size(&self) -> uint { 64 }
}
#[cfg(test)]
mod tests {
use cryptoutil::test::test_digest_1million_random;
use digest::Digest;
use sha1::Sha1;
#[deriving(Clone)]
struct Test {
input: &'static str,
output: Vec<u8>,
output_str: &'static str,
}
#[test]
fn test() {
let tests = vec![
// Test messages from FIPS 180-1
Test {
input: "abc",
output: vec![
0xA9u8, 0x99u8, 0x3Eu8, 0x36u8,
0x47u8, 0x06u8, 0x81u8, 0x6Au8,
0xBAu8, 0x3Eu8, 0x25u8, 0x71u8,
0x78u8, 0x50u8, 0xC2u8, 0x6Cu8,
0x9Cu8, 0xD0u8, 0xD8u8, 0x9Du8,
],
output_str: "a9993e364706816aba3e25717850c26c9cd0d89d"
},
Test {
input:
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
output: vec![
0x84u8, 0x98u8, 0x3Eu8, 0x44u8,
0x1Cu8, 0x3Bu8, 0xD2u8, 0x6Eu8,
0xBAu8, 0xAEu8, 0x4Au8, 0xA1u8,
0xF9u8, 0x51u8, 0x29u8, 0xE5u8,
0xE5u8, 0x46u8, 0x70u8, 0xF1u8,
],
output_str: "84983e441c3bd26ebaae4aa1f95129e5e54670f1"
},
// Examples from wikipedia
Test {
input: "The quick brown fox jumps over the lazy dog",
output: vec![
0x2fu8, 0xd4u8, 0xe1u8, 0xc6u8,
0x7au8, 0x2du8, 0x28u8, 0xfcu8,
0xedu8, 0x84u8, 0x9eu8, 0xe1u8,
0xbbu8, 0x76u8, 0xe7u8, 0x39u8,
0x1bu8, 0x93u8, 0xebu8, 0x12u8,
],
output_str: "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
},
Test {
input: "The quick brown fox jumps over the lazy cog",
output: vec![
0xdeu8, 0x9fu8, 0x2cu8, 0x7fu8,
0xd2u8, 0x5eu8, 0x1bu8, 0x3au8,
0xfau8, 0xd3u8, 0xe8u8, 0x5au8,
0x0bu8, 0xd1u8, 0x7du8, 0x9bu8,
0x10u8, 0x0du8, 0xb4u8, 0xb3u8,
],
output_str: "de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3",
},
];
// Test that it works when accepting the message all at once
let mut out = [0u8, ..20];
let mut sh = box Sha1::new();
for t in tests.iter() {
(*sh).input_str(t.input);
sh.result(out);
assert!(t.output.as_slice() == out);
let out_str = (*sh).result_str();
assert_eq!(out_str.len(), 40);
assert!(out_str.as_slice() == t.output_str);
sh.reset();
}
// Test that it works when accepting the message in pieces
for t in tests.iter() {
let len = t.input.len();
let mut left = len;
while left > 0u {
let take = (left + 1u) / 2u;
(*sh).input_str(t.input.slice(len - left, take + len - left));
left = left - take;
}
sh.result(out);
assert!(t.output.as_slice() == out);
let out_str = (*sh).result_str();
assert_eq!(out_str.len(), 40);
assert!(out_str.as_slice() == t.output_str);
sh.reset();
}
}
#[test]
fn test_1million_random_sha1() {
let mut sh = Sha1::new();
test_digest_1million_random(
&mut sh,
64,
"34aa973cd4c4daa4f61eeb2bdbad27316534016f");
}
}
#[cfg(test)]
mod bench {
use test::Bencher;
use digest::Digest;
use sha1::Sha1;
#[bench]
pub fn sha1_10(bh: & mut Bencher) {
let mut sh = Sha1::new();
let bytes = [1u8, ..10];
bh.iter( || {
sh.input(bytes);
});
bh.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha1_1k(bh: & mut Bencher) {
let mut sh = Sha1::new();
let bytes = [1u8, ..1024];
bh.iter( || {
sh.input(bytes);
});
bh.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha1_64k(bh: & mut Bencher) {
let mut sh = Sha1::new();
let bytes = [1u8, ..65536];
bh.iter( || {
sh.input(bytes);
});
bh.bytes = bytes.len() as u64;
}
}
| 29.033333 | 91 | 0.518422 |
d7755ae26c9918a96a9a483d4b248427ed32e081 | 14,480 | // Copyright 2015-2018 Benjamin Fry <[email protected]>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! Configuration types for all security options in trust-dns
use std::path::Path;
#[cfg(all(feature = "dns-over-openssl", not(feature = "dns-over-rustls")))]
use openssl::{pkey::PKey, stack::Stack, x509::X509};
#[cfg(feature = "dns-over-rustls")]
use rustls::{Certificate, PrivateKey};
use serde::Deserialize;
use crate::client::error::ParseResult;
use crate::client::rr::dnssec::Algorithm;
#[cfg(any(feature = "dns-over-tls", feature = "dnssec"))]
use crate::client::rr::dnssec::{KeyFormat, KeyPair, Private, Signer};
#[cfg(feature = "dnssec")]
use crate::client::rr::domain::IntoName;
use crate::client::rr::domain::Name;
/// Key pair configuration for DNSSec keys for signing a zone
#[derive(Deserialize, PartialEq, Debug)]
pub struct KeyConfig {
/// file path to the key
pub key_path: String,
/// password to use to read the key
pub password: Option<String>,
/// the type of key stored, see `Algorithm`
pub algorithm: String,
/// the name to use when signing records, e.g. ns.example.com
pub signer_name: Option<String>,
/// specify that this key should be used for signing a zone
pub is_zone_signing_key: Option<bool>,
/// specifies that this key can be used for dynamic updates in the zone
pub is_zone_update_auth: Option<bool>,
}
impl KeyConfig {
/// Return a new KeyConfig
///
/// # Arguments
///
/// * `key_path` - file path to the key
/// * `password` - password to use to read the key
/// * `algorithm` - the type of key stored, see `Algorithm`
/// * `signer_name` - the name to use when signing records, e.g. ns.example.com
/// * `is_zone_signing_key` - specify that this key should be used for signing a zone
/// * `is_zone_update_auth` - specifies that this key can be used for dynamic updates in the zone
pub fn new(
key_path: String,
password: Option<String>,
algorithm: Algorithm,
signer_name: String,
is_zone_signing_key: bool,
is_zone_update_auth: bool,
) -> Self {
KeyConfig {
key_path,
password,
algorithm: algorithm.as_str().to_string(),
signer_name: Some(signer_name),
is_zone_signing_key: Some(is_zone_signing_key),
is_zone_update_auth: Some(is_zone_update_auth),
}
}
/// path to the key file, either relative to the zone file, or a explicit from the root.
pub fn key_path(&self) -> &Path {
Path::new(&self.key_path)
}
/// Converts key into
#[cfg(any(feature = "dns-over-tls", feature = "dnssec"))]
pub fn format(&self) -> ParseResult<KeyFormat> {
use crate::client::error::ParseErrorKind;
let extension = self.key_path().extension().ok_or_else(|| {
ParseErrorKind::Msg(format!(
"file lacks extension, e.g. '.pk8': {:?}",
self.key_path()
))
})?;
match extension.to_str() {
Some("der") => Ok(KeyFormat::Der),
Some("key") => Ok(KeyFormat::Pem), // TODO: deprecate this...
Some("pem") => Ok(KeyFormat::Pem),
Some("pk8") => Ok(KeyFormat::Pkcs8),
e => Err(ParseErrorKind::Msg(format!(
"extension not understood, '{:?}': {:?}",
e,
self.key_path()
))
.into()),
}
}
/// Returns the password used to read the key
pub fn password(&self) -> Option<&str> {
self.password.as_deref()
}
/// algorithm for for the key, see `Algorithm` for supported algorithms.
pub fn algorithm(&self) -> ParseResult<Algorithm> {
match self.algorithm.as_str() {
"RSASHA1" => Ok(Algorithm::RSASHA1),
"RSASHA256" => Ok(Algorithm::RSASHA256),
"RSASHA1-NSEC3-SHA1" => Ok(Algorithm::RSASHA1NSEC3SHA1),
"RSASHA512" => Ok(Algorithm::RSASHA512),
"ECDSAP256SHA256" => Ok(Algorithm::ECDSAP256SHA256),
"ECDSAP384SHA384" => Ok(Algorithm::ECDSAP384SHA384),
"ED25519" => Ok(Algorithm::ED25519),
s => Err(format!("unrecognized string {}", s).into()),
}
}
/// the signer name for the key, this defaults to the $ORIGIN aka zone name.
pub fn signer_name(&self) -> ParseResult<Option<Name>> {
if let Some(signer_name) = self.signer_name.as_ref() {
let name = Name::parse(signer_name, None)?;
return Ok(Some(name));
}
Ok(None)
}
/// specifies that this key should be used to sign the zone
///
/// The public key for this must be trusted by a resolver to work. The key must have a private
/// portion associated with it. It will be registered as a DNSKEY in the zone.
pub fn is_zone_signing_key(&self) -> bool {
self.is_zone_signing_key.unwrap_or(false)
}
/// this is at least a public_key, and can be used for SIG0 dynamic updates.
///
/// it will be registered as a KEY record in the zone.
pub fn is_zone_update_auth(&self) -> bool {
self.is_zone_update_auth.unwrap_or(false)
}
/// Tries to read the defined key into a Signer
#[cfg(feature = "dnssec")]
pub fn try_into_signer<N: IntoName>(&self, signer_name: N) -> Result<Signer, String> {
let signer_name = signer_name
.into_name()
.map_err(|e| format!("error loading signer name: {}", e))?;
let key = load_key(signer_name, self)
.map_err(|e| format!("failed to load key: {:?} msg: {}", self.key_path(), e))?;
key.test_key()
.map_err(|e| format!("key failed test: {}", e))?;
Ok(key)
}
}
/// Certificate format of the file being read
#[derive(Deserialize, PartialEq, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum CertType {
/// Pkcs12 formatted certificates and private key (requires OpenSSL)
Pkcs12,
/// PEM formatted Certificate chain
Pem,
}
impl Default for CertType {
fn default() -> Self {
CertType::Pkcs12
}
}
/// Format of the private key file to read
#[derive(Deserialize, PartialEq, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum PrivateKeyType {
/// PKCS8 formatted key file, allows for a password (requires Rustls)
Pkcs8,
/// DER formatted key, raw and unencrypted
Der,
}
impl Default for PrivateKeyType {
fn default() -> Self {
PrivateKeyType::Der
}
}
/// Configuration for a TLS certificate
#[derive(Deserialize, PartialEq, Debug)]
pub struct TlsCertConfig {
path: String,
endpoint_name: String,
cert_type: Option<CertType>,
password: Option<String>,
private_key: Option<String>,
private_key_type: Option<PrivateKeyType>,
}
impl TlsCertConfig {
/// path to the pkcs12 der formatted certificate file
pub fn get_path(&self) -> &Path {
Path::new(&self.path)
}
/// return the DNS name of the certificate hosted at the TLS endpoint
pub fn get_endpoint_name(&self) -> &str {
&self.endpoint_name
}
/// Returns the format type of the certificate file
pub fn get_cert_type(&self) -> CertType {
self.cert_type.unwrap_or_default()
}
/// optional password for open the pkcs12, none assumes no password
pub fn get_password(&self) -> Option<&str> {
self.password.as_deref()
}
/// returns the path to the private key, as associated with the certificate
pub fn get_private_key(&self) -> Option<&Path> {
self.private_key.as_deref().map(Path::new)
}
/// returns the path to the private key
pub fn get_private_key_type(&self) -> PrivateKeyType {
self.private_key_type.unwrap_or_default()
}
}
/// set of DNSSEC algorithms to use to sign the zone. enable_dnssec must be true.
/// these will be lookedup by $file.{key_name}.pem, for backward compatibility
/// with previous versions of Trust-DNS, if enable_dnssec is enabled but
/// supported_algorithms is not specified, it will default to "RSASHA256" and
/// look for the $file.pem for the key. To control key length, or other options
/// keys of the specified formats can be generated in PEM format. Instructions
/// for custom keys can be found elsewhere.
///
/// the currently supported set of supported_algorithms are
/// ["RSASHA256", "RSASHA512", "ECDSAP256SHA256", "ECDSAP384SHA384", "ED25519"]
///
/// keys are listed in pairs of key_name and algorithm, the search path is the
/// same directory has the zone $file:
/// keys = [ "my_rsa_2048|RSASHA256", "/path/to/my_ed25519|ED25519" ]
#[cfg(feature = "dnssec")]
fn load_key(zone_name: Name, key_config: &KeyConfig) -> Result<Signer, String> {
use log::info;
use chrono::Duration;
use std::fs::File;
use std::io::Read;
let key_path = key_config.key_path();
let algorithm = key_config
.algorithm()
.map_err(|e| format!("bad algorithm: {}", e))?;
let format = key_config
.format()
.map_err(|e| format!("bad key format: {}", e))?;
// read the key in
let key: KeyPair<Private> = {
info!("reading key: {:?}", key_path);
let mut file = File::open(&key_path)
.map_err(|e| format!("error opening private key file: {:?}: {}", key_path, e))?;
let mut key_bytes = Vec::with_capacity(256);
file.read_to_end(&mut key_bytes)
.map_err(|e| format!("could not read key from: {:?}: {}", key_path, e))?;
format
.decode_key(&key_bytes, key_config.password(), algorithm)
.map_err(|e| format!("could not decode key: {}", e))?
};
let name = key_config
.signer_name()
.map_err(|e| format!("error reading name: {}", e))?
.unwrap_or(zone_name);
// add the key to the zone
// TODO: allow the duration of signatures to be customized
let dnskey = key
.to_dnskey(algorithm)
.map_err(|e| format!("error converting to dnskey: {}", e))?;
Ok(Signer::dnssec(dnskey, key, name, Duration::weeks(52)))
}
/// Load a Certificate from the path (with openssl)
#[cfg(all(feature = "dns-over-openssl", not(feature = "dns-over-rustls")))]
pub fn load_cert(
zone_dir: &Path,
tls_cert_config: &TlsCertConfig,
) -> Result<((X509, Option<Stack<X509>>), PKey<Private>), String> {
use log::{info, warn};
use trust_dns_openssl::tls_server::{
read_cert_pem, read_cert_pkcs12, read_key_from_der, read_key_from_pkcs8,
};
let path = zone_dir.to_owned().join(tls_cert_config.get_path());
let cert_type = tls_cert_config.get_cert_type();
let password = tls_cert_config.get_password();
let private_key_path = tls_cert_config
.get_private_key()
.map(|p| zone_dir.to_owned().join(p));
let private_key_type = tls_cert_config.get_private_key_type();
// if it's pkcs12, we'll be collecting the key and certs from that, otherwise continue processing
let (cert, cert_chain) = match cert_type {
CertType::Pem => {
info!("loading TLS PEM certificate from: {:?}", path);
read_cert_pem(&path)?
}
CertType::Pkcs12 => {
if private_key_path.is_some() {
warn!(
"ignoring specified key, using the one in the PKCS12 file: {}",
path.display()
);
}
info!("loading TLS PKCS12 certificate from: {:?}", path);
return read_cert_pkcs12(&path, password).map_err(Into::into);
}
};
// it wasn't plcs12, we need to load the key separately
let key = match (private_key_path, private_key_type) {
(Some(private_key_path), PrivateKeyType::Pkcs8) => {
info!("loading TLS PKCS8 key from: {}", private_key_path.display());
read_key_from_pkcs8(&private_key_path, password)?
}
(Some(private_key_path), PrivateKeyType::Der) => {
info!("loading TLS DER key from: {}", private_key_path.display());
read_key_from_der(&private_key_path)?
}
(None, _) => {
return Err(format!(
"No private key associated with specified certificate"
));
}
};
Ok(((cert, cert_chain), key))
}
/// Load a Certificate from the path (with rustls)
#[cfg(feature = "dns-over-rustls")]
pub fn load_cert(
zone_dir: &Path,
tls_cert_config: &TlsCertConfig,
) -> Result<(Vec<Certificate>, PrivateKey), String> {
use log::{info, warn};
use trust_dns_rustls::tls_server::{read_cert, read_key_from_der, read_key_from_pkcs8};
let path = zone_dir.to_owned().join(tls_cert_config.get_path());
let cert_type = tls_cert_config.get_cert_type();
let password = tls_cert_config.get_password();
let private_key_path = tls_cert_config
.get_private_key()
.map(|p| zone_dir.to_owned().join(p));
let private_key_type = tls_cert_config.get_private_key_type();
let cert = match cert_type {
CertType::Pem => {
info!("loading TLS PEM certificate chain from: {}", path.display());
read_cert(&path).map_err(|e| format!("error reading cert: {}", e))?
}
CertType::Pkcs12 => {
return Err(
"PKCS12 is not supported with Rustls for certificate, use PEM encoding".to_string(),
);
}
};
let key = match (private_key_path, private_key_type) {
(Some(private_key_path), PrivateKeyType::Pkcs8) => {
info!("loading TLS PKCS8 key from: {}", private_key_path.display());
if password.is_some() {
warn!("Password for key supplied, but Rustls does not support encrypted PKCS8");
}
read_key_from_pkcs8(&private_key_path)?
}
(Some(private_key_path), PrivateKeyType::Der) => {
info!("loading TLS DER key from: {}", private_key_path.display());
read_key_from_der(&private_key_path)?
}
(None, _) => return Err("No private key associated with specified certificate".to_string()),
};
Ok((cert, key))
}
| 35.930521 | 101 | 0.620097 |
394817a5d7656bc47a1bb27b3bb05506b70ef1d9 | 4,353 | use serde::{Deserialize, Serialize};
/// CKB capacity.
///
/// It is encoded as the amount of `Shannons` internally.
#[derive(
Debug, Clone, Copy, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
)]
pub struct Capacity(u64);
/// Represents the ratio `numerator / denominator`, where `numerator` and `denominator` are both
/// unsigned 64-bit integers.
#[derive(Clone, PartialEq, Debug, Eq, Copy, Deserialize, Serialize)]
pub struct Ratio {
/// Numerator.
numer: u64,
/// Denominator.
denom: u64,
}
impl Ratio {
/// Creates a ratio numer / denom.
pub const fn new(numer: u64, denom: u64) -> Self {
Self { numer, denom }
}
/// The numerator in ratio numerator / denominator.
pub fn numer(&self) -> u64 {
self.numer
}
/// The denominator in ratio numerator / denominator.
pub fn denom(&self) -> u64 {
self.denom
}
}
/// Conversion into `Capacity`.
pub trait AsCapacity {
/// Converts `self` into `Capacity`.
fn as_capacity(self) -> Capacity;
}
impl AsCapacity for Capacity {
fn as_capacity(self) -> Capacity {
self
}
}
impl AsCapacity for u64 {
fn as_capacity(self) -> Capacity {
Capacity::shannons(self)
}
}
impl AsCapacity for u32 {
fn as_capacity(self) -> Capacity {
Capacity::shannons(u64::from(self))
}
}
impl AsCapacity for u16 {
fn as_capacity(self) -> Capacity {
Capacity::shannons(u64::from(self))
}
}
impl AsCapacity for u8 {
fn as_capacity(self) -> Capacity {
Capacity::shannons(u64::from(self))
}
}
// A `Byte` contains how many `Shannons`.
const BYTE_SHANNONS: u64 = 100_000_000;
/// Numeric errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
/// Numeric overflow.
Overflow,
}
impl ::std::fmt::Display for Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "OccupiedCapacity: overflow")
}
}
impl ::std::error::Error for Error {}
/// Numeric operation result.
pub type Result<T> = ::std::result::Result<T, Error>;
impl Capacity {
/// Capacity of zero Shannons.
pub const fn zero() -> Self {
Capacity(0)
}
/// Capacity of one Shannon.
pub const fn one() -> Self {
Capacity(1)
}
/// Views the capacity as Shannons.
pub const fn shannons(val: u64) -> Self {
Capacity(val)
}
/// Views the capacity as CKBytes.
pub fn bytes(val: usize) -> Result<Self> {
(val as u64)
.checked_mul(BYTE_SHANNONS)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
/// Views the capacity as Shannons.
pub fn as_u64(self) -> u64 {
self.0
}
/// Adds self and rhs and checks overflow error.
pub fn safe_add<C: AsCapacity>(self, rhs: C) -> Result<Self> {
self.0
.checked_add(rhs.as_capacity().0)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
/// Subtracts self and rhs and checks overflow error.
pub fn safe_sub<C: AsCapacity>(self, rhs: C) -> Result<Self> {
self.0
.checked_sub(rhs.as_capacity().0)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
/// Multiplies self and rhs and checks overflow error.
pub fn safe_mul<C: AsCapacity>(self, rhs: C) -> Result<Self> {
self.0
.checked_mul(rhs.as_capacity().0)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
/// Multiplies self with a ratio and checks overflow error.
pub fn safe_mul_ratio(self, ratio: Ratio) -> Result<Self> {
self.0
.checked_mul(ratio.numer())
.and_then(|ret| ret.checked_div(ratio.denom()))
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
}
impl ::std::str::FromStr for Capacity {
type Err = ::std::num::ParseIntError;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
Ok(Capacity(s.parse::<u64>()?))
}
}
impl ::std::fmt::Display for Capacity {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.0.fmt(f)
}
}
impl ::std::fmt::LowerHex for Capacity {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.0.fmt(f)
}
}
| 24.59322 | 96 | 0.589019 |
79a66e034109bba6c83105f6195e42d3003612de | 611 | //! A collection of types used to pass data across the rest HTTP API.
//!
//! This is primarily used by the validator client and the beacon node rest API.
mod beacon;
mod consensus;
mod node;
mod validator;
pub use beacon::{
BlockResponse, CanonicalHeadResponse, Committee, HeadBeaconBlock, StateResponse,
ValidatorRequest, ValidatorResponse,
};
pub use validator::{
ValidatorDutiesRequest, ValidatorDuty, ValidatorDutyBytes, ValidatorSubscription,
};
pub use consensus::{IndividualVote, IndividualVotesRequest, IndividualVotesResponse};
pub use node::{Health, SyncingResponse, SyncingStatus};
| 27.772727 | 85 | 0.780687 |
69c4279450b7b9694af09bc49b0bf68ee655b641 | 1,915 | use core::ops::{Deref, DerefMut};
#[cfg(target_pointer_width = "64")]
#[repr(align(8))]
#[derive(Copy, Clone, Debug)]
pub struct UsizeAligned<T: ?Sized>(T);
#[cfg(target_pointer_width = "32")]
#[repr(align(4))]
#[derive(Copy, Clone, Debug)]
pub struct UsizeAligned<T: ?Sized>(T);
impl<T> UsizeAligned<T> {
#[inline]
pub const fn new(value: T) -> Self {
UsizeAligned(value)
}
#[inline]
pub fn into_inner(self) -> T {
self.0
}
}
impl<T: ?Sized> Deref for UsizeAligned<T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
&self.0
}
}
impl<T: ?Sized> DerefMut for UsizeAligned<T> {
#[inline]
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
#[repr(packed)]
struct Unaligned<T>(T);
pub struct ForcedUsizeAligned<T>(UsizeAligned<Unaligned<T>>);
impl<T> ForcedUsizeAligned<T> {
#[inline]
pub const fn new(value: T) -> Self {
ForcedUsizeAligned(UsizeAligned(Unaligned(value)))
}
}
#[cfg(test)]
mod test {
use super::*;
use core::mem;
#[test]
fn alignment() {
let x = 0i8;
let x_usize_aligned = UsizeAligned::new(x);
assert_eq!(
mem::align_of_val(&x_usize_aligned),
mem::align_of::<usize>()
);
let x = ();
let x_usize_aligned = UsizeAligned::new(x);
assert_eq!(
mem::align_of_val(&x_usize_aligned),
mem::align_of::<usize>()
);
#[repr(align(1024))]
struct OverAligned;
let x = OverAligned;
let x_usize_aligned = UsizeAligned::new(x);
assert!(mem::align_of_val(&x_usize_aligned) > mem::align_of::<usize>());
let x = OverAligned;
let x_force_usize_aligned = ForcedUsizeAligned::new(x);
assert_eq!(
mem::align_of_val(&x_force_usize_aligned),
mem::align_of::<usize>()
);
}
}
| 21.516854 | 80 | 0.565013 |
accb90f3ab5955dbb808c9de9be2da9c920f91d3 | 4,591 | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![deny(missing_docs)]
//! Typesafe wrappers around an "update" package.
mod board;
mod hash;
mod image;
mod images;
mod name;
mod packages;
mod update_mode;
mod version;
pub use crate::{
board::VerifyBoardError,
hash::HashError,
image::{Image, ImageClass, OpenImageError},
images::{ImageList, ResolveImagesError, UnverifiedImageList},
name::VerifyNameError,
packages::ParsePackageError,
update_mode::{ParseUpdateModeError, UpdateMode},
version::ReadVersionError,
};
use {fidl_fuchsia_io::DirectoryProxy, fuchsia_hash::Hash, fuchsia_url::pkg_url::PkgUrl};
/// An open handle to an "update" package.
#[derive(Debug)]
pub struct UpdatePackage {
proxy: DirectoryProxy,
}
impl UpdatePackage {
/// Creates a new [`UpdatePackage`] with the given proxy.
pub fn new(proxy: DirectoryProxy) -> Self {
Self { proxy }
}
/// Verifies that the package's name/variant is "update/0".
pub async fn verify_name(&self) -> Result<(), VerifyNameError> {
name::verify(&self.proxy).await
}
/// Searches for the requested images in the update package, returning the resolved sequence of
/// images in the same order as the requests.
///
/// If a request ends in `[_type]`, that request is expanded to all found images with the
/// prefix of the request, sorted alphabetically.
pub async fn resolve_images(
&self,
requests: &[String],
) -> Result<UnverifiedImageList, ResolveImagesError> {
images::resolve_images(&self.proxy, requests).await
}
/// Opens the given `image` as a resizable VMO buffer.
pub async fn open_image(
&self,
image: &Image,
) -> Result<fidl_fuchsia_mem::Buffer, OpenImageError> {
image::open(&self.proxy, image).await
}
/// Verifies the board file has the given `contents`.
pub async fn verify_board(&self, contents: &str) -> Result<(), VerifyBoardError> {
board::verify_board(&self.proxy, contents).await
}
/// Parses the update-mode file to obtain update mode.
pub async fn update_mode(&self) -> Result<Option<UpdateMode>, ParseUpdateModeError> {
update_mode::update_mode(&self.proxy).await
}
/// Returns the list of package urls that go in the universe of this update package.
pub async fn packages(&self) -> Result<Vec<PkgUrl>, ParsePackageError> {
packages::packages(&self.proxy).await
}
/// Returns the package hash of this update package.
pub async fn hash(&self) -> Result<Hash, HashError> {
hash::hash(&self.proxy).await
}
/// Returns the version of this update package.
pub async fn version(&self) -> Result<String, ReadVersionError> {
version::read_version(&self.proxy).await
}
}
#[cfg(test)]
struct TestUpdatePackage {
update_pkg: UpdatePackage,
temp_dir: tempfile::TempDir,
}
#[cfg(test)]
impl TestUpdatePackage {
fn new() -> Self {
let temp_dir = tempfile::tempdir().expect("/tmp to exist");
let update_pkg_proxy = io_util::directory::open_in_namespace(
temp_dir.path().to_str().unwrap(),
io_util::OPEN_RIGHT_READABLE,
)
.expect("temp dir to open");
Self { temp_dir, update_pkg: UpdatePackage::new(update_pkg_proxy) }
}
fn proxy(&self) -> &DirectoryProxy {
&self.update_pkg.proxy
}
async fn add_file(self, path: impl AsRef<std::path::Path>, contents: impl AsRef<[u8]>) -> Self {
let path = path.as_ref();
match path.parent() {
Some(empty) if empty == std::path::Path::new("") => {}
None => {}
Some(parent) => std::fs::create_dir_all(self.temp_dir.path().join(parent)).unwrap(),
}
io_util::file::write_in_namespace(
self.temp_dir.path().join(path).to_str().unwrap(),
contents,
)
.await
.expect("create test update package file");
self
}
}
#[cfg(test)]
impl std::ops::Deref for TestUpdatePackage {
type Target = UpdatePackage;
fn deref(&self) -> &Self::Target {
&self.update_pkg
}
}
#[cfg(test)]
mod tests {
use {super::*, fidl_fuchsia_io::DirectoryMarker};
#[fuchsia_async::run_singlethreaded(test)]
async fn lifecycle() {
let (proxy, _server_end) = fidl::endpoints::create_proxy::<DirectoryMarker>().unwrap();
UpdatePackage::new(proxy);
}
}
| 30.203947 | 100 | 0.643868 |
4ad353bbcc265514d881006b655d20c72288637e | 402 | #[derive(Debug)]
pub enum WasmError
{
IOError(std::io::Error),
UnkownKind,
InvalidOpcode,
InvalidThread,
NotImplemented
}
impl std::convert::From<WasmError> for std::io::Error
{
fn from(e: WasmError) -> Self {
match e {
WasmError::IOError(e) => e,
err @ _ => std::io::Error::new(std::io::ErrorKind::Other, format!("{:?}", err))
}
}
} | 21.157895 | 91 | 0.554726 |
ab96dbe732d42409d6c9128039d918ae751a1794 | 48,495 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use crate::logical_plan::display::{GraphvizVisitor, IndentVisitor};
use crate::logical_plan::extension::UserDefinedLogicalNode;
use crate::{Expr, TableProviderFilterPushDown, TableSource};
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use datafusion_common::{Column, DFSchemaRef, DataFusionError};
use std::collections::HashSet;
///! Logical plan types
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
/// A LogicalPlan represents the different types of relational
/// operators (such as Projection, Filter, etc) and can be created by
/// the SQL query planner and the DataFrame API.
///
/// A LogicalPlan represents transforming an input relation (table) to
/// an output relation (table) with a (potentially) different
/// schema. A plan represents a dataflow tree where data flows
/// from leaves up to the root to produce the query result.
#[derive(Clone)]
pub enum LogicalPlan {
/// Evaluates an arbitrary list of expressions (essentially a
/// SELECT with an expression list) on its input.
Projection(Projection),
/// Filters rows from its input that do not match an
/// expression (essentially a WHERE clause with a predicate
/// expression).
///
/// Semantically, `<predicate>` is evaluated for each row of the input;
/// If the value of `<predicate>` is true, the input row is passed to
/// the output. If the value of `<predicate>` is false, the row is
/// discarded.
Filter(Filter),
/// Window its input based on a set of window spec and window function (e.g. SUM or RANK)
Window(Window),
/// Aggregates its input based on a set of grouping and aggregate
/// expressions (e.g. SUM).
Aggregate(Aggregate),
/// Sorts its input according to a list of sort expressions.
Sort(Sort),
/// Join two logical plans on one or more join columns
Join(Join),
/// Apply Cross Join to two logical plans
CrossJoin(CrossJoin),
/// Repartition the plan based on a partitioning scheme.
Repartition(Repartition),
/// Union multiple inputs
Union(Union),
/// Produces rows from a table provider by reference or from the context
TableScan(TableScan),
/// Produces no rows: An empty relation with an empty schema
EmptyRelation(EmptyRelation),
/// Subquery
Subquery(Subquery),
/// Aliased relation provides, or changes, the name of a relation.
SubqueryAlias(SubqueryAlias),
/// Produces the first `n` tuples from its input and discards the rest.
Limit(Limit),
/// Creates an external table.
CreateExternalTable(CreateExternalTable),
/// Creates an in memory table.
CreateMemoryTable(CreateMemoryTable),
/// Creates a new view.
CreateView(CreateView),
/// Creates a new catalog schema.
CreateCatalogSchema(CreateCatalogSchema),
/// Creates a new catalog (aka "Database").
CreateCatalog(CreateCatalog),
/// Drops a table.
DropTable(DropTable),
/// Values expression. See
/// [Postgres VALUES](https://www.postgresql.org/docs/current/queries-values.html)
/// documentation for more details.
Values(Values),
/// Produces a relation with string representations of
/// various parts of the plan
Explain(Explain),
/// Runs the actual plan, and then prints the physical plan with
/// with execution metrics.
Analyze(Analyze),
/// Extension operator defined outside of DataFusion
Extension(Extension),
}
impl LogicalPlan {
/// Get a reference to the logical plan's schema
pub fn schema(&self) -> &DFSchemaRef {
match self {
LogicalPlan::EmptyRelation(EmptyRelation { schema, .. }) => schema,
LogicalPlan::Values(Values { schema, .. }) => schema,
LogicalPlan::TableScan(TableScan {
projected_schema, ..
}) => projected_schema,
LogicalPlan::Projection(Projection { schema, .. }) => schema,
LogicalPlan::Filter(Filter { input, .. }) => input.schema(),
LogicalPlan::Window(Window { schema, .. }) => schema,
LogicalPlan::Aggregate(Aggregate { schema, .. }) => schema,
LogicalPlan::Sort(Sort { input, .. }) => input.schema(),
LogicalPlan::Join(Join { schema, .. }) => schema,
LogicalPlan::CrossJoin(CrossJoin { schema, .. }) => schema,
LogicalPlan::Repartition(Repartition { input, .. }) => input.schema(),
LogicalPlan::Limit(Limit { input, .. }) => input.schema(),
LogicalPlan::Subquery(Subquery { subquery, .. }) => subquery.schema(),
LogicalPlan::SubqueryAlias(SubqueryAlias { schema, .. }) => schema,
LogicalPlan::CreateExternalTable(CreateExternalTable { schema, .. }) => {
schema
}
LogicalPlan::Explain(explain) => &explain.schema,
LogicalPlan::Analyze(analyze) => &analyze.schema,
LogicalPlan::Extension(extension) => extension.node.schema(),
LogicalPlan::Union(Union { schema, .. }) => schema,
LogicalPlan::CreateMemoryTable(CreateMemoryTable { input, .. })
| LogicalPlan::CreateView(CreateView { input, .. }) => input.schema(),
LogicalPlan::CreateCatalogSchema(CreateCatalogSchema { schema, .. }) => {
schema
}
LogicalPlan::CreateCatalog(CreateCatalog { schema, .. }) => schema,
LogicalPlan::DropTable(DropTable { schema, .. }) => schema,
}
}
/// Get a vector of references to all schemas in every node of the logical plan
pub fn all_schemas(&self) -> Vec<&DFSchemaRef> {
match self {
LogicalPlan::TableScan(TableScan {
projected_schema, ..
}) => vec![projected_schema],
LogicalPlan::Values(Values { schema, .. }) => vec![schema],
LogicalPlan::Window(Window { input, schema, .. })
| LogicalPlan::Projection(Projection { input, schema, .. })
| LogicalPlan::Aggregate(Aggregate { input, schema, .. }) => {
let mut schemas = input.all_schemas();
schemas.insert(0, schema);
schemas
}
LogicalPlan::Join(Join {
left,
right,
schema,
..
})
| LogicalPlan::CrossJoin(CrossJoin {
left,
right,
schema,
}) => {
let mut schemas = left.all_schemas();
schemas.extend(right.all_schemas());
schemas.insert(0, schema);
schemas
}
LogicalPlan::Subquery(Subquery { subquery, .. }) => subquery.all_schemas(),
LogicalPlan::SubqueryAlias(SubqueryAlias { schema, .. }) => {
vec![schema]
}
LogicalPlan::Union(Union { schema, .. }) => {
vec![schema]
}
LogicalPlan::Extension(extension) => vec![extension.node.schema()],
LogicalPlan::Explain(Explain { schema, .. })
| LogicalPlan::Analyze(Analyze { schema, .. })
| LogicalPlan::EmptyRelation(EmptyRelation { schema, .. })
| LogicalPlan::CreateExternalTable(CreateExternalTable { schema, .. })
| LogicalPlan::CreateCatalogSchema(CreateCatalogSchema { schema, .. })
| LogicalPlan::CreateCatalog(CreateCatalog { schema, .. }) => {
vec![schema]
}
LogicalPlan::Limit(Limit { input, .. })
| LogicalPlan::Repartition(Repartition { input, .. })
| LogicalPlan::Sort(Sort { input, .. })
| LogicalPlan::CreateMemoryTable(CreateMemoryTable { input, .. })
| LogicalPlan::CreateView(CreateView { input, .. })
| LogicalPlan::Filter(Filter { input, .. }) => input.all_schemas(),
LogicalPlan::DropTable(_) => vec![],
}
}
/// Returns the (fixed) output schema for explain plans
pub fn explain_schema() -> SchemaRef {
SchemaRef::new(Schema::new(vec![
Field::new("plan_type", DataType::Utf8, false),
Field::new("plan", DataType::Utf8, false),
]))
}
/// returns all expressions (non-recursively) in the current
/// logical plan node. This does not include expressions in any
/// children
pub fn expressions(self: &LogicalPlan) -> Vec<Expr> {
match self {
LogicalPlan::Projection(Projection { expr, .. }) => expr.clone(),
LogicalPlan::Values(Values { values, .. }) => {
values.iter().flatten().cloned().collect()
}
LogicalPlan::Filter(Filter { predicate, .. }) => vec![predicate.clone()],
LogicalPlan::Repartition(Repartition {
partitioning_scheme,
..
}) => match partitioning_scheme {
Partitioning::Hash(expr, _) => expr.clone(),
_ => vec![],
},
LogicalPlan::Window(Window { window_expr, .. }) => window_expr.clone(),
LogicalPlan::Aggregate(Aggregate {
group_expr,
aggr_expr,
..
}) => group_expr.iter().chain(aggr_expr.iter()).cloned().collect(),
LogicalPlan::Join(Join { on, .. }) => on
.iter()
.flat_map(|(l, r)| vec![Expr::Column(l.clone()), Expr::Column(r.clone())])
.collect(),
LogicalPlan::Sort(Sort { expr, .. }) => expr.clone(),
LogicalPlan::Extension(extension) => extension.node.expressions(),
// plans without expressions
LogicalPlan::TableScan { .. }
| LogicalPlan::EmptyRelation(_)
| LogicalPlan::Subquery(_)
| LogicalPlan::SubqueryAlias(_)
| LogicalPlan::Limit(_)
| LogicalPlan::CreateExternalTable(_)
| LogicalPlan::CreateMemoryTable(_)
| LogicalPlan::CreateView(_)
| LogicalPlan::CreateCatalogSchema(_)
| LogicalPlan::CreateCatalog(_)
| LogicalPlan::DropTable(_)
| LogicalPlan::CrossJoin(_)
| LogicalPlan::Analyze { .. }
| LogicalPlan::Explain { .. }
| LogicalPlan::Union(_) => {
vec![]
}
}
}
/// returns all inputs of this `LogicalPlan` node. Does not
/// include inputs to inputs.
pub fn inputs(self: &LogicalPlan) -> Vec<&LogicalPlan> {
match self {
LogicalPlan::Projection(Projection { input, .. }) => vec![input],
LogicalPlan::Filter(Filter { input, .. }) => vec![input],
LogicalPlan::Repartition(Repartition { input, .. }) => vec![input],
LogicalPlan::Window(Window { input, .. }) => vec![input],
LogicalPlan::Aggregate(Aggregate { input, .. }) => vec![input],
LogicalPlan::Sort(Sort { input, .. }) => vec![input],
LogicalPlan::Join(Join { left, right, .. }) => vec![left, right],
LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => vec![left, right],
LogicalPlan::Limit(Limit { input, .. }) => vec![input],
LogicalPlan::Subquery(Subquery { subquery, .. }) => vec![subquery],
LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => vec![input],
LogicalPlan::Extension(extension) => extension.node.inputs(),
LogicalPlan::Union(Union { inputs, .. }) => inputs.iter().collect(),
LogicalPlan::Explain(explain) => vec![&explain.plan],
LogicalPlan::Analyze(analyze) => vec![&analyze.input],
LogicalPlan::CreateMemoryTable(CreateMemoryTable { input, .. })
| LogicalPlan::CreateView(CreateView { input, .. }) => {
vec![input]
}
// plans without inputs
LogicalPlan::TableScan { .. }
| LogicalPlan::EmptyRelation { .. }
| LogicalPlan::Values { .. }
| LogicalPlan::CreateExternalTable(_)
| LogicalPlan::CreateCatalogSchema(_)
| LogicalPlan::CreateCatalog(_)
| LogicalPlan::DropTable(_) => vec![],
}
}
/// returns all `Using` join columns in a logical plan
pub fn using_columns(&self) -> Result<Vec<HashSet<Column>>, DataFusionError> {
struct UsingJoinColumnVisitor {
using_columns: Vec<HashSet<Column>>,
}
impl PlanVisitor for UsingJoinColumnVisitor {
type Error = DataFusionError;
fn pre_visit(&mut self, plan: &LogicalPlan) -> Result<bool, Self::Error> {
if let LogicalPlan::Join(Join {
join_constraint: JoinConstraint::Using,
on,
..
}) = plan
{
self.using_columns.push(
on.iter()
.flat_map(|entry| [&entry.0, &entry.1])
.cloned()
.collect::<HashSet<Column>>(),
);
}
Ok(true)
}
}
let mut visitor = UsingJoinColumnVisitor {
using_columns: vec![],
};
self.accept(&mut visitor)?;
Ok(visitor.using_columns)
}
}
/// Trait that implements the [Visitor
/// pattern](https://en.wikipedia.org/wiki/Visitor_pattern) for a
/// depth first walk of `LogicalPlan` nodes. `pre_visit` is called
/// before any children are visited, and then `post_visit` is called
/// after all children have been visited.
////
/// To use, define a struct that implements this trait and then invoke
/// [`LogicalPlan::accept`].
///
/// For example, for a logical plan like:
///
/// ```text
/// Projection: #id
/// Filter: #state Eq Utf8(\"CO\")\
/// CsvScan: employee.csv projection=Some([0, 3])";
/// ```
///
/// The sequence of visit operations would be:
/// ```text
/// visitor.pre_visit(Projection)
/// visitor.pre_visit(Filter)
/// visitor.pre_visit(CsvScan)
/// visitor.post_visit(CsvScan)
/// visitor.post_visit(Filter)
/// visitor.post_visit(Projection)
/// ```
pub trait PlanVisitor {
/// The type of error returned by this visitor
type Error;
/// Invoked on a logical plan before any of its child inputs have been
/// visited. If Ok(true) is returned, the recursion continues. If
/// Err(..) or Ok(false) are returned, the recursion stops
/// immediately and the error, if any, is returned to `accept`
fn pre_visit(&mut self, plan: &LogicalPlan)
-> std::result::Result<bool, Self::Error>;
/// Invoked on a logical plan after all of its child inputs have
/// been visited. The return value is handled the same as the
/// return value of `pre_visit`. The provided default implementation
/// returns `Ok(true)`.
fn post_visit(
&mut self,
_plan: &LogicalPlan,
) -> std::result::Result<bool, Self::Error> {
Ok(true)
}
}
impl LogicalPlan {
/// returns all inputs in the logical plan. Returns Ok(true) if
/// all nodes were visited, and Ok(false) if any call to
/// `pre_visit` or `post_visit` returned Ok(false) and may have
/// cut short the recursion
pub fn accept<V>(&self, visitor: &mut V) -> std::result::Result<bool, V::Error>
where
V: PlanVisitor,
{
if !visitor.pre_visit(self)? {
return Ok(false);
}
let recurse = match self {
LogicalPlan::Projection(Projection { input, .. }) => input.accept(visitor)?,
LogicalPlan::Filter(Filter { input, .. }) => input.accept(visitor)?,
LogicalPlan::Repartition(Repartition { input, .. }) => {
input.accept(visitor)?
}
LogicalPlan::Window(Window { input, .. }) => input.accept(visitor)?,
LogicalPlan::Aggregate(Aggregate { input, .. }) => input.accept(visitor)?,
LogicalPlan::Sort(Sort { input, .. }) => input.accept(visitor)?,
LogicalPlan::Join(Join { left, right, .. })
| LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => {
left.accept(visitor)? && right.accept(visitor)?
}
LogicalPlan::Union(Union { inputs, .. }) => {
for input in inputs {
if !input.accept(visitor)? {
return Ok(false);
}
}
true
}
LogicalPlan::Limit(Limit { input, .. }) => input.accept(visitor)?,
LogicalPlan::Subquery(Subquery { subquery, .. }) => {
subquery.accept(visitor)?
}
LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => {
input.accept(visitor)?
}
LogicalPlan::CreateMemoryTable(CreateMemoryTable { input, .. })
| LogicalPlan::CreateView(CreateView { input, .. }) => {
input.accept(visitor)?
}
LogicalPlan::Extension(extension) => {
for input in extension.node.inputs() {
if !input.accept(visitor)? {
return Ok(false);
}
}
true
}
LogicalPlan::Explain(explain) => explain.plan.accept(visitor)?,
LogicalPlan::Analyze(analyze) => analyze.input.accept(visitor)?,
// plans without inputs
LogicalPlan::TableScan { .. }
| LogicalPlan::EmptyRelation(_)
| LogicalPlan::Values(_)
| LogicalPlan::CreateExternalTable(_)
| LogicalPlan::CreateCatalogSchema(_)
| LogicalPlan::CreateCatalog(_)
| LogicalPlan::DropTable(_) => true,
};
if !recurse {
return Ok(false);
}
if !visitor.post_visit(self)? {
return Ok(false);
}
Ok(true)
}
}
// Various implementations for printing out LogicalPlans
impl LogicalPlan {
/// Return a `format`able structure that produces a single line
/// per node. For example:
///
/// ```text
/// Projection: #employee.id
/// Filter: #employee.state Eq Utf8(\"CO\")\
/// CsvScan: employee projection=Some([0, 3])
/// ```
///
/// ```ignore
/// use arrow::datatypes::{Field, Schema, DataType};
/// use datafusion::logical_plan::{lit, col, LogicalPlanBuilder};
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int32, false),
/// ]);
/// let plan = LogicalPlanBuilder::scan_empty(Some("foo_csv"), &schema, None).unwrap()
/// .filter(col("id").eq(lit(5))).unwrap()
/// .build().unwrap();
///
/// // Format using display_indent
/// let display_string = format!("{}", plan.display_indent());
///
/// assert_eq!("Filter: #foo_csv.id = Int32(5)\
/// \n TableScan: foo_csv projection=None",
/// display_string);
/// ```
pub fn display_indent(&self) -> impl fmt::Display + '_ {
// Boilerplate structure to wrap LogicalPlan with something
// that that can be formatted
struct Wrapper<'a>(&'a LogicalPlan);
impl<'a> fmt::Display for Wrapper<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let with_schema = false;
let mut visitor = IndentVisitor::new(f, with_schema);
self.0.accept(&mut visitor).unwrap();
Ok(())
}
}
Wrapper(self)
}
/// Return a `format`able structure that produces a single line
/// per node that includes the output schema. For example:
///
/// ```text
/// Projection: #employee.id [id:Int32]\
/// Filter: #employee.state = Utf8(\"CO\") [id:Int32, state:Utf8]\
/// TableScan: employee projection=Some([0, 3]) [id:Int32, state:Utf8]";
/// ```
///
/// ```ignore
/// use arrow::datatypes::{Field, Schema, DataType};
/// use datafusion::logical_plan::{lit, col, LogicalPlanBuilder};
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int32, false),
/// ]);
/// let plan = LogicalPlanBuilder::scan_empty(Some("foo_csv"), &schema, None).unwrap()
/// .filter(col("id").eq(lit(5))).unwrap()
/// .build().unwrap();
///
/// // Format using display_indent_schema
/// let display_string = format!("{}", plan.display_indent_schema());
///
/// assert_eq!("Filter: #foo_csv.id = Int32(5) [id:Int32]\
/// \n TableScan: foo_csv projection=None [id:Int32]",
/// display_string);
/// ```
pub fn display_indent_schema(&self) -> impl fmt::Display + '_ {
// Boilerplate structure to wrap LogicalPlan with something
// that that can be formatted
struct Wrapper<'a>(&'a LogicalPlan);
impl<'a> fmt::Display for Wrapper<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let with_schema = true;
let mut visitor = IndentVisitor::new(f, with_schema);
self.0.accept(&mut visitor).unwrap();
Ok(())
}
}
Wrapper(self)
}
/// Return a `format`able structure that produces lines meant for
/// graphical display using the `DOT` language. This format can be
/// visualized using software from
/// [`graphviz`](https://graphviz.org/)
///
/// This currently produces two graphs -- one with the basic
/// structure, and one with additional details such as schema.
///
/// ```ignore
/// use arrow::datatypes::{Field, Schema, DataType};
/// use datafusion::logical_plan::{lit, col, LogicalPlanBuilder};
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int32, false),
/// ]);
/// let plan = LogicalPlanBuilder::scan_empty(Some("foo.csv"), &schema, None).unwrap()
/// .filter(col("id").eq(lit(5))).unwrap()
/// .build().unwrap();
///
/// // Format using display_graphviz
/// let graphviz_string = format!("{}", plan.display_graphviz());
/// ```
///
/// If graphviz string is saved to a file such as `/tmp/example.dot`, the following
/// commands can be used to render it as a pdf:
///
/// ```bash
/// dot -Tpdf < /tmp/example.dot > /tmp/example.pdf
/// ```
///
pub fn display_graphviz(&self) -> impl fmt::Display + '_ {
// Boilerplate structure to wrap LogicalPlan with something
// that that can be formatted
struct Wrapper<'a>(&'a LogicalPlan);
impl<'a> fmt::Display for Wrapper<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(
f,
"// Begin DataFusion GraphViz Plan (see https://graphviz.org)"
)?;
writeln!(f, "digraph {{")?;
let mut visitor = GraphvizVisitor::new(f);
visitor.pre_visit_plan("LogicalPlan")?;
self.0.accept(&mut visitor).unwrap();
visitor.post_visit_plan()?;
visitor.set_with_schema(true);
visitor.pre_visit_plan("Detailed LogicalPlan")?;
self.0.accept(&mut visitor).unwrap();
visitor.post_visit_plan()?;
writeln!(f, "}}")?;
writeln!(f, "// End DataFusion GraphViz Plan")?;
Ok(())
}
}
Wrapper(self)
}
/// Return a `format`able structure with the a human readable
/// description of this LogicalPlan node per node, not including
/// children. For example:
///
/// ```text
/// Projection: #id
/// ```
/// ```ignore
/// use arrow::datatypes::{Field, Schema, DataType};
/// use datafusion::logical_plan::{lit, col, LogicalPlanBuilder};
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int32, false),
/// ]);
/// let plan = LogicalPlanBuilder::scan_empty(Some("foo.csv"), &schema, None).unwrap()
/// .build().unwrap();
///
/// // Format using display
/// let display_string = format!("{}", plan.display());
///
/// assert_eq!("TableScan: foo.csv projection=None", display_string);
/// ```
pub fn display(&self) -> impl fmt::Display + '_ {
// Boilerplate structure to wrap LogicalPlan with something
// that that can be formatted
struct Wrapper<'a>(&'a LogicalPlan);
impl<'a> fmt::Display for Wrapper<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &*self.0 {
LogicalPlan::EmptyRelation(_) => write!(f, "EmptyRelation"),
LogicalPlan::Values(Values { ref values, .. }) => {
let str_values: Vec<_> = values
.iter()
// limit to only 5 values to avoid horrible display
.take(5)
.map(|row| {
let item = row
.iter()
.map(|expr| expr.to_string())
.collect::<Vec<_>>()
.join(", ");
format!("({})", item)
})
.collect();
let elipse = if values.len() > 5 { "..." } else { "" };
write!(f, "Values: {}{}", str_values.join(", "), elipse)
}
LogicalPlan::TableScan(TableScan {
ref source,
ref table_name,
ref projection,
ref filters,
ref limit,
..
}) => {
write!(
f,
"TableScan: {} projection={:?}",
table_name, projection
)?;
if !filters.is_empty() {
let mut full_filter = vec![];
let mut partial_filter = vec![];
let mut unsupported_filters = vec![];
filters.iter().for_each(|x| {
if let Ok(t) = source.supports_filter_pushdown(x) {
match t {
TableProviderFilterPushDown::Exact => {
full_filter.push(x)
}
TableProviderFilterPushDown::Inexact => {
partial_filter.push(x)
}
TableProviderFilterPushDown::Unsupported => {
unsupported_filters.push(x)
}
}
}
});
if !full_filter.is_empty() {
write!(f, ", full_filters={:?}", full_filter)?;
};
if !partial_filter.is_empty() {
write!(f, ", partial_filters={:?}", partial_filter)?;
}
if !unsupported_filters.is_empty() {
write!(
f,
", unsupported_filters={:?}",
unsupported_filters
)?;
}
}
if let Some(n) = limit {
write!(f, ", limit={}", n)?;
}
Ok(())
}
LogicalPlan::Projection(Projection {
ref expr, alias, ..
}) => {
write!(f, "Projection: ")?;
for (i, expr_item) in expr.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{:?}", expr_item)?;
}
if let Some(a) = alias {
write!(f, ", alias={}", a)?;
}
Ok(())
}
LogicalPlan::Filter(Filter {
predicate: ref expr,
..
}) => write!(f, "Filter: {:?}", expr),
LogicalPlan::Window(Window {
ref window_expr, ..
}) => {
write!(f, "WindowAggr: windowExpr=[{:?}]", window_expr)
}
LogicalPlan::Aggregate(Aggregate {
ref group_expr,
ref aggr_expr,
..
}) => write!(
f,
"Aggregate: groupBy=[{:?}], aggr=[{:?}]",
group_expr, aggr_expr
),
LogicalPlan::Sort(Sort { expr, .. }) => {
write!(f, "Sort: ")?;
for (i, expr_item) in expr.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{:?}", expr_item)?;
}
Ok(())
}
LogicalPlan::Join(Join {
on: ref keys,
join_constraint,
join_type,
..
}) => {
let join_expr: Vec<String> =
keys.iter().map(|(l, r)| format!("{} = {}", l, r)).collect();
match join_constraint {
JoinConstraint::On => {
write!(f, "{} Join: {}", join_type, join_expr.join(", "))
}
JoinConstraint::Using => {
write!(
f,
"{} Join: Using {}",
join_type,
join_expr.join(", ")
)
}
}
}
LogicalPlan::CrossJoin(_) => {
write!(f, "CrossJoin:")
}
LogicalPlan::Repartition(Repartition {
partitioning_scheme,
..
}) => match partitioning_scheme {
Partitioning::RoundRobinBatch(n) => write!(
f,
"Repartition: RoundRobinBatch partition_count={}",
n
),
Partitioning::Hash(expr, n) => {
let hash_expr: Vec<String> =
expr.iter().map(|e| format!("{:?}", e)).collect();
write!(
f,
"Repartition: Hash({}) partition_count={}",
hash_expr.join(", "),
n
)
}
},
LogicalPlan::Limit(Limit { ref n, .. }) => write!(f, "Limit: {}", n),
LogicalPlan::Subquery(Subquery { subquery, .. }) => {
write!(f, "Subquery: {:?}", subquery)
}
LogicalPlan::SubqueryAlias(SubqueryAlias { ref alias, .. }) => {
write!(f, "SubqueryAlias: {}", alias)
}
LogicalPlan::CreateExternalTable(CreateExternalTable {
ref name,
..
}) => {
write!(f, "CreateExternalTable: {:?}", name)
}
LogicalPlan::CreateMemoryTable(CreateMemoryTable {
name, ..
}) => {
write!(f, "CreateMemoryTable: {:?}", name)
}
LogicalPlan::CreateView(CreateView { name, .. }) => {
write!(f, "CreateView: {:?}", name)
}
LogicalPlan::CreateCatalogSchema(CreateCatalogSchema {
schema_name,
..
}) => {
write!(f, "CreateCatalogSchema: {:?}", schema_name)
}
LogicalPlan::CreateCatalog(CreateCatalog {
catalog_name, ..
}) => {
write!(f, "CreateCatalog: {:?}", catalog_name)
}
LogicalPlan::DropTable(DropTable {
name, if_exists, ..
}) => {
write!(f, "DropTable: {:?} if not exist:={}", name, if_exists)
}
LogicalPlan::Explain { .. } => write!(f, "Explain"),
LogicalPlan::Analyze { .. } => write!(f, "Analyze"),
LogicalPlan::Union(_) => write!(f, "Union"),
LogicalPlan::Extension(e) => e.node.fmt_for_explain(f),
}
}
}
Wrapper(self)
}
}
impl fmt::Debug for LogicalPlan {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.display_indent().fmt(f)
}
}
impl ToStringifiedPlan for LogicalPlan {
fn to_stringified(&self, plan_type: PlanType) -> StringifiedPlan {
StringifiedPlan::new(plan_type, self.display_indent().to_string())
}
}
/// Join type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoinType {
/// Inner Join
Inner,
/// Left Join
Left,
/// Right Join
Right,
/// Full Join
Full,
/// Semi Join
Semi,
/// Anti Join
Anti,
}
impl Display for JoinType {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let join_type = match self {
JoinType::Inner => "Inner",
JoinType::Left => "Left",
JoinType::Right => "Right",
JoinType::Full => "Full",
JoinType::Semi => "Semi",
JoinType::Anti => "Anti",
};
write!(f, "{}", join_type)
}
}
/// Join constraint
#[derive(Debug, Clone, Copy)]
pub enum JoinConstraint {
/// Join ON
On,
/// Join USING
Using,
}
/// Creates a catalog (aka "Database").
#[derive(Clone)]
pub struct CreateCatalog {
/// The catalog name
pub catalog_name: String,
/// Do nothing (except issuing a notice) if a schema with the same name already exists
pub if_not_exists: bool,
/// Empty schema
pub schema: DFSchemaRef,
}
/// Creates a schema.
#[derive(Clone)]
pub struct CreateCatalogSchema {
/// The table schema
pub schema_name: String,
/// Do nothing (except issuing a notice) if a schema with the same name already exists
pub if_not_exists: bool,
/// Empty schema
pub schema: DFSchemaRef,
}
/// Drops a table.
#[derive(Clone)]
pub struct DropTable {
/// The table name
pub name: String,
/// If the table exists
pub if_exists: bool,
/// Dummy schema
pub schema: DFSchemaRef,
}
/// Produces no rows: An empty relation with an empty schema
#[derive(Clone)]
pub struct EmptyRelation {
/// Whether to produce a placeholder row
pub produce_one_row: bool,
/// The schema description of the output
pub schema: DFSchemaRef,
}
/// Values expression. See
/// [Postgres VALUES](https://www.postgresql.org/docs/current/queries-values.html)
/// documentation for more details.
#[derive(Clone)]
pub struct Values {
/// The table schema
pub schema: DFSchemaRef,
/// Values
pub values: Vec<Vec<Expr>>,
}
/// Evaluates an arbitrary list of expressions (essentially a
/// SELECT with an expression list) on its input.
#[derive(Clone)]
pub struct Projection {
/// The list of expressions
pub expr: Vec<Expr>,
/// The incoming logical plan
pub input: Arc<LogicalPlan>,
/// The schema description of the output
pub schema: DFSchemaRef,
/// Projection output relation alias
pub alias: Option<String>,
}
/// Aliased subquery
#[derive(Clone)]
pub struct SubqueryAlias {
/// The incoming logical plan
pub input: Arc<LogicalPlan>,
/// The alias for the input relation
pub alias: String,
/// The schema with qualified field names
pub schema: DFSchemaRef,
}
/// Filters rows from its input that do not match an
/// expression (essentially a WHERE clause with a predicate
/// expression).
///
/// Semantically, `<predicate>` is evaluated for each row of the input;
/// If the value of `<predicate>` is true, the input row is passed to
/// the output. If the value of `<predicate>` is false, the row is
/// discarded.
#[derive(Clone)]
pub struct Filter {
/// The predicate expression, which must have Boolean type.
pub predicate: Expr,
/// The incoming logical plan
pub input: Arc<LogicalPlan>,
}
/// Window its input based on a set of window spec and window function (e.g. SUM or RANK)
#[derive(Clone)]
pub struct Window {
/// The incoming logical plan
pub input: Arc<LogicalPlan>,
/// The window function expression
pub window_expr: Vec<Expr>,
/// The schema description of the window output
pub schema: DFSchemaRef,
}
/// Produces rows from a table provider by reference or from the context
#[derive(Clone)]
pub struct TableScan {
/// The name of the table
pub table_name: String,
/// The source of the table
pub source: Arc<dyn TableSource>,
/// Optional column indices to use as a projection
pub projection: Option<Vec<usize>>,
/// The schema description of the output
pub projected_schema: DFSchemaRef,
/// Optional expressions to be used as filters by the table provider
pub filters: Vec<Expr>,
/// Optional limit to skip reading
pub limit: Option<usize>,
}
/// Apply Cross Join to two logical plans
#[derive(Clone)]
pub struct CrossJoin {
/// Left input
pub left: Arc<LogicalPlan>,
/// Right input
pub right: Arc<LogicalPlan>,
/// The output schema, containing fields from the left and right inputs
pub schema: DFSchemaRef,
}
/// Repartition the plan based on a partitioning scheme.
#[derive(Clone)]
pub struct Repartition {
/// The incoming logical plan
pub input: Arc<LogicalPlan>,
/// The partitioning scheme
pub partitioning_scheme: Partitioning,
}
/// Union multiple inputs
#[derive(Clone)]
pub struct Union {
/// Inputs to merge
pub inputs: Vec<LogicalPlan>,
/// Union schema. Should be the same for all inputs.
pub schema: DFSchemaRef,
/// Union output relation alias
pub alias: Option<String>,
}
/// Creates an in memory table.
#[derive(Clone)]
pub struct CreateMemoryTable {
/// The table name
pub name: String,
/// The logical plan
pub input: Arc<LogicalPlan>,
/// Option to not error if table already exists
pub if_not_exists: bool,
}
/// Creates a view.
#[derive(Clone)]
pub struct CreateView {
/// The table name
pub name: String,
/// The logical plan
pub input: Arc<LogicalPlan>,
/// Option to not error if table already exists
pub or_replace: bool,
}
/// Types of files to parse as DataFrames
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FileType {
/// Newline-delimited JSON
NdJson,
/// Apache Parquet columnar storage
Parquet,
/// Comma separated values
CSV,
/// Avro binary records
Avro,
}
/// Creates an external table.
#[derive(Clone)]
pub struct CreateExternalTable {
/// The table schema
pub schema: DFSchemaRef,
/// The table name
pub name: String,
/// The physical location
pub location: String,
/// The file type of physical file
pub file_type: FileType,
/// Whether the CSV file contains a header
pub has_header: bool,
/// Delimiter for CSV
pub delimiter: char,
/// Partition Columns
pub table_partition_cols: Vec<String>,
/// Option to not error if table already exists
pub if_not_exists: bool,
}
/// Produces a relation with string representations of
/// various parts of the plan
#[derive(Clone)]
pub struct Explain {
/// Should extra (detailed, intermediate plans) be included?
pub verbose: bool,
/// The logical plan that is being EXPLAIN'd
pub plan: Arc<LogicalPlan>,
/// Represent the various stages plans have gone through
pub stringified_plans: Vec<StringifiedPlan>,
/// The output schema of the explain (2 columns of text)
pub schema: DFSchemaRef,
}
/// Runs the actual plan, and then prints the physical plan with
/// with execution metrics.
#[derive(Clone)]
pub struct Analyze {
/// Should extra detail be included?
pub verbose: bool,
/// The logical plan that is being EXPLAIN ANALYZE'd
pub input: Arc<LogicalPlan>,
/// The output schema of the explain (2 columns of text)
pub schema: DFSchemaRef,
}
/// Extension operator defined outside of DataFusion
#[derive(Clone)]
pub struct Extension {
/// The runtime extension operator
pub node: Arc<dyn UserDefinedLogicalNode + Send + Sync>,
}
/// Produces the first `n` tuples from its input and discards the rest.
#[derive(Clone)]
pub struct Limit {
/// The limit
pub n: usize,
/// The logical plan
pub input: Arc<LogicalPlan>,
}
/// Aggregates its input based on a set of grouping and aggregate
/// expressions (e.g. SUM).
#[derive(Clone)]
pub struct Aggregate {
/// The incoming logical plan
pub input: Arc<LogicalPlan>,
/// Grouping expressions
pub group_expr: Vec<Expr>,
/// Aggregate expressions
pub aggr_expr: Vec<Expr>,
/// The schema description of the aggregate output
pub schema: DFSchemaRef,
}
/// Sorts its input according to a list of sort expressions.
#[derive(Clone)]
pub struct Sort {
/// The sort expressions
pub expr: Vec<Expr>,
/// The incoming logical plan
pub input: Arc<LogicalPlan>,
}
/// Join two logical plans on one or more join columns
#[derive(Clone)]
pub struct Join {
/// Left input
pub left: Arc<LogicalPlan>,
/// Right input
pub right: Arc<LogicalPlan>,
/// Equijoin clause expressed as pairs of (left, right) join columns
pub on: Vec<(Column, Column)>,
/// Join type
pub join_type: JoinType,
/// Join constraint
pub join_constraint: JoinConstraint,
/// The output schema, containing fields from the left and right inputs
pub schema: DFSchemaRef,
/// If null_equals_null is true, null == null else null != null
pub null_equals_null: bool,
}
/// Subquery
#[derive(Clone)]
pub struct Subquery {
/// The subquery
pub subquery: Arc<LogicalPlan>,
}
impl Debug for Subquery {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Subquery: {:?}", self.subquery)
}
}
impl Hash for Subquery {
fn hash<H: Hasher>(&self, state: &mut H) {
state.finish();
}
fn hash_slice<H: Hasher>(_data: &[Self], state: &mut H)
where
Self: Sized,
{
state.finish();
}
}
impl PartialEq for Subquery {
fn eq(&self, _other: &Self) -> bool {
false
}
}
/// Logical partitioning schemes supported by the repartition operator.
#[derive(Debug, Clone)]
pub enum Partitioning {
/// Allocate batches using a round-robin algorithm and the specified number of partitions
RoundRobinBatch(usize),
/// Allocate rows based on a hash of one of more expressions and the specified number
/// of partitions.
/// This partitioning scheme is not yet fully supported. See <https://issues.apache.org/jira/browse/ARROW-11011>
Hash(Vec<Expr>, usize),
}
/// Represents which type of plan, when storing multiple
/// for use in EXPLAIN plans
#[derive(Debug, Clone, PartialEq)]
pub enum PlanType {
/// The initial LogicalPlan provided to DataFusion
InitialLogicalPlan,
/// The LogicalPlan which results from applying an optimizer pass
OptimizedLogicalPlan {
/// The name of the optimizer which produced this plan
optimizer_name: String,
},
/// The final, fully optimized LogicalPlan that was converted to a physical plan
FinalLogicalPlan,
/// The initial physical plan, prepared for execution
InitialPhysicalPlan,
/// The ExecutionPlan which results from applying an optimizer pass
OptimizedPhysicalPlan {
/// The name of the optimizer which produced this plan
optimizer_name: String,
},
/// The final, fully optimized physical which would be executed
FinalPhysicalPlan,
}
impl fmt::Display for PlanType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PlanType::InitialLogicalPlan => write!(f, "initial_logical_plan"),
PlanType::OptimizedLogicalPlan { optimizer_name } => {
write!(f, "logical_plan after {}", optimizer_name)
}
PlanType::FinalLogicalPlan => write!(f, "logical_plan"),
PlanType::InitialPhysicalPlan => write!(f, "initial_physical_plan"),
PlanType::OptimizedPhysicalPlan { optimizer_name } => {
write!(f, "physical_plan after {}", optimizer_name)
}
PlanType::FinalPhysicalPlan => write!(f, "physical_plan"),
}
}
}
/// Represents some sort of execution plan, in String form
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::rc_buffer)]
pub struct StringifiedPlan {
/// An identifier of what type of plan this string represents
pub plan_type: PlanType,
/// The string representation of the plan
pub plan: Arc<String>,
}
impl StringifiedPlan {
/// Create a new Stringified plan of `plan_type` with string
/// representation `plan`
pub fn new(plan_type: PlanType, plan: impl Into<String>) -> Self {
StringifiedPlan {
plan_type,
plan: Arc::new(plan.into()),
}
}
/// returns true if this plan should be displayed. Generally
/// `verbose_mode = true` will display all available plans
pub fn should_display(&self, verbose_mode: bool) -> bool {
match self.plan_type {
PlanType::FinalLogicalPlan | PlanType::FinalPhysicalPlan => true,
_ => verbose_mode,
}
}
}
/// Trait for something that can be formatted as a stringified plan
pub trait ToStringifiedPlan {
/// Create a stringified plan with the specified type
fn to_stringified(&self, plan_type: PlanType) -> StringifiedPlan;
}
| 37.447876 | 116 | 0.535457 |
8f50133f5a0646f3d7a03376bcfb7557df34699d | 150 | // SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright (c) 2020-2022 Andre Richter <[email protected]>
//! Processor code.
mod boot;
| 18.75 | 68 | 0.7 |
5dac9556d15573ac8fee5f88091d963f35e84850 | 1,639 | // This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
use super::*;
/// `CERT` record support.
pub mod certificate;
/// `CAA` record support.
pub mod certification_authority_authorization;
/// `DHCID` record support.
pub mod dhcid;
/// `TLSA` and `SMIME` record support.
pub mod dns_based_authentication_of_named_entities;
/// DNSSEC.
pub mod dnssec;
/// `LOC` record support.
pub mod location;
/// `NAPTR` record support.
pub mod naming_authority_pointer;
/// Host Identity Protocol (HIP) record support.
///
/// See RFC 8005.
pub mod host_identity_protocol;
/// Identifier-Locator Network Protocol (ILNP) record support.
///
/// See RFC 6742.
pub mod identifier_locator_network_protocol;
/// `IPSECKEY` (and potentially the obsolete `KEY`) record support.
pub mod ipsec;
/// `SSHFP` record support.
pub mod ssh_fingerprint;
/// `SOA` record support.
pub mod start_of_authority;
include!("HostInformation.rs");
include!("KeyExchange.rs");
include!("MailExchange.rs");
include!("OpenPgpRfc4880TransferablePublicKey.rs");
include!("ServiceLocation.rs");
include!("Uri.rs");
| 24.833333 | 388 | 0.752898 |
0a33f186c16b04d765c5386cb932c0800e3b6f05 | 14,553 | use std::{cell::Cell, iter, num::NonZeroU64};
use smallvec::SmallVec;
use crate::{
math::{self, Bezier, Mat},
renderer::StrokeStyle,
shapes::paint::{StrokeCap, StrokeJoin},
};
#[derive(Clone, Debug)]
pub struct CommandPathBuilder {
commands: Vec<Command>,
}
impl CommandPathBuilder {
pub fn new() -> Self {
Self {
commands: Vec::new(),
}
}
pub fn move_to(&mut self, p: math::Vec) -> &mut Self {
self.commands.push(Command::MoveTo(p));
self
}
pub fn line_to(&mut self, p: math::Vec) -> &mut Self {
self.commands.push(Command::LineTo(p));
self
}
pub fn cubic_to(&mut self, c0: math::Vec, c1: math::Vec, p: math::Vec) -> &mut Self {
self.commands.push(Command::CubicTo(c0, c1, p));
self
}
pub fn rect(&mut self, p: math::Vec, size: math::Vec) -> &mut Self {
self.move_to(p)
.line_to(p + math::Vec::new(size.x, 0.0))
.line_to(p + math::Vec::new(size.x, size.y))
.line_to(p + math::Vec::new(0.0, size.y))
.close()
}
pub fn path(&mut self, path: &CommandPath, t: Mat) -> &mut Self {
self.commands
.extend(path.commands.iter().map(|&command| match command {
Command::MoveTo(p) => Command::MoveTo(t * p),
Command::LineTo(p) => Command::LineTo(t * p),
Command::CubicTo(c0, c1, p) => Command::CubicTo(t * c0, t * c1, t * p),
Command::Close => Command::Close,
}));
self
}
pub fn close(&mut self) -> &mut Self {
self.commands.push(Command::Close);
self
}
pub fn build(self) -> CommandPath {
CommandPath {
commands: self.commands,
user_tag: Cell::new(None),
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum Command {
MoveTo(math::Vec),
LineTo(math::Vec),
CubicTo(math::Vec, math::Vec, math::Vec),
Close,
}
#[derive(Clone, Debug)]
pub struct CommandPath {
pub commands: Vec<Command>,
pub user_tag: Cell<Option<NonZeroU64>>,
}
impl CommandPath {
pub fn outline_strokes(&self, style: &StrokeStyle) -> Self {
let mut commands = Vec::new();
let mut curves = Vec::new();
let mut end_point = None;
for command in &self.commands {
match *command {
Command::MoveTo(p) => {
if !curves.is_empty() {
if let Some(outline) = Outline::new(&curves, false, style) {
commands.extend(outline.as_commands());
}
curves.clear();
}
end_point = Some(p);
}
Command::LineTo(p) => {
curves.push(Bezier::Line([end_point.unwrap(), p]));
end_point = Some(p);
}
Command::CubicTo(c0, c1, p) => {
curves.push(Bezier::Cubic([end_point.unwrap(), c0, c1, p]));
end_point = Some(p);
}
Command::Close => {
if let (Some(first), Some(last)) = (
curves.first().and_then(|c| c.points().first().copied()),
curves.last().and_then(|c| c.points().last().copied()),
) {
if first.distance(last) > 0.01 {
curves.push(Bezier::Line([last, first]));
}
}
if let Some(outline) = Outline::new(&curves, true, &style) {
commands.extend(outline.as_commands());
}
curves.clear();
end_point = None;
}
}
}
if !curves.is_empty() {
if let Some(outline) = Outline::new(&curves, false, &style) {
commands.extend(outline.as_commands());
}
}
Self {
commands,
user_tag: Cell::new(None),
}
}
}
#[derive(Debug)]
struct Line {
point: math::Vec,
angle: f32,
}
impl Line {
pub fn new(p0: math::Vec, p1: math::Vec) -> Self {
let diff = p1 - p0;
Self {
point: p1,
angle: diff.y.atan2(diff.x),
}
}
fn angle_vec(&self) -> math::Vec {
let (sin, cos) = self.angle.sin_cos();
math::Vec::new(cos, sin)
}
pub fn intersect(&self, other: &Self) -> math::Vec {
let d0 = self.angle_vec();
let d1 = other.angle_vec();
let d = d0 - d1;
let t = if d.x != 0.0 {
(other.point.x - self.point.x) / d.x
} else {
(other.point.y - self.point.y) / d.y
};
self.point + math::Vec::new(d0.x, d0.y) * t
}
pub fn angle_diff(&self, other: &Self) -> f32 {
let diff = self.angle - other.angle;
let (sin, cos) = diff.sin_cos();
sin.atan2(cos).abs()
}
pub fn project(&self, dist: f32) -> math::Vec {
self.point + self.angle_vec() * dist
}
pub fn mid(&self, other: &Self) -> Self {
let mid_angle = (self.angle_vec() + other.angle_vec()) * 0.5;
Self {
point: (self.point + other.point) * 0.5,
angle: mid_angle.y.atan2(mid_angle.x),
}
}
}
const MITER_LIMIT: f32 = 10.0;
#[derive(Debug)]
struct Outline {
curves: Vec<Bezier>,
second_outline_index: Option<usize>,
}
impl Outline {
fn last_first_line(&self, next_curves: &[Bezier]) -> (Line, Line) {
let last = self.curves.last().unwrap();
let first = next_curves.first().unwrap();
let [p0, p1] = last.right_different();
let last_line = Line::new(p0, p1);
let [p0, p1] = first.left_different();
let first_line = Line::new(p1, p0);
(last_line, first_line)
}
fn join(&mut self, next_curves: &mut [Bezier], dist: f32, join: StrokeJoin) {
let last = self.curves.last_mut().unwrap();
let first = next_curves.first_mut().unwrap();
if !last.intersect(first) {
let (last_line, first_line) = self.last_first_line(&next_curves);
let mid_line = last_line.mid(&first_line);
match join {
StrokeJoin::Bevel => {
self.curves
.push(Bezier::Line([last_line.point, first_line.point]));
}
StrokeJoin::Miter => {
let intersection = last_line.intersect(&first_line);
if last_line.angle_diff(&first_line) >= MITER_LIMIT.recip().asin() * 2.0 {
self.curves
.push(Bezier::Line([last_line.point, intersection]));
self.curves
.push(Bezier::Line([intersection, first_line.point]));
} else {
self.curves
.push(Bezier::Line([last_line.point, first_line.point]));
}
}
StrokeJoin::Round => {
let angle = std::f32::consts::PI - last_line.angle_diff(&first_line);
if angle < std::f32::consts::FRAC_PI_2 {
self.curves.push(Bezier::Cubic([
last_line.point,
last_line.project(math::arc_constant(angle) * dist),
first_line.project(math::arc_constant(angle) * dist),
first_line.point,
]));
} else {
let angle = angle / 2.0;
let mid_dist = (1.0 - angle.cos()) * dist;
let mid = mid_line.project(mid_dist);
let mid_left = Line {
point: mid,
angle: mid_line.angle + std::f32::consts::FRAC_PI_2,
};
let mid_right = Line {
point: mid,
angle: mid_line.angle - std::f32::consts::FRAC_PI_2,
};
self.curves.push(Bezier::Cubic([
last_line.point,
last_line.project(math::arc_constant(angle) * dist),
mid_left.project(math::arc_constant(angle) * dist),
mid,
]));
self.curves.push(Bezier::Cubic([
mid,
mid_right.project(math::arc_constant(angle) * dist),
first_line.project(math::arc_constant(angle) * dist),
first_line.point,
]));
}
}
}
}
}
fn join_curves(
&mut self,
mut offset_curves: impl Iterator<Item = SmallVec<[Bezier; 16]>>,
dist: f32,
join: StrokeJoin,
is_closed: bool,
) {
let start_index = self.curves.len();
self.curves.extend(offset_curves.next().unwrap());
for mut next_curves in offset_curves {
self.join(&mut next_curves, dist, join);
self.curves.extend(next_curves);
}
if is_closed {
let mut next_curves = [self.curves[start_index].clone()];
self.join(&mut next_curves, dist, join);
self.curves[start_index] = next_curves[0].clone();
}
}
fn cap_end(&mut self, last_line: &Line, first_line: &Line, dist: f32, cap: StrokeCap) {
match cap {
StrokeCap::Butt => {
self.curves
.push(Bezier::Line([last_line.point, first_line.point]));
}
StrokeCap::Square => {
let projected_last = last_line.project(dist);
let projected_first = first_line.project(dist);
self.curves
.push(Bezier::Line([last_line.point, projected_last]));
self.curves
.push(Bezier::Line([projected_last, projected_first]));
self.curves
.push(Bezier::Line([projected_first, first_line.point]));
}
StrokeCap::Round => {
let mid_line = last_line.mid(&first_line);
let mid = mid_line.project(dist);
let mid_left = Line {
point: mid,
angle: mid_line.angle + std::f32::consts::FRAC_PI_2,
};
let mid_right = Line {
point: mid,
angle: mid_line.angle - std::f32::consts::FRAC_PI_2,
};
self.curves.push(Bezier::Cubic([
last_line.point,
last_line.project(math::arc_constant(std::f32::consts::FRAC_PI_2) * dist),
mid_left.project(math::arc_constant(std::f32::consts::FRAC_PI_2) * dist),
mid,
]));
self.curves.push(Bezier::Cubic([
mid,
mid_right.project(math::arc_constant(std::f32::consts::FRAC_PI_2) * dist),
first_line.project(math::arc_constant(std::f32::consts::FRAC_PI_2) * dist),
first_line.point,
]));
}
}
}
pub fn new(curves: &[Bezier], is_closed: bool, style: &StrokeStyle) -> Option<Self> {
if curves.is_empty() {
return None;
}
let mut outline = Self {
curves: Vec::new(),
second_outline_index: None,
};
let dist = style.thickness / 2.0;
if !is_closed {
outline.join_curves(
curves
.iter()
.filter_map(Bezier::normalize)
.map(|curve| curve.offset(dist)),
dist,
style.join,
is_closed,
);
let mut flipside_curves = curves
.iter()
.rev()
.filter_map(Bezier::normalize)
.map(|curve| curve.offset(-dist))
.peekable();
let (last_line, first_line) = outline.last_first_line(&flipside_curves.peek().unwrap());
outline.cap_end(&last_line, &first_line, dist, style.cap);
outline.join_curves(flipside_curves, dist, style.join, is_closed);
let (last_line, first_line) = outline.last_first_line(&outline.curves);
outline.cap_end(&last_line, &first_line, dist, style.cap);
} else {
outline.join_curves(
curves
.iter()
.filter_map(Bezier::normalize)
.map(|curve| curve.offset(dist)),
dist,
style.join,
is_closed,
);
outline.second_outline_index = Some(outline.curves.len());
outline.join_curves(
curves
.iter()
.rev()
.filter_map(Bezier::normalize)
.map(|curve| curve.offset(-dist)),
dist,
style.join,
is_closed,
);
}
Some(outline)
}
pub fn as_commands(&self) -> impl Iterator<Item = Command> + '_ {
let mid_move = self
.second_outline_index
.map(|i| Command::MoveTo(self.curves[i].points()[0]));
let as_commands = |curve: &Bezier| match *curve {
Bezier::Line([_, p1]) => Command::LineTo(p1),
Bezier::Cubic([_, p1, p2, p3]) => Command::CubicTo(p1, p2, p3),
};
iter::once(Command::MoveTo(self.curves[0].points()[0]))
.chain(
self.curves[..self.second_outline_index.unwrap_or_default()]
.iter()
.map(as_commands),
)
.chain(self.second_outline_index.map(|_| Command::Close))
.chain(mid_move)
.chain(
self.curves[self.second_outline_index.unwrap_or_default()..]
.iter()
.map(as_commands),
)
.chain(iter::once(Command::Close))
}
}
| 32.851016 | 100 | 0.465952 |
4a1d151e963f3e9b73fe97636c1f3ce2c5443df7 | 12,265 | use std::fs;
use itertools::Itertools;
use std::cmp::{max, min};
#[derive(Debug, PartialEq, Clone)]
enum PointAxisTranslation {
Up(i64),
Right(i64),
Down(i64),
Left(i64),
}
impl PointAxisTranslation {
fn from_str(raw: &str) -> Option<Self> {
let mut chars_iter = raw.chars();
let direction = match chars_iter.next() {
None => return None,
Some(c) => c,
};
let value_str: String = chars_iter.collect();
let value = value_str.parse::<i64>();
match value {
Err(_) => None,
Ok(val) => match direction {
'U' => Some(PointAxisTranslation::Up(val)),
'R' => Some(PointAxisTranslation::Right(val)),
'D' => Some(PointAxisTranslation::Down(val)),
'L' => Some(PointAxisTranslation::Left(val)),
_ => None,
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i64,
y: i64,
}
impl Point {
#[allow(dead_code)]
fn new(x: i64, y: i64) -> Self {
Point { x, y }
}
fn translate_on_axis(&self, translation: PointAxisTranslation) -> Self {
match translation {
PointAxisTranslation::Up(val) => Point {
x: self.x,
y: self.y + val,
},
PointAxisTranslation::Right(val) => Point {
x: self.x + val,
y: self.y,
},
PointAxisTranslation::Down(val) => Point {
x: self.x,
y: self.y - val,
},
PointAxisTranslation::Left(val) => Point {
x: self.x - val,
y: self.y,
},
}
}
fn origin() -> Self {
Point { x: 0, y: 0 }
}
fn manhattan_distance_to_origin(&self) -> i64 {
self.x.abs() + self.y.abs()
}
fn distance_to(&self, other: Self) -> i64 {
(self.x - other.x).abs() + (self.y - other.y).abs()
}
// Note: this method assumes that we already determined the point is an actual intersection
// so that it's guaranteed to be collinear
fn is_on_segment(&self, segment: &WireSegment) -> bool {
let r1 = min(segment.start.x, segment.end.x)..=max(segment.start.x, segment.end.x);
let r2 = min(segment.start.y, segment.end.y)..=max(segment.start.y, segment.end.y);
r1.contains(&self.x) && r2.contains(&self.y)
}
}
#[derive(Debug, Clone)]
struct WireSegment {
start: Point,
end: Point,
}
impl WireSegment {
fn new(start: Point, end: Point) -> Self {
WireSegment { start, end }
}
fn len(&self) -> i64 {
self.start.distance_to(self.end)
}
fn intersection(&self, other: &Self) -> Option<Point> {
let a1 = self.end.y - self.start.y;
let b1 = self.start.x - self.end.x;
let c1 = a1 * self.start.x + b1 * self.start.y;
let a2 = other.end.y - other.start.y;
let b2 = other.start.x - other.end.x;
let c2 = a2 * other.start.x + b2 * other.start.y;
let delta = a1 * b2 - a2 * b1;
match delta {
0 => None,
_ => {
let potential_intersection = Point {
x: (b2 * c1 - b1 * c2) / delta,
y: (a1 * c2 - a2 * c1) / delta,
};
if potential_intersection.is_on_segment(self)
&& potential_intersection.is_on_segment(other)
{
Some(potential_intersection)
} else {
None
}
}
}
}
}
#[derive(Clone)]
struct Wire {
segments: Vec<WireSegment>,
}
impl Wire {
fn new_from_raw(raw_str: &str) -> Self {
let origin = Point::origin();
let points: Vec<_> = vec![origin] // we need to start our sequence with the origin
.into_iter()
.chain(
raw_str
.split(',')
.map(|s| PointAxisTranslation::from_str(s).unwrap()) // if it panics during unwrap it means we got invalid input so there's nothing sensible we can do anyway
.scan(origin, |curr_point, translation| {
let new_point = curr_point.translate_on_axis(translation);
*curr_point = new_point;
// TODO: unnecessary copy
Some(new_point)
}),
)
.collect();
let segments = points
.into_iter()
.tuple_windows()
.map(|(p1, p2)| WireSegment::new(p1, p2))
.collect();
Self { segments }
}
fn retrace_steps(&self, point: &Point) -> i64 {
// while not on segment, add segment len
// then if on segment, add distance from seg start to point
let intersection_segment_index = self
.segments
.iter()
.position(|seg| point.is_on_segment(seg))
.unwrap(); // if it panics, something weird must have happened...
let full_segments_distance: i64 = self
.segments
.iter()
.take(intersection_segment_index)
.map(|seg| seg.len())
.sum();
full_segments_distance + point.distance_to(self.segments[intersection_segment_index].start)
}
fn all_intersections(&self, other: &Self) -> Vec<Point> {
self.segments
.iter()
.flat_map(|w1_seg| other.segments.iter().map(move |w2_seg| (w1_seg, w2_seg)))
.filter_map(|(w1_seg, w2_seg)| w1_seg.intersection(w2_seg))
.collect()
}
fn closest_intersection_to_origin(&self, other: &Self) -> Point {
// all intersections
let origin = Point::origin();
self.all_intersections(other)
.into_iter()
.filter(|p| p != &origin) // we don't want origin itself
.map(|p| (p, p.manhattan_distance_to_origin()))
.min_by(|(_, d1), (_, d2)| d1.cmp(d2))
.unwrap()
.0
// we don't care about distance itself, only the coordinates
}
fn least_step_intersection_distance(&self, other: &Self) -> i64 {
// all intersections
let origin = Point::origin();
self.all_intersections(other)
.into_iter()
.filter(|p| p != &origin) // we don't want origin itself
.map(|p| self.retrace_steps(&p) + other.retrace_steps(&p))
.min()
.unwrap()
}
}
fn do_part1(input_wires: Vec<Wire>) {
assert_eq!(2, input_wires.len()); // as per specs
let closest_intersection_dist = input_wires[0]
.closest_intersection_to_origin(&input_wires[1])
.manhattan_distance_to_origin();
println!("Part 1 answer: {}", closest_intersection_dist);
}
fn do_part2(input_wires: Vec<Wire>) {
assert_eq!(2, input_wires.len()); // as per specs
let least_steps = input_wires[0].least_step_intersection_distance(&input_wires[1]);
println!("Part 2 answer: {}", least_steps);
}
fn read_input_file(path: &str) -> Vec<Wire> {
fs::read_to_string(path)
.unwrap()
.split('\n')
.map(|s| Wire::new_from_raw(s))
.collect()
}
fn main() {
let wires = read_input_file("day3.input");
do_part1(wires.clone());
do_part2(wires);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_correctly_determines_closest_intersection_for_first_input() {
let wire1 = Wire::new_from_raw("R8,U5,L5,D3");
let wire2 = Wire::new_from_raw("U7,R6,D4,L4");
assert_eq!(
6,
wire1
.closest_intersection_to_origin(&wire2)
.manhattan_distance_to_origin()
)
}
#[test]
fn it_correctly_determines_closest_intersection_for_second_input() {
let wire1 = Wire::new_from_raw("R75,D30,R83,U83,L12,D49,R71,U7,L72");
let wire2 = Wire::new_from_raw("U62,R66,U55,R34,D71,R55,D58,R83");
assert_eq!(
159,
wire1
.closest_intersection_to_origin(&wire2)
.manhattan_distance_to_origin()
)
}
#[test]
fn it_correctly_determines_closest_intersection_for_third_input() {
let wire1 = Wire::new_from_raw("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51");
let wire2 = Wire::new_from_raw("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7");
assert_eq!(
135,
wire1
.closest_intersection_to_origin(&wire2)
.manhattan_distance_to_origin()
)
}
#[test]
fn it_correctly_determines_closest_intersection_steps_for_first_input() {
let wire1 = Wire::new_from_raw("R8,U5,L5,D3");
let wire2 = Wire::new_from_raw("U7,R6,D4,L4");
assert_eq!(30, wire1.least_step_intersection_distance(&wire2))
}
#[test]
fn it_correctly_determines_closest_intersection_steps_for_second_input() {
let wire1 = Wire::new_from_raw("R75,D30,R83,U83,L12,D49,R71,U7,L72");
let wire2 = Wire::new_from_raw("U62,R66,U55,R34,D71,R55,D58,R83");
assert_eq!(610, wire1.least_step_intersection_distance(&wire2))
}
#[test]
fn it_correctly_determines_closest_intersection_steps_for_third_input() {
let wire1 = Wire::new_from_raw("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51");
let wire2 = Wire::new_from_raw("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7");
assert_eq!(410, wire1.least_step_intersection_distance(&wire2))
}
#[cfg(test)]
mod segment_intersection {
use super::*;
#[test]
fn it_correctly_detects_intersection() {
let l1 = WireSegment::new(Point::new(4, 0), Point::new(6, 10));
let l2 = WireSegment::new(Point::new(0, 3), Point::new(10, 7));
assert_eq!(Point::new(5, 5), l1.intersection(&l2).unwrap())
}
#[test]
fn it_correctly_detects_no_intersection() {
let l1 = WireSegment::new(Point::new(0, 0), Point::new(1, 1));
let l2 = WireSegment::new(Point::new(1, 2), Point::new(4, 5));
assert_eq!(None, l1.intersection(&l2))
}
#[test]
fn it_correctly_detects_no_intersection_for_parallel_lines() {
let l1 = WireSegment::new(Point::new(0, 0), Point::new(1, 1));
let l2 = WireSegment::new(Point::new(0, 1), Point::new(1, 2));
assert_eq!(None, l1.intersection(&l2))
}
#[test]
fn it_correctly_detects_no_intersection_outside_segments_even_if_infinite_lines_would_have_intersected(
) {
let l1 = WireSegment::new(Point::new(0, 0), Point::new(1, 1));
let l2 = WireSegment::new(Point::new(2, 3), Point::new(3, 2));
assert_eq!(None, l1.intersection(&l2))
}
}
#[cfg(test)]
mod point_axis_translation {
use super::*;
#[test]
fn it_returns_valid_up_translation() {
assert_eq!(
PointAxisTranslation::Up(10),
PointAxisTranslation::from_str("U10").unwrap()
);
}
#[test]
fn it_returns_valid_right_translation() {
assert_eq!(
PointAxisTranslation::Right(10),
PointAxisTranslation::from_str("R10").unwrap()
);
}
#[test]
fn it_returns_valid_down_translation() {
assert_eq!(
PointAxisTranslation::Down(10),
PointAxisTranslation::from_str("D10").unwrap()
);
}
#[test]
fn it_returns_valid_left_translation() {
assert_eq!(
PointAxisTranslation::Left(10),
PointAxisTranslation::from_str("L10").unwrap()
);
}
#[test]
fn it_returns_none_for_invalid_translations() {
if let Some(_) = PointAxisTranslation::from_str("Z10") {
panic!("expected nothing!")
}
if let Some(_) = PointAxisTranslation::from_str("Z1Y0") {
panic!("expected nothing!")
}
}
}
}
| 30.894207 | 177 | 0.54309 |
729eadc5553bafa96cd686e19fd3407591e317bc | 15,230 | //! Polling API bindings
use crate::reactor::platform;
use crate::reactor::registration::Registration;
use futures::io::{AsyncRead, AsyncWrite};
use futures::task::Waker;
use futures::{ready, Poll};
use mio;
use mio::event::Evented;
use std::fmt;
use std::io::{self, Read, Write};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::Relaxed;
/// Associates an I/O resource that implements the [`std::io::Read`] and/or
/// [`std::io::Write`] traits with the reactor that drives it.
///
/// `PollEvented` uses [`Registration`] internally to take a type that
/// implements [`mio::Evented`] as well as [`std::io::Read`] and or
/// [`std::io::Write`] and associate it with a reactor that will drive it.
///
/// Once the [`mio::Evented`] type is wrapped by `PollEvented`, it can be
/// used from within the future's execution model. As such, the `PollEvented`
/// type provides [`AsyncRead`] and [`AsyncWrite`] implementations using the
/// underlying I/O resource as well as readiness events provided by the reactor.
///
/// **Note**: While `PollEvented` is `Sync` (if the underlying I/O type is
/// `Sync`), the caller must ensure that there are at most two tasks that use a
/// `PollEvented` instance concurrently. One for reading and one for writing.
/// While violating this requirement is "safe" from a Rust memory model point of
/// view, it will result in unexpected behavior in the form of lost
/// notifications and tasks hanging.
///
/// ## Readiness events
///
/// Besides just providing [`AsyncRead`] and [`AsyncWrite`] implementations,
/// this type also supports access to the underlying readiness event stream.
/// While similar in function to what [`Registration`] provides, the semantics
/// are a bit different.
///
/// Two functions are provided to access the readiness events:
/// [`poll_read_ready`] and [`poll_write_ready`]. These functions return the
/// current readiness state of the `PollEvented` instance. If
/// [`poll_read_ready`] indicates read readiness, immediately calling
/// [`poll_read_ready`] again will also indicate read readiness.
///
/// When the operation is attempted and is unable to succeed due to the I/O
/// resource not being ready, the caller must call [`clear_read_ready`] or
/// [`clear_write_ready`]. This clears the readiness state until a new readiness
/// event is received.
///
/// This allows the caller to implement additional functions. For example,
/// [`TcpListener`] implements poll_accept by using [`poll_read_ready`] and
/// [`clear_read_ready`].
///
/// ```rust,ignore
/// pub fn poll_accept(&mut self) -> Poll<(net::TcpStream, SocketAddr), io::Error> {
/// let ready = Ready::readable();
///
/// try_ready!(self.poll_evented.poll_read_ready(ready));
///
/// match self.poll_evented.get_ref().accept_std() {
/// Ok(pair) => Ok(Async::Ready(pair)),
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// self.poll_evented.clear_read_ready(ready);
/// Ok(Async::NotReady)
/// }
/// Err(e) => Err(e),
/// }
/// }
/// ```
///
/// ## Platform-specific events
///
/// `PollEvented` also allows receiving platform-specific `mio::Ready` events.
/// These events are included as part of the read readiness event stream. The
/// write readiness event stream is only for `Ready::writable()` events.
///
/// [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
/// [`std::io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
/// [`AsyncRead`]: ../io/trait.AsyncRead.html
/// [`AsyncWrite`]: ../io/trait.AsyncWrite.html
/// [`mio::Evented`]: https://docs.rs/mio/0.6/mio/trait.Evented.html
/// [`Registration`]: struct.Registration.html
/// [`TcpListener`]: ../net/struct.TcpListener.html
/// [`clear_read_ready`]: #method.clear_read_ready
/// [`clear_write_ready`]: #method.clear_write_ready
/// [`poll_read_ready`]: #method.poll_read_ready
/// [`poll_write_ready`]: #method.poll_write_ready
pub struct PollEvented<E: Evented> {
io: Option<E>,
inner: Inner,
}
struct Inner {
registration: Registration,
/// Currently visible read readiness
read_readiness: AtomicUsize,
/// Currently visible write readiness
write_readiness: AtomicUsize,
}
// ===== impl PollEvented =====
impl<E> PollEvented<E>
where
E: Evented,
{
/// Creates a new `PollEvented` associated with the default reactor.
pub fn new(io: E) -> PollEvented<E> {
PollEvented {
io: Some(io),
inner: Inner {
registration: Registration::new(),
read_readiness: AtomicUsize::new(0),
write_readiness: AtomicUsize::new(0),
},
}
}
/// Returns a shared reference to the underlying I/O object this readiness
/// stream is wrapping.
pub fn get_ref(&self) -> &E {
self.io.as_ref().unwrap()
}
/// Returns a mutable reference to the underlying I/O object this readiness
/// stream is wrapping.
pub fn get_mut(&mut self) -> &mut E {
self.io.as_mut().unwrap()
}
// TODO: restore this once we make reactor::poll_evented public
// /// Consumes self, returning the inner I/O object
// ///
// /// This function will deregister the I/O resource from the reactor before
// /// returning. If the deregistration operation fails, an error is returned.
// ///
// /// Note that deregistering does not guarantee that the I/O resource can be
// /// registered with a different reactor. Some I/O resource types can only be
// /// associated with a single reactor instance for their lifetime.
// pub fn into_inner(mut self) -> io::Result<E> {
// let io = self.io.take().unwrap();
// self.inner.registration.deregister(&io)?;
// Ok(io)
// }
/// Check the I/O resource's read readiness state.
///
/// The mask argument allows specifying what readiness to notify on. This
/// can be any value, including platform specific readiness, **except**
/// `writable`. HUP is always implicitly included on platforms that support
/// it.
///
/// If the resource is not ready for a read then `Async::NotReady` is
/// returned and the current task is notified once a new event is received.
///
/// The I/O resource will remain in a read-ready state until readiness is
/// cleared by calling [`clear_read_ready`].
///
/// [`clear_read_ready`]: #method.clear_read_ready
pub fn poll_read_ready(&self, waker: &Waker) -> Poll<io::Result<mio::Ready>> {
self.register()?;
// Load cached & encoded readiness.
let mut cached = self.inner.read_readiness.load(Relaxed);
let mask = mio::Ready::readable() | platform::hup();
// See if the current readiness matches any bits.
let mut ret = mio::Ready::from_usize(cached) & mio::Ready::readable();
if ret.is_empty() {
// Readiness does not match, consume the registration's readiness
// stream. This happens in a loop to ensure that the stream gets
// drained.
loop {
let ready = ready!(self.inner.registration.poll_read_ready(waker)?);
cached |= ready.as_usize();
// Update the cache store
self.inner.read_readiness.store(cached, Relaxed);
ret |= ready & mask;
if !ret.is_empty() {
return Poll::Ready(Ok(ret));
}
}
} else {
// Check what's new with the registration stream. This will not
// request to be notified
if let Some(ready) = self.inner.registration.take_read_ready()? {
cached |= ready.as_usize();
self.inner.read_readiness.store(cached, Relaxed);
}
Poll::Ready(Ok(mio::Ready::from_usize(cached)))
}
}
/// Clears the I/O resource's read readiness state and registers the current
/// task to be notified once a read readiness event is received.
///
/// After calling this function, `poll_read_ready` will return `NotReady`
/// until a new read readiness event has been received.
///
/// The `mask` argument specifies the readiness bits to clear. This may not
/// include `writable` or `hup`.
pub fn clear_read_ready(&self, waker: &Waker) -> io::Result<()> {
self.inner
.read_readiness
.fetch_and(!mio::Ready::readable().as_usize(), Relaxed);
if self.poll_read_ready(waker)?.is_ready() {
// Notify the current task
waker.wake();
}
Ok(())
}
/// Check the I/O resource's write readiness state.
///
/// This always checks for writable readiness and also checks for HUP
/// readiness on platforms that support it.
///
/// If the resource is not ready for a write then `Async::NotReady` is
/// returned and the current task is notified once a new event is received.
///
/// The I/O resource will remain in a write-ready state until readiness is
/// cleared by calling [`clear_write_ready`].
///
/// [`clear_write_ready`]: #method.clear_write_ready
///
/// # Panics
///
/// This function panics if:
///
/// * `ready` contains bits besides `writable` and `hup`.
/// * called from outside of a task context.
pub fn poll_write_ready(&self, waker: &Waker) -> Poll<Result<mio::Ready, io::Error>> {
self.register()?;
// Load cached & encoded readiness.
let mut cached = self.inner.write_readiness.load(Relaxed);
let mask = mio::Ready::writable() | platform::hup();
// See if the current readiness matches any bits.
let mut ret = mio::Ready::from_usize(cached) & mio::Ready::writable();
if ret.is_empty() {
// Readiness does not match, consume the registration's readiness
// stream. This happens in a loop to ensure that the stream gets
// drained.
loop {
let ready = ready!(self.inner.registration.poll_write_ready(waker)?);
cached |= ready.as_usize();
// Update the cache store
self.inner.write_readiness.store(cached, Relaxed);
ret |= ready & mask;
if !ret.is_empty() {
return Poll::Ready(Ok(ret));
}
}
} else {
// Check what's new with the registration stream. This will not
// request to be notified
if let Some(ready) = self.inner.registration.take_write_ready()? {
cached |= ready.as_usize();
self.inner.write_readiness.store(cached, Relaxed);
}
Poll::Ready(Ok(mio::Ready::from_usize(cached)))
}
}
/// Resets the I/O resource's write readiness state and registers the current
/// task to be notified once a write readiness event is received.
///
/// This only clears writable readiness. HUP (on platforms that support HUP)
/// cannot be cleared as it is a final state.
///
/// After calling this function, `poll_write_ready(Ready::writable())` will
/// return `NotReady` until a new write readiness event has been received.
///
/// # Panics
///
/// This function will panic if called from outside of a task context.
pub fn clear_write_ready(&self, waker: &Waker) -> io::Result<()> {
self.inner
.write_readiness
.fetch_and(!mio::Ready::writable().as_usize(), Relaxed);
if self.poll_write_ready(waker)?.is_ready() {
// Notify the current task
waker.wake();
}
Ok(())
}
/// Ensure that the I/O resource is registered with the reactor.
fn register(&self) -> io::Result<()> {
self.inner
.registration
.register(self.io.as_ref().unwrap())?;
Ok(())
}
}
// ===== AsyncRead / AsyncWrite impls =====
impl<E> AsyncRead for PollEvented<E>
where
E: Evented + Read,
{
fn poll_read(&mut self, waker: &Waker, buf: &mut [u8]) -> Poll<io::Result<usize>> {
ready!(self.poll_read_ready(waker)?);
let r = self.get_mut().read(buf);
if is_wouldblock(&r) {
self.clear_read_ready(waker)?;
Poll::Pending
} else {
Poll::Ready(r)
}
}
}
impl<E> AsyncWrite for PollEvented<E>
where
E: Evented + Write,
{
fn poll_write(&mut self, waker: &Waker, buf: &[u8]) -> Poll<io::Result<usize>> {
ready!(self.poll_write_ready(waker)?);
let r = self.get_mut().write(buf);
if is_wouldblock(&r) {
self.clear_write_ready(waker)?;
Poll::Pending
} else {
Poll::Ready(r)
}
}
fn poll_flush(&mut self, waker: &Waker) -> Poll<io::Result<()>> {
ready!(self.poll_write_ready(waker)?);
let r = self.get_mut().flush();
if is_wouldblock(&r) {
self.clear_write_ready(waker)?;
Poll::Pending
} else {
Poll::Ready(r)
}
}
fn poll_close(&mut self, _: &Waker) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
// ===== &'a AsyncRead / &'a AsyncWrite impls =====
impl<'a, E> AsyncRead for &'a PollEvented<E>
where
E: Evented,
&'a E: Read,
{
fn poll_read(&mut self, waker: &Waker, buf: &mut [u8]) -> Poll<io::Result<usize>> {
ready!(self.poll_read_ready(waker)?);
let r = self.get_ref().read(buf);
if is_wouldblock(&r) {
self.clear_read_ready(waker)?;
Poll::Pending
} else {
Poll::Ready(r)
}
}
}
impl<'a, E> AsyncWrite for &'a PollEvented<E>
where
E: Evented,
&'a E: Write,
{
fn poll_write(&mut self, waker: &Waker, buf: &[u8]) -> Poll<io::Result<usize>> {
ready!(self.poll_write_ready(waker)?);
let r = self.get_ref().write(buf);
if is_wouldblock(&r) {
self.clear_write_ready(waker)?;
Poll::Pending
} else {
Poll::Ready(r)
}
}
fn poll_flush(&mut self, waker: &Waker) -> Poll<io::Result<()>> {
ready!(self.poll_write_ready(waker)?);
let r = self.get_ref().flush();
if is_wouldblock(&r) {
self.clear_write_ready(waker)?;
Poll::Pending
} else {
Poll::Ready(r)
}
}
fn poll_close(&mut self, _: &Waker) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
fn is_wouldblock<T>(r: &io::Result<T>) -> bool {
match *r {
Ok(_) => false,
Err(ref e) => e.kind() == io::ErrorKind::WouldBlock,
}
}
impl<E: Evented + fmt::Debug> fmt::Debug for PollEvented<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PollEvented").field("io", &self.io).finish()
}
}
impl<E: Evented> Drop for PollEvented<E> {
fn drop(&mut self) {
if let Some(io) = self.io.take() {
// Ignore errors
let _ = self.inner.registration.deregister(&io);
}
}
}
| 33.769401 | 90 | 0.597308 |
8af4dae0dad4556d87e41262bbd4810a68b0e28d | 2,844 | // Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use canonical_serialization::SimpleSerializer;
use failure::prelude::*;
use libra_types::{
account_config::{account_struct_tag, AccountResource},
language_storage::StructTag,
};
use vm_runtime_types::{
loaded_data::{struct_def::StructDef, types::Type},
value::{Struct, Value},
};
/// resolve StructDef by StructTag.
pub trait StructDefResolve {
fn resolve(&self, tag: &StructTag) -> Result<StructDef>;
}
#[derive(Clone, Debug)]
pub struct Resource(StructTag, Struct);
impl Resource {
pub fn new(tag: StructTag, value: Struct) -> Self {
Self(tag, value)
}
pub fn tag(&self) -> &StructTag {
&self.0
}
pub fn new_from_account_resource(account_resource: AccountResource) -> Self {
//this serialize and decode should never fail, so use unwrap.
let out: Vec<u8> = SimpleSerializer::serialize(&account_resource).unwrap();
Self::decode(account_struct_tag(), get_account_struct_def(), &out).expect("decode fail.")
}
pub fn decode(tag: StructTag, def: StructDef, bytes: &[u8]) -> Result<Self> {
let struct_value = Value::simple_deserialize(bytes, def)
.map_err(|vm_error| format_err!("decode resource fail:{:?}", vm_error))
.and_then(|value| {
value
.value_as()
.ok_or(format_err!("value is not struct type"))
})?;
Ok(Self::new(tag, struct_value))
}
pub fn encode(&self) -> Vec<u8> {
Into::<Value>::into(self)
.simple_serialize()
.expect("serialize should not fail.")
}
}
impl Into<Value> for Resource {
fn into(self) -> Value {
Value::struct_(self.1)
}
}
impl Into<Value> for &Resource {
fn into(self) -> Value {
self.clone().into()
}
}
impl std::cmp::PartialEq for Resource {
fn eq(&self, other: &Self) -> bool {
//TODO optimize
self.encode() == other.encode()
}
}
impl Into<(StructTag, Struct)> for Resource {
fn into(self) -> (StructTag, Struct) {
(self.0, self.1)
}
}
pub fn get_account_struct_def() -> StructDef {
let int_type = Type::U64;
let byte_array_type = Type::ByteArray;
let coin = Type::Struct(get_coin_struct_def());
let event_handle = Type::Struct(get_event_handle_struct_def());
StructDef::new(vec![
byte_array_type,
coin,
Type::Bool,
Type::Bool,
event_handle.clone(),
event_handle.clone(),
int_type.clone(),
])
}
pub fn get_coin_struct_def() -> StructDef {
let int_type = Type::U64;
StructDef::new(vec![int_type.clone()])
}
pub fn get_event_handle_struct_def() -> StructDef {
StructDef::new(vec![Type::U64, Type::ByteArray])
}
| 26.579439 | 97 | 0.615331 |
fc016c83923156326ada1403eceb81f3e2b9b482 | 32,483 | use std::iter;
use cgmath::prelude::*;
use wgpu::util::DeviceExt;
use winit::{
event::*,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
mod texture;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
position: [f32; 3],
tex_coords: [f32; 2],
}
impl Vertex {
fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
use std::mem;
wgpu::VertexBufferLayout {
array_stride: mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x2,
},
],
}
}
}
const VERTICES: &[Vertex] = &[
Vertex {
position: [-0.0868241, -0.49240386, 0.0],
tex_coords: [1.0 - 0.4131759, 1.0 - 0.00759614],
}, // A
Vertex {
position: [-0.49513406, -0.06958647, 0.0],
tex_coords: [1.0 - 0.0048659444, 1.0 - 0.43041354],
}, // B
Vertex {
position: [-0.21918549, 0.44939706, 0.0],
tex_coords: [1.0 - 0.28081453, 1.0 - 0.949397],
}, // C
Vertex {
position: [0.35966998, 0.3473291, 0.0],
tex_coords: [1.0 - 0.85967, 1.0 - 0.84732914],
}, // D
Vertex {
position: [0.44147372, -0.2347359, 0.0],
tex_coords: [1.0 - 0.9414737, 1.0 - 0.2652641],
}, // E
];
const INDICES: &[u16] = &[0, 1, 4, 1, 2, 4, 2, 3, 4];
const DEPTH_VERTICES: &[Vertex] = &[
Vertex {
position: [0.0, 0.0, 0.0],
tex_coords: [0.0, 1.0],
},
Vertex {
position: [1.0, 0.0, 0.0],
tex_coords: [1.0, 1.0],
},
Vertex {
position: [1.0, 1.0, 0.0],
tex_coords: [1.0, 0.0],
},
Vertex {
position: [0.0, 1.0, 0.0],
tex_coords: [0.0, 0.0],
},
];
const DEPTH_INDICES: &[u16] = &[0, 1, 2, 0, 2, 3];
#[rustfmt::skip]
pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4<f32> = cgmath::Matrix4::new(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.0, 0.0, 0.5, 1.0,
);
const NUM_INSTANCES_PER_ROW: u32 = 10;
const INSTANCE_DISPLACEMENT: cgmath::Vector3<f32> = cgmath::Vector3::new(
NUM_INSTANCES_PER_ROW as f32 * 0.5,
0.0,
NUM_INSTANCES_PER_ROW as f32 * 0.5,
);
struct Camera {
eye: cgmath::Point3<f32>,
target: cgmath::Point3<f32>,
up: cgmath::Vector3<f32>,
aspect: f32,
fovy: f32,
znear: f32,
zfar: f32,
}
impl Camera {
fn build_view_projection_matrix(&self) -> cgmath::Matrix4<f32> {
let view = cgmath::Matrix4::look_at_rh(self.eye, self.target, self.up);
let proj = cgmath::perspective(cgmath::Deg(self.fovy), self.aspect, self.znear, self.zfar);
proj * view
}
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct CameraUniform {
view_proj: [[f32; 4]; 4],
}
impl CameraUniform {
fn new() -> Self {
Self {
view_proj: cgmath::Matrix4::identity().into(),
}
}
fn update_view_proj(&mut self, camera: &Camera) {
self.view_proj = (OPENGL_TO_WGPU_MATRIX * camera.build_view_projection_matrix()).into();
}
}
struct CameraController {
speed: f32,
is_forward_pressed: bool,
is_backward_pressed: bool,
is_left_pressed: bool,
is_right_pressed: bool,
}
impl CameraController {
fn new(speed: f32) -> Self {
Self {
speed,
is_forward_pressed: false,
is_backward_pressed: false,
is_left_pressed: false,
is_right_pressed: false,
}
}
fn process_events(&mut self, event: &WindowEvent) -> bool {
match event {
WindowEvent::KeyboardInput {
input:
KeyboardInput {
state,
virtual_keycode: Some(keycode),
..
},
..
} => {
let is_pressed = *state == ElementState::Pressed;
match keycode {
VirtualKeyCode::W | VirtualKeyCode::Up => {
self.is_forward_pressed = is_pressed;
true
}
VirtualKeyCode::A | VirtualKeyCode::Left => {
self.is_left_pressed = is_pressed;
true
}
VirtualKeyCode::S | VirtualKeyCode::Down => {
self.is_backward_pressed = is_pressed;
true
}
VirtualKeyCode::D | VirtualKeyCode::Right => {
self.is_right_pressed = is_pressed;
true
}
_ => false,
}
}
_ => false,
}
}
fn update_camera(&self, camera: &mut Camera) {
let forward = camera.target - camera.eye;
let forward_norm = forward.normalize();
let forward_mag = forward.magnitude();
// Prevents glitching when camera gets too close to the
// center of the scene.
if self.is_forward_pressed && forward_mag > self.speed {
camera.eye += forward_norm * self.speed;
}
if self.is_backward_pressed {
camera.eye -= forward_norm * self.speed;
}
let right = forward_norm.cross(camera.up);
// Redo radius calc in case the up/ down is pressed.
let forward = camera.target - camera.eye;
let forward_mag = forward.magnitude();
if self.is_right_pressed {
// Rescale the distance between the target and eye so
// that it doesn't change. The eye therefore still
// lies on the circle made by the target and eye.
camera.eye = camera.target - (forward + right * self.speed).normalize() * forward_mag;
}
if self.is_left_pressed {
camera.eye = camera.target - (forward - right * self.speed).normalize() * forward_mag;
}
}
}
struct Instance {
position: cgmath::Vector3<f32>,
rotation: cgmath::Quaternion<f32>,
}
impl Instance {
fn to_raw(&self) -> InstanceRaw {
InstanceRaw {
model: (cgmath::Matrix4::from_translation(self.position)
* cgmath::Matrix4::from(self.rotation))
.into(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct InstanceRaw {
model: [[f32; 4]; 4],
}
impl InstanceRaw {
fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
use std::mem;
wgpu::VertexBufferLayout {
array_stride: mem::size_of::<InstanceRaw>() as wgpu::BufferAddress,
// We need to switch from using a step mode of Vertex to Instance
// This means that our shaders will only change to use the next
// instance when the shader starts processing a new instance
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
// While our vertex shader only uses locations 0, and 1 now, in later tutorials we'll
// be using 2, 3, and 4, for Vertex. We'll start at slot 5 not conflict with them later
shader_location: 5,
format: wgpu::VertexFormat::Float32x4,
},
// A mat4 takes up 4 vertex slots as it is technically 4 vec4s. We need to define a slot
// for each vec4. We don't have to do this in code though.
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress,
shader_location: 6,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress,
shader_location: 7,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 12]>() as wgpu::BufferAddress,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
}
}
}
struct DepthPass {
texture: texture::Texture,
layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
num_depth_indices: u32,
render_pipeline: wgpu::RenderPipeline,
}
impl DepthPass {
fn new(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> Self {
let texture = texture::Texture::create_depth_texture(device, config, "depth_texture");
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Depth Pass Layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
count: None,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
},
visibility: wgpu::ShaderStages::FRAGMENT,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
count: None,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
visibility: wgpu::ShaderStages::FRAGMENT,
},
],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&texture.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&texture.sampler),
},
],
label: Some("depth_pass.bind_group"),
});
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Depth Pass VB"),
contents: bytemuck::cast_slice(DEPTH_VERTICES),
usage: wgpu::BufferUsages::VERTEX,
});
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Depth Pass IB"),
contents: bytemuck::cast_slice(DEPTH_INDICES),
usage: wgpu::BufferUsages::INDEX,
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Depth Pass Pipeline Layout"),
bind_group_layouts: &[&layout],
push_constant_ranges: &[],
});
let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
label: Some("Shadow Display Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("challenge.wgsl").into()),
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Depth Pass Render Pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[Vertex::desc()],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[wgpu::ColorTargetState {
format: config.format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent::REPLACE,
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
}],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
// Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE
polygon_mode: wgpu::PolygonMode::Fill,
// Requires Features::DEPTH_CLIP_CONTROL
unclipped_depth: false,
// Requires Features::CONSERVATIVE_RASTERIZATION
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
// If the pipeline will be used with a multiview render pass, this
// indicates how many array layers the attachments will have.
multiview: None,
});
Self {
texture,
layout,
bind_group,
vertex_buffer,
index_buffer,
num_depth_indices: DEPTH_INDICES.len() as u32,
render_pipeline,
}
}
fn resize(&mut self, device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) {
self.texture = texture::Texture::create_depth_texture(device, config, "depth_texture");
self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &self.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&self.texture.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.texture.sampler),
},
],
label: Some("depth_pass.bind_group"),
});
}
fn render(&self, view: &wgpu::TextureView, encoder: &mut wgpu::CommandEncoder) {
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Depth Visual Render Pass"),
color_attachments: &[wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: true,
},
}],
depth_stencil_attachment: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.bind_group, &[]);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
render_pass.draw_indexed(0..self.num_depth_indices, 0, 0..1);
}
}
struct State {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
num_indices: u32,
#[allow(dead_code)]
diffuse_texture: texture::Texture,
diffuse_bind_group: wgpu::BindGroup,
camera: Camera,
camera_controller: CameraController,
camera_uniform: CameraUniform,
camera_buffer: wgpu::Buffer,
camera_bind_group: wgpu::BindGroup,
size: winit::dpi::PhysicalSize<u32>,
instances: Vec<Instance>,
#[allow(dead_code)]
instance_buffer: wgpu::Buffer,
depth_pass: DepthPass,
}
impl State {
async fn new(window: &Window) -> Self {
let size = window.inner_size();
// The instance is a handle to our GPU
// BackendBit::PRIMARY => Vulkan + Metal + DX12 + Browser WebGPU
let instance = wgpu::Instance::new(wgpu::Backends::all());
let surface = unsafe { instance.create_surface(window) };
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
.await
.unwrap();
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: None,
features: wgpu::Features::empty(),
// WebGL doesn't support all of wgpu's features, so if
// we're building for the web we'll have to disable some.
limits: if cfg!(target_arch = "wasm32") {
wgpu::Limits::downlevel_webgl2_defaults()
} else {
wgpu::Limits::default()
},
},
None, // Trace path
)
.await
.unwrap();
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface.get_preferred_format(&adapter).unwrap(),
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
};
surface.configure(&device, &config);
let diffuse_bytes = include_bytes!("happy-tree.png");
let diffuse_texture =
texture::Texture::from_bytes(&device, &queue, diffuse_bytes, "happy-tree.png").unwrap();
let texture_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
label: Some("texture_bind_group_layout"),
});
let diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &texture_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&diffuse_texture.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&diffuse_texture.sampler),
},
],
label: Some("diffuse_bind_group"),
});
let camera = Camera {
eye: (0.0, 5.0, -10.0).into(),
target: (0.0, 0.0, 0.0).into(),
up: cgmath::Vector3::unit_y(),
aspect: config.width as f32 / config.height as f32,
fovy: 45.0,
znear: 0.1,
zfar: 100.0,
};
let camera_controller = CameraController::new(0.2);
let mut camera_uniform = CameraUniform::new();
camera_uniform.update_view_proj(&camera);
let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Camera Buffer"),
contents: bytemuck::cast_slice(&[camera_uniform]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let instances = (0..NUM_INSTANCES_PER_ROW)
.flat_map(|z| {
(0..NUM_INSTANCES_PER_ROW).map(move |x| {
let position = cgmath::Vector3 {
x: x as f32,
y: 0.0,
z: z as f32,
} - INSTANCE_DISPLACEMENT;
let rotation = if position.is_zero() {
// this is needed so an object at (0, 0, 0) won't get scaled to zero
// as Quaternions can effect scale if they're not create correctly
cgmath::Quaternion::from_axis_angle(
cgmath::Vector3::unit_z(),
cgmath::Deg(0.0),
)
} else {
cgmath::Quaternion::from_axis_angle(position.normalize(), cgmath::Deg(45.0))
};
Instance { position, rotation }
})
})
.collect::<Vec<_>>();
let instance_data = instances.iter().map(Instance::to_raw).collect::<Vec<_>>();
let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Instance Buffer"),
contents: bytemuck::cast_slice(&instance_data),
usage: wgpu::BufferUsages::VERTEX,
});
let camera_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
label: Some("camera_bind_group_layout"),
});
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &camera_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: camera_buffer.as_entire_binding(),
}],
label: Some("camera_bind_group"),
});
let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
});
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[&texture_bind_group_layout, &camera_bind_group_layout],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[Vertex::desc(), InstanceRaw::desc()],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[wgpu::ColorTargetState {
format: config.format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent::REPLACE,
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
}],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
// Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE
polygon_mode: wgpu::PolygonMode::Fill,
// Requires Features::DEPTH_CLIP_CONTROL
unclipped_depth: false,
// Requires Features::CONSERVATIVE_RASTERIZATION
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: texture::Texture::DEPTH_FORMAT,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::Less,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState {
constant: 2, // Corresponds to bilinear filtering
slope_scale: 2.0,
clamp: 0.0,
},
}),
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
// If the pipeline will be used with a multiview render pass, this
// indicates how many array layers the attachments will have.
multiview: None,
});
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex Buffer"),
contents: bytemuck::cast_slice(VERTICES),
usage: wgpu::BufferUsages::VERTEX,
});
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Index Buffer"),
contents: bytemuck::cast_slice(INDICES),
usage: wgpu::BufferUsages::INDEX,
});
let num_indices = INDICES.len() as u32;
let depth_pass = DepthPass::new(&device, &config);
Self {
surface,
device,
queue,
config,
render_pipeline,
vertex_buffer,
index_buffer,
num_indices,
diffuse_texture,
diffuse_bind_group,
camera,
camera_controller,
camera_buffer,
camera_bind_group,
camera_uniform,
size,
instances,
instance_buffer,
depth_pass,
}
}
pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
if new_size.width > 0 && new_size.height > 0 {
self.size = new_size;
self.config.width = new_size.width;
self.config.height = new_size.height;
self.surface.configure(&self.device, &self.config);
self.depth_pass.resize(&self.device, &self.config);
self.camera.aspect = self.config.width as f32 / self.config.height as f32;
}
}
fn input(&mut self, event: &WindowEvent) -> bool {
self.camera_controller.process_events(event)
}
fn update(&mut self) {
self.camera_controller.update_camera(&mut self.camera);
self.camera_uniform.update_view_proj(&self.camera);
self.queue.write_buffer(
&self.camera_buffer,
0,
bytemuck::cast_slice(&[self.camera_uniform]),
);
}
fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
let output = self.surface.get_current_texture()?;
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
{
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
}),
store: true,
},
}],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_pass.texture.view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: true,
}),
stencil_ops: None,
}),
});
render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]);
render_pass.set_bind_group(1, &self.camera_bind_group, &[]);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
render_pass.draw_indexed(0..self.num_indices, 0, 0..self.instances.len() as u32);
}
self.depth_pass.render(&view, &mut encoder);
self.queue.submit(iter::once(encoder.finish()));
output.present();
Ok(())
}
}
fn main() {
pollster::block_on(run());
}
async fn run() {
env_logger::init();
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
// State::new uses async code, so we're going to wait for it to finish
let mut state = State::new(&window).await;
event_loop.run(move |event, _, control_flow| {
match event {
Event::WindowEvent {
ref event,
window_id,
} if window_id == window.id() => {
if !state.input(event) {
match event {
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
input:
KeyboardInput {
state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Escape),
..
},
..
} => *control_flow = ControlFlow::Exit,
WindowEvent::Resized(physical_size) => {
state.resize(*physical_size);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
// new_inner_size is &mut so w have to dereference it twice
state.resize(**new_inner_size);
}
_ => {}
}
}
}
Event::RedrawRequested(window_id) if window_id == window.id() => {
state.update();
match state.render() {
Ok(_) => {}
// Reconfigure the surface if lost
Err(wgpu::SurfaceError::Lost) => state.resize(state.size),
// The system is out of memory, we should probably quit
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
// All other errors (Outdated, Timeout) should be resolved by the next frame
Err(e) => eprintln!("{:?}", e),
}
}
Event::MainEventsCleared => {
// RedrawRequested will only trigger once, unless we manually
// request it.
window.request_redraw();
}
_ => {}
}
});
}
| 36.787089 | 107 | 0.516147 |
1ca8b90b866f8f8c6c4f74f317dbff4497de685c | 11,750 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
/// Service config.
///
///
/// Service configuration allows for customization of endpoints, region, credentials providers,
/// and retry configuration. Generally, it is constructed automatically for you from a shared
/// configuration loaded by the `aws-config` crate. For example:
///
/// ```ignore
/// // Load a shared config from the environment
/// let shared_config = aws_config::from_env().load().await;
/// // The client constructor automatically converts the shared config into the service config
/// let client = Client::new(&shared_config);
/// ```
///
/// The service config can also be constructed manually using its builder.
///
pub struct Config {
app_name: Option<aws_types::app_name::AppName>,
pub(crate) timeout_config: Option<aws_smithy_types::timeout::Config>,
pub(crate) sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>,
pub(crate) retry_config: Option<aws_smithy_types::retry::RetryConfig>,
pub(crate) endpoint_resolver: ::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>,
pub(crate) region: Option<aws_types::region::Region>,
pub(crate) credentials_provider: aws_types::credentials::SharedCredentialsProvider,
}
impl std::fmt::Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut config = f.debug_struct("Config");
config.finish()
}
}
impl Config {
/// Constructs a config builder.
pub fn builder() -> Builder {
Builder::default()
}
/// Returns the name of the app that is using the client, if it was provided.
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
pub fn app_name(&self) -> Option<&aws_types::app_name::AppName> {
self.app_name.as_ref()
}
/// Creates a new [service config](crate::Config) from a [shared `config`](aws_types::sdk_config::SdkConfig).
pub fn new(config: &aws_types::sdk_config::SdkConfig) -> Self {
Builder::from(config).build()
}
/// The signature version 4 service signing name to use in the credential scope when signing requests.
///
/// The signing service may be overridden by the `Endpoint`, or by specifying a custom
/// [`SigningService`](aws_types::SigningService) during operation construction
pub fn signing_service(&self) -> &'static str {
"glue"
}
}
/// Builder for creating a `Config`.
#[derive(Default)]
pub struct Builder {
app_name: Option<aws_types::app_name::AppName>,
timeout_config: Option<aws_smithy_types::timeout::Config>,
sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>,
retry_config: Option<aws_smithy_types::retry::RetryConfig>,
endpoint_resolver: Option<::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>>,
region: Option<aws_types::region::Region>,
credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>,
}
impl Builder {
/// Constructs a config builder.
pub fn new() -> Self {
Self::default()
}
/// Sets the name of the app that is using the client.
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
pub fn app_name(mut self, app_name: aws_types::app_name::AppName) -> Self {
self.set_app_name(Some(app_name));
self
}
/// Sets the name of the app that is using the client.
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
pub fn set_app_name(&mut self, app_name: Option<aws_types::app_name::AppName>) -> &mut Self {
self.app_name = app_name;
self
}
/// Set the timeout_config for the builder
///
/// # Examples
///
/// ```no_run
/// # use std::time::Duration;
/// use aws_sdk_glue::config::Config;
/// use aws_smithy_types::{timeout, tristate::TriState};
///
/// let api_timeouts = timeout::Api::new()
/// .with_call_attempt_timeout(TriState::Set(Duration::from_secs(1)));
/// let timeout_config = timeout::Config::new()
/// .with_api_timeouts(api_timeouts);
/// let config = Config::builder().timeout_config(timeout_config).build();
/// ```
pub fn timeout_config(mut self, timeout_config: aws_smithy_types::timeout::Config) -> Self {
self.set_timeout_config(Some(timeout_config));
self
}
/// Set the timeout_config for the builder
///
/// # Examples
///
/// ```no_run
/// # use std::time::Duration;
/// use aws_sdk_glue::config::{Builder, Config};
/// use aws_smithy_types::{timeout, tristate::TriState};
///
/// fn set_request_timeout(builder: &mut Builder) {
/// let api_timeouts = timeout::Api::new()
/// .with_call_attempt_timeout(TriState::Set(Duration::from_secs(1)));
/// let timeout_config = timeout::Config::new()
/// .with_api_timeouts(api_timeouts);
/// builder.set_timeout_config(Some(timeout_config));
/// }
///
/// let mut builder = Config::builder();
/// set_request_timeout(&mut builder);
/// let config = builder.build();
/// ```
pub fn set_timeout_config(
&mut self,
timeout_config: Option<aws_smithy_types::timeout::Config>,
) -> &mut Self {
self.timeout_config = timeout_config;
self
}
/// Set the sleep_impl for the builder
///
/// # Examples
///
/// ```no_run
/// use aws_sdk_glue::config::Config;
/// use aws_smithy_async::rt::sleep::AsyncSleep;
/// use aws_smithy_async::rt::sleep::Sleep;
///
/// #[derive(Debug)]
/// pub struct ForeverSleep;
///
/// impl AsyncSleep for ForeverSleep {
/// fn sleep(&self, duration: std::time::Duration) -> Sleep {
/// Sleep::new(std::future::pending())
/// }
/// }
///
/// let sleep_impl = std::sync::Arc::new(ForeverSleep);
/// let config = Config::builder().sleep_impl(sleep_impl).build();
/// ```
pub fn sleep_impl(
mut self,
sleep_impl: std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>,
) -> Self {
self.set_sleep_impl(Some(sleep_impl));
self
}
/// Set the sleep_impl for the builder
///
/// # Examples
///
/// ```no_run
/// use aws_sdk_glue::config::{Builder, Config};
/// use aws_smithy_async::rt::sleep::AsyncSleep;
/// use aws_smithy_async::rt::sleep::Sleep;
///
/// #[derive(Debug)]
/// pub struct ForeverSleep;
///
/// impl AsyncSleep for ForeverSleep {
/// fn sleep(&self, duration: std::time::Duration) -> Sleep {
/// Sleep::new(std::future::pending())
/// }
/// }
///
/// fn set_never_ending_sleep_impl(builder: &mut Builder) {
/// let sleep_impl = std::sync::Arc::new(ForeverSleep);
/// builder.set_sleep_impl(Some(sleep_impl));
/// }
///
/// let mut builder = Config::builder();
/// set_never_ending_sleep_impl(&mut builder);
/// let config = builder.build();
/// ```
pub fn set_sleep_impl(
&mut self,
sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>,
) -> &mut Self {
self.sleep_impl = sleep_impl;
self
}
/// Set the retry_config for the builder
///
/// # Examples
/// ```no_run
/// use aws_sdk_glue::config::Config;
/// use aws_smithy_types::retry::RetryConfig;
///
/// let retry_config = RetryConfig::new().with_max_attempts(5);
/// let config = Config::builder().retry_config(retry_config).build();
/// ```
pub fn retry_config(mut self, retry_config: aws_smithy_types::retry::RetryConfig) -> Self {
self.set_retry_config(Some(retry_config));
self
}
/// Set the retry_config for the builder
///
/// # Examples
/// ```no_run
/// use aws_sdk_glue::config::{Builder, Config};
/// use aws_smithy_types::retry::RetryConfig;
///
/// fn disable_retries(builder: &mut Builder) {
/// let retry_config = RetryConfig::new().with_max_attempts(1);
/// builder.set_retry_config(Some(retry_config));
/// }
///
/// let mut builder = Config::builder();
/// disable_retries(&mut builder);
/// let config = builder.build();
/// ```
pub fn set_retry_config(
&mut self,
retry_config: Option<aws_smithy_types::retry::RetryConfig>,
) -> &mut Self {
self.retry_config = retry_config;
self
}
// TODO(docs): include an example of using a static endpoint
/// Sets the endpoint resolver to use when making requests.
pub fn endpoint_resolver(
mut self,
endpoint_resolver: impl aws_endpoint::ResolveAwsEndpoint + 'static,
) -> Self {
self.endpoint_resolver = Some(::std::sync::Arc::new(endpoint_resolver));
self
}
/// Sets the AWS region to use when making requests.
///
/// # Examples
/// ```no_run
/// use aws_types::region::Region;
/// use aws_sdk_glue::config::{Builder, Config};
///
/// let config = aws_sdk_glue::Config::builder()
/// .region(Region::new("us-east-1"))
/// .build();
/// ```
pub fn region(mut self, region: impl Into<Option<aws_types::region::Region>>) -> Self {
self.region = region.into();
self
}
/// Sets the credentials provider for this service
pub fn credentials_provider(
mut self,
credentials_provider: impl aws_types::credentials::ProvideCredentials + 'static,
) -> Self {
self.credentials_provider = Some(aws_types::credentials::SharedCredentialsProvider::new(
credentials_provider,
));
self
}
/// Sets the credentials provider for this service
pub fn set_credentials_provider(
&mut self,
credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>,
) -> &mut Self {
self.credentials_provider = credentials_provider;
self
}
/// Builds a [`Config`].
pub fn build(self) -> Config {
Config {
app_name: self.app_name,
timeout_config: self.timeout_config,
sleep_impl: self.sleep_impl,
retry_config: self.retry_config,
endpoint_resolver: self
.endpoint_resolver
.unwrap_or_else(|| ::std::sync::Arc::new(crate::aws_endpoint::endpoint_resolver())),
region: self.region,
credentials_provider: self.credentials_provider.unwrap_or_else(|| {
aws_types::credentials::SharedCredentialsProvider::new(
crate::no_credentials::NoCredentials,
)
}),
}
}
}
impl From<&aws_types::sdk_config::SdkConfig> for Builder {
fn from(input: &aws_types::sdk_config::SdkConfig) -> Self {
let mut builder = Builder::default();
builder = builder.region(input.region().cloned());
builder.set_retry_config(input.retry_config().cloned());
builder.set_timeout_config(input.timeout_config().cloned());
builder.set_sleep_impl(input.sleep_impl().clone());
builder.set_credentials_provider(input.credentials_provider().cloned());
builder.set_app_name(input.app_name().cloned());
builder
}
}
impl From<&aws_types::sdk_config::SdkConfig> for Config {
fn from(sdk_config: &aws_types::sdk_config::SdkConfig) -> Self {
Builder::from(sdk_config).build()
}
}
| 36.71875 | 113 | 0.623404 |
61537f7b8f76ad1f93f078d78b7593847fe079ee | 2,281 | #![allow(unused_imports)]
use super::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
# [wasm_bindgen (extends = :: js_sys :: Object , js_name = CredentialRequestOptions)]
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc = "The `CredentialRequestOptions` dictionary."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `CredentialRequestOptions`*"]
pub type CredentialRequestOptions;
}
impl CredentialRequestOptions {
#[doc = "Construct a new `CredentialRequestOptions`."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `CredentialRequestOptions`*"]
pub fn new() -> Self {
#[allow(unused_mut)]
let mut ret: Self = ::wasm_bindgen::JsCast::unchecked_into(::js_sys::Object::new());
ret
}
#[cfg(feature = "PublicKeyCredentialRequestOptions")]
#[doc = "Change the `publicKey` field of this object."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `CredentialRequestOptions`, `PublicKeyCredentialRequestOptions`*"]
pub fn public_key(&mut self, val: &PublicKeyCredentialRequestOptions) -> &mut Self {
use wasm_bindgen::JsValue;
let r = ::js_sys::Reflect::set(
self.as_ref(),
&JsValue::from("publicKey"),
&JsValue::from(val),
);
debug_assert!(
r.is_ok(),
"setting properties should never fail on our dictionary objects"
);
let _ = r;
self
}
#[cfg(feature = "AbortSignal")]
#[doc = "Change the `signal` field of this object."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `AbortSignal`, `CredentialRequestOptions`*"]
pub fn signal(&mut self, val: &AbortSignal) -> &mut Self {
use wasm_bindgen::JsValue;
let r =
::js_sys::Reflect::set(self.as_ref(), &JsValue::from("signal"), &JsValue::from(val));
debug_assert!(
r.is_ok(),
"setting properties should never fail on our dictionary objects"
);
let _ = r;
self
}
}
impl Default for CredentialRequestOptions {
fn default() -> Self {
Self::new()
}
}
| 37.393443 | 144 | 0.610259 |
acd3009951f98185bba02a1996a4cb99d5beb0eb | 1,092 | use bbecs::components::CastComponents;
use bbecs::data_types::point::Point;
use bbecs::query;
use bbecs::world::{DataWrapper, World};
use eyre::Result;
use ggez::graphics::{self, DrawParam, Text, WHITE};
use ggez::Context;
use crate::names::component_names::ComponentNames;
#[derive(Default)]
pub struct DrawText;
impl DrawText {
pub fn run(&self, world: &World, context: &mut Context) -> Result<()> {
let query;
let (text_fragments, positions) = query!(
world,
query,
ComponentNames::Text.as_ref(),
ComponentNames::Position.as_ref()
);
for (index, text_fragment) in text_fragments.iter().enumerate() {
let text: &DataWrapper<Text> = text_fragment.cast()?;
let position: &DataWrapper<Point> = positions[index].cast()?;
graphics::draw(
context,
&*text.borrow(),
DrawParam::new()
.dest(position.borrow().to_array())
.color(WHITE),
)?;
}
Ok(())
}
}
| 27.3 | 75 | 0.557692 |
2638a3525a980936d5e2f09b9ffb175666b4e600 | 3,174 | use maybe_owned::MaybeOwned;
use super::op_resolver::OpResolver;
use super::FlatBufferModel;
use super::Interpreter;
use crate::bindings::tflite as bindings;
use crate::{Error, Result};
cpp! {{
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/kernels/register.h"
using namespace tflite;
}}
pub struct InterpreterBuilder<'a, Op>
where
Op: OpResolver,
{
handle: Box<bindings::InterpreterBuilder>,
_model: MaybeOwned<'a, FlatBufferModel>,
_resolver: Op,
}
impl<'a, Op> Drop for InterpreterBuilder<'a, Op>
where
Op: OpResolver,
{
fn drop(&mut self) {
let handle = Box::into_raw(std::mem::take(&mut self.handle));
#[allow(clippy::forget_copy, clippy::useless_transmute, deprecated)]
unsafe {
cpp!([handle as "InterpreterBuilder*"] {
delete handle;
});
}
}
}
impl<'a, Op> InterpreterBuilder<'a, Op>
where
Op: OpResolver,
{
#[allow(clippy::new_ret_no_self)]
pub fn new<M: Into<MaybeOwned<'a, FlatBufferModel>>>(model: M, resolver: Op) -> Result<Self> {
use std::ops::Deref;
let model = model.into();
let handle = {
let model_handle = model.as_ref().handle.deref();
let resolver_handle = resolver.get_resolver_handle();
#[allow(clippy::forget_copy, deprecated)]
unsafe {
cpp!([model_handle as "const FlatBufferModel*",
resolver_handle as "const OpResolver*"
] -> *mut bindings::InterpreterBuilder as "InterpreterBuilder*" {
return new InterpreterBuilder(*model_handle, *resolver_handle);
})
}
};
if handle.is_null() {
return Err(Error::InternalError("failed to create InterpreterBuilder".to_string()));
}
let handle = unsafe { Box::from_raw(handle) };
Ok(Self { handle, _model: model, _resolver: resolver })
}
pub fn build(mut self) -> Result<Interpreter<'a, Op>> {
#[allow(clippy::forget_copy, deprecated)]
let handle = {
let builder = &mut *self.handle;
unsafe {
cpp!([builder as "InterpreterBuilder*"] -> *mut bindings::Interpreter as "Interpreter*" {
std::unique_ptr<Interpreter> interpreter;
(*builder)(&interpreter);
return interpreter.release();
})
}
};
Interpreter::new(handle, self)
}
pub fn build_with_threads(
mut self,
threads: std::os::raw::c_int,
) -> Result<Interpreter<'a, Op>> {
#[allow(clippy::forget_copy, deprecated)]
let handle = {
let builder = &mut *self.handle;
unsafe {
cpp!([builder as "InterpreterBuilder*", threads as "int"] -> *mut bindings::Interpreter as "Interpreter*" {
std::unique_ptr<Interpreter> interpreter;
(*builder)(&interpreter, threads);
return interpreter.release();
})
}
};
Interpreter::new(handle, self)
}
}
| 31.425743 | 123 | 0.563642 |
099687bd6b08240449b7b92b6773fd2e73fe6f42 | 92,637 | use core::borrow::Borrow;
use core::cmp::Ordering;
use core::fmt::Debug;
use core::hash::{Hash, Hasher};
use core::iter::{FromIterator, FusedIterator, Peekable};
use core::marker::PhantomData;
use core::mem::{self, ManuallyDrop};
use core::ops::Bound::{Excluded, Included, Unbounded};
use core::ops::{Index, RangeBounds};
use core::{fmt, ptr};
use super::node::{self, marker, ForceResult::*, Handle, InsertResult::*, NodeRef};
use super::search::{self, SearchResult::*};
use super::unwrap_unchecked;
use Entry::*;
use UnderflowResult::*;
/// A map based on a B-Tree.
///
/// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
/// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
/// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
/// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
/// is done is *very* inefficient for modern computer architectures. In particular, every element
/// is stored in its own individually heap-allocated node. This means that every single insertion
/// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
/// are both notably expensive things to do in practice, we are forced to at very least reconsider
/// the BST strategy.
///
/// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
/// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
/// searches. However, this does mean that searches will have to do *more* comparisons on average.
/// The precise number of comparisons depends on the node search strategy used. For optimal cache
/// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
/// the node using binary search. As a compromise, one could also perform a linear search
/// that initially only checks every i<sup>th</sup> element for some choice of i.
///
/// Currently, our implementation simply performs naive linear search. This provides excellent
/// performance on *small* nodes of elements which are cheap to compare. However in the future we
/// would like to further explore choosing the optimal search strategy based on the choice of B,
/// and possibly other factors. Using linear search, searching for a random element is expected
/// to take O(B * log(n)) comparisons, which is generally worse than a BST. In practice,
/// however, performance is excellent.
///
/// It is a logic error for a key to be modified in such a way that the key's ordering relative to
/// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
///
/// [`Ord`]: ../../std/cmp/trait.Ord.html
/// [`Cell`]: ../../std/cell/struct.Cell.html
/// [`RefCell`]: ../../std/cell/struct.RefCell.html
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// // type inference lets us omit an explicit type signature (which
/// // would be `BTreeMap<&str, &str>` in this example).
/// let mut movie_reviews = BTreeMap::new();
///
/// // review some movies.
/// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
/// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
/// movie_reviews.insert("The Godfather", "Very enjoyable.");
/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
///
/// // check for a specific one.
/// if !movie_reviews.contains_key("Les Misérables") {
/// println!("We've got {} reviews, but Les Misérables ain't one.",
/// movie_reviews.len());
/// }
///
/// // oops, this review has a lot of spelling mistakes, let's delete it.
/// movie_reviews.remove("The Blues Brothers");
///
/// // look up the values associated with some keys.
/// let to_find = ["Up!", "Office Space"];
/// for movie in &to_find {
/// match movie_reviews.get(movie) {
/// Some(review) => println!("{}: {}", movie, review),
/// None => println!("{} is unreviewed.", movie)
/// }
/// }
///
/// // Look up the value for a key (will panic if the key is not found).
/// println!("Movie review: {}", movie_reviews["Office Space"]);
///
/// // iterate over everything.
/// for (movie, review) in &movie_reviews {
/// println!("{}: \"{}\"", movie, review);
/// }
/// ```
///
/// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
/// for more complex methods of getting, setting, updating and removing keys and
/// their values:
///
/// ```
/// use std::collections::BTreeMap;
///
/// // type inference lets us omit an explicit type signature (which
/// // would be `BTreeMap<&str, u8>` in this example).
/// let mut player_stats = BTreeMap::new();
///
/// fn random_stat_buff() -> u8 {
/// // could actually return some random value here - let's just return
/// // some fixed value for now
/// 42
/// }
///
/// // insert a key only if it doesn't already exist
/// player_stats.entry("health").or_insert(100);
///
/// // insert a key using a function that provides a new value only if it
/// // doesn't already exist
/// player_stats.entry("defence").or_insert_with(random_stat_buff);
///
/// // update a key, guarding against the key possibly not being set
/// let stat = player_stats.entry("attack").or_insert(100);
/// *stat += random_stat_buff();
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct BTreeMap<K, V> {
root: Option<node::Root<K, V>>,
length: usize,
}
#[stable(feature = "btree_drop", since = "1.7.0")]
unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
fn drop(&mut self) {
unsafe {
drop(ptr::read(self).into_iter());
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
fn clone(&self) -> BTreeMap<K, V> {
fn clone_subtree<'a, K: Clone, V: Clone>(
node: node::NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
) -> BTreeMap<K, V>
where
K: 'a,
V: 'a,
{
match node.force() {
Leaf(leaf) => {
let mut out_tree = BTreeMap { root: Some(node::Root::new_leaf()), length: 0 };
{
let root = out_tree.root.as_mut().unwrap();
let mut out_node = match root.as_mut().force() {
Leaf(leaf) => leaf,
Internal(_) => unreachable!(),
};
let mut in_edge = leaf.first_edge();
while let Ok(kv) = in_edge.right_kv() {
let (k, v) = kv.into_kv();
in_edge = kv.right_edge();
out_node.push(k.clone(), v.clone());
out_tree.length += 1;
}
}
out_tree
}
Internal(internal) => {
let mut out_tree = clone_subtree(internal.first_edge().descend());
out_tree.ensure_root_is_owned();
{
// Ideally we'd use the return of ensure_root_is_owned
// instead of re-unwrapping here but unfortunately that
// borrows all of out_tree and we need access to the
// length below.
let mut out_node = out_tree.root.as_mut().unwrap().push_level();
let mut in_edge = internal.first_edge();
while let Ok(kv) = in_edge.right_kv() {
let (k, v) = kv.into_kv();
in_edge = kv.right_edge();
let k = (*k).clone();
let v = (*v).clone();
let subtree = clone_subtree(in_edge.descend());
// We can't destructure subtree directly
// because BTreeMap implements Drop
let (subroot, sublength) = unsafe {
let subtree = ManuallyDrop::new(subtree);
let root = ptr::read(&subtree.root);
let length = subtree.length;
(root, length)
};
out_node.push(k, v, subroot.unwrap_or_else(node::Root::new_leaf));
out_tree.length += 1 + sublength;
}
}
out_tree
}
}
}
if self.is_empty() {
// Ideally we'd call `BTreeMap::new` here, but that has the `K:
// Ord` constraint, which this method lacks.
BTreeMap { root: None, length: 0 }
} else {
clone_subtree(self.root.as_ref().unwrap().as_ref())
}
}
fn clone_from(&mut self, other: &Self) {
BTreeClone::clone_from(self, other);
}
}
trait BTreeClone {
fn clone_from(&mut self, other: &Self);
}
impl<K: Clone, V: Clone> BTreeClone for BTreeMap<K, V> {
default fn clone_from(&mut self, other: &Self) {
*self = other.clone();
}
}
impl<K: Clone + Ord, V: Clone> BTreeClone for BTreeMap<K, V> {
fn clone_from(&mut self, other: &Self) {
// This truncates `self` to `other.len()` by calling `split_off` on
// the first key after `other.len()` elements if it exists.
let split_off_key = if self.len() > other.len() {
let diff = self.len() - other.len();
if diff <= other.len() {
self.iter().nth_back(diff - 1).map(|pair| (*pair.0).clone())
} else {
self.iter().nth(other.len()).map(|pair| (*pair.0).clone())
}
} else {
None
};
if let Some(key) = split_off_key {
self.split_off(&key);
}
let mut siter = self.range_mut(..);
let mut oiter = other.iter();
// After truncation, `self` is at most as long as `other` so this loop
// replaces every key-value pair in `self`. Since `oiter` is in sorted
// order and the structure of the `BTreeMap` stays the same,
// the BTree invariants are maintained at the end of the loop.
while !siter.is_empty() {
if let Some((ok, ov)) = oiter.next() {
// SAFETY: This is safe because `siter` is nonempty.
let (sk, sv) = unsafe { siter.next_unchecked() };
sk.clone_from(ok);
sv.clone_from(ov);
} else {
break;
}
}
// If `other` is longer than `self`, the remaining elements are inserted.
self.extend(oiter.map(|(k, v)| ((*k).clone(), (*v).clone())));
}
}
impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
where
K: Borrow<Q> + Ord,
Q: Ord,
{
type Key = K;
fn get(&self, key: &Q) -> Option<&K> {
match search::search_tree(self.root.as_ref()?.as_ref(), key) {
Found(handle) => Some(handle.into_kv().0),
GoDown(_) => None,
}
}
fn take(&mut self, key: &Q) -> Option<K> {
match search::search_tree(self.root.as_mut()?.as_mut(), key) {
Found(handle) => Some(
OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
.remove_kv()
.0,
),
GoDown(_) => None,
}
}
fn replace(&mut self, key: K) -> Option<K> {
self.ensure_root_is_owned();
match search::search_tree::<marker::Mut<'_>, K, (), K>(self.root.as_mut()?.as_mut(), &key) {
Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
GoDown(handle) => {
VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData }
.insert(());
None
}
}
}
}
/// An iterator over the entries of a `BTreeMap`.
///
/// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
/// documentation for more.
///
/// [`iter`]: struct.BTreeMap.html#method.iter
/// [`BTreeMap`]: struct.BTreeMap.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Iter<'a, K: 'a, V: 'a> {
range: Range<'a, K, V>,
length: usize,
}
#[stable(feature = "collection_debug", since = "1.17.0")]
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
/// A mutable iterator over the entries of a `BTreeMap`.
///
/// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
/// documentation for more.
///
/// [`iter_mut`]: struct.BTreeMap.html#method.iter_mut
/// [`BTreeMap`]: struct.BTreeMap.html
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug)]
pub struct IterMut<'a, K: 'a, V: 'a> {
range: RangeMut<'a, K, V>,
length: usize,
}
/// An owning iterator over the entries of a `BTreeMap`.
///
/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
/// (provided by the `IntoIterator` trait). See its documentation for more.
///
/// [`into_iter`]: struct.BTreeMap.html#method.into_iter
/// [`BTreeMap`]: struct.BTreeMap.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct IntoIter<K, V> {
front: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
back: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
length: usize,
}
#[stable(feature = "collection_debug", since = "1.17.0")]
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let range = Range {
front: self.front.as_ref().map(|f| f.reborrow()),
back: self.back.as_ref().map(|b| b.reborrow()),
};
f.debug_list().entries(range).finish()
}
}
/// An iterator over the keys of a `BTreeMap`.
///
/// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
/// documentation for more.
///
/// [`keys`]: struct.BTreeMap.html#method.keys
/// [`BTreeMap`]: struct.BTreeMap.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Keys<'a, K: 'a, V: 'a> {
inner: Iter<'a, K, V>,
}
#[stable(feature = "collection_debug", since = "1.17.0")]
impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
/// An iterator over the values of a `BTreeMap`.
///
/// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
/// documentation for more.
///
/// [`values`]: struct.BTreeMap.html#method.values
/// [`BTreeMap`]: struct.BTreeMap.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Values<'a, K: 'a, V: 'a> {
inner: Iter<'a, K, V>,
}
#[stable(feature = "collection_debug", since = "1.17.0")]
impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
/// A mutable iterator over the values of a `BTreeMap`.
///
/// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
/// documentation for more.
///
/// [`values_mut`]: struct.BTreeMap.html#method.values_mut
/// [`BTreeMap`]: struct.BTreeMap.html
#[stable(feature = "map_values_mut", since = "1.10.0")]
#[derive(Debug)]
pub struct ValuesMut<'a, K: 'a, V: 'a> {
inner: IterMut<'a, K, V>,
}
/// An iterator over a sub-range of entries in a `BTreeMap`.
///
/// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
/// documentation for more.
///
/// [`range`]: struct.BTreeMap.html#method.range
/// [`BTreeMap`]: struct.BTreeMap.html
#[stable(feature = "btree_range", since = "1.17.0")]
pub struct Range<'a, K: 'a, V: 'a> {
front: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
back: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
}
#[stable(feature = "collection_debug", since = "1.17.0")]
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
/// A mutable iterator over a sub-range of entries in a `BTreeMap`.
///
/// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
/// documentation for more.
///
/// [`range_mut`]: struct.BTreeMap.html#method.range_mut
/// [`BTreeMap`]: struct.BTreeMap.html
#[stable(feature = "btree_range", since = "1.17.0")]
pub struct RangeMut<'a, K: 'a, V: 'a> {
front: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
back: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
// Be invariant in `K` and `V`
_marker: PhantomData<&'a mut (K, V)>,
}
#[stable(feature = "collection_debug", since = "1.17.0")]
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let range = Range {
front: self.front.as_ref().map(|f| f.reborrow()),
back: self.back.as_ref().map(|b| b.reborrow()),
};
f.debug_list().entries(range).finish()
}
}
/// A view into a single entry in a map, which may either be vacant or occupied.
///
/// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
///
/// [`BTreeMap`]: struct.BTreeMap.html
/// [`entry`]: struct.BTreeMap.html#method.entry
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Entry<'a, K: 'a, V: 'a> {
/// A vacant entry.
#[stable(feature = "rust1", since = "1.0.0")]
Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
/// An occupied entry.
#[stable(feature = "rust1", since = "1.0.0")]
Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
}
#[stable(feature = "debug_btree_map", since = "1.12.0")]
impl<K: Debug + Ord, V: Debug> Debug for Entry<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
}
}
}
/// A view into a vacant entry in a `BTreeMap`.
/// It is part of the [`Entry`] enum.
///
/// [`Entry`]: enum.Entry.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct VacantEntry<'a, K: 'a, V: 'a> {
key: K,
handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
length: &'a mut usize,
// Be invariant in `K` and `V`
_marker: PhantomData<&'a mut (K, V)>,
}
#[stable(feature = "debug_btree_map", since = "1.12.0")]
impl<K: Debug + Ord, V> Debug for VacantEntry<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("VacantEntry").field(self.key()).finish()
}
}
/// A view into an occupied entry in a `BTreeMap`.
/// It is part of the [`Entry`] enum.
///
/// [`Entry`]: enum.Entry.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
length: &'a mut usize,
// Be invariant in `K` and `V`
_marker: PhantomData<&'a mut (K, V)>,
}
#[stable(feature = "debug_btree_map", since = "1.12.0")]
impl<K: Debug + Ord, V: Debug> Debug for OccupiedEntry<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
}
}
// An iterator for merging two sorted sequences into one
struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
left: Peekable<I>,
right: Peekable<I>,
}
impl<K: Ord, V> BTreeMap<K, V> {
/// Makes a new empty BTreeMap with a reasonable choice for B.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
///
/// // entries can now be inserted into the empty map
/// map.insert(1, "a");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> BTreeMap<K, V> {
BTreeMap { root: None, length: 0 }
}
/// Clears the map, removing all elements.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// a.insert(1, "a");
/// a.clear();
/// assert!(a.is_empty());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn clear(&mut self) {
*self = BTreeMap::new();
}
/// Returns a reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the map's key type, but the ordering
/// on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.get(&1), Some(&"a"));
/// assert_eq!(map.get(&2), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Ord,
{
match search::search_tree(self.root.as_ref()?.as_ref(), key) {
Found(handle) => Some(handle.into_kv().1),
GoDown(_) => None,
}
}
/// Returns the key-value pair corresponding to the supplied key.
///
/// The supplied key may be any borrowed form of the map's key type, but the ordering
/// on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
/// assert_eq!(map.get_key_value(&2), None);
/// ```
#[stable(feature = "map_get_key_value", since = "1.40.0")]
pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
where
K: Borrow<Q>,
Q: Ord,
{
match search::search_tree(self.root.as_ref()?.as_ref(), k) {
Found(handle) => Some(handle.into_kv()),
GoDown(_) => None,
}
}
/// Returns the first key-value pair in the map.
/// The key in this pair is the minimum key in the map.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(map_first_last)]
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// assert_eq!(map.first_key_value(), None);
/// map.insert(1, "b");
/// map.insert(2, "a");
/// assert_eq!(map.first_key_value(), Some((&1, &"b")));
/// ```
#[unstable(feature = "map_first_last", issue = "62924")]
pub fn first_key_value(&self) -> Option<(&K, &V)> {
let front = self.root.as_ref()?.as_ref().first_leaf_edge();
front.right_kv().ok().map(Handle::into_kv)
}
/// Returns the first entry in the map for in-place manipulation.
/// The key of this entry is the minimum key in the map.
///
/// # Examples
///
/// ```
/// #![feature(map_first_last)]
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// map.insert(2, "b");
/// if let Some(mut entry) = map.first_entry() {
/// if *entry.key() > 0 {
/// entry.insert("first");
/// }
/// }
/// assert_eq!(*map.get(&1).unwrap(), "first");
/// assert_eq!(*map.get(&2).unwrap(), "b");
/// ```
#[unstable(feature = "map_first_last", issue = "62924")]
pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
let front = self.root.as_mut()?.as_mut().first_leaf_edge();
let kv = front.right_kv().ok()?;
Some(OccupiedEntry {
handle: kv.forget_node_type(),
length: &mut self.length,
_marker: PhantomData,
})
}
/// Removes and returns the first element in the map.
/// The key of this element is the minimum key that was in the map.
///
/// # Examples
///
/// Draining elements in ascending order, while keeping a usable map each iteration.
///
/// ```
/// #![feature(map_first_last)]
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// map.insert(2, "b");
/// while let Some((key, _val)) = map.pop_first() {
/// assert!(map.iter().all(|(k, _v)| *k > key));
/// }
/// assert!(map.is_empty());
/// ```
#[unstable(feature = "map_first_last", issue = "62924")]
pub fn pop_first(&mut self) -> Option<(K, V)> {
self.first_entry().map(|entry| entry.remove_entry())
}
/// Returns the last key-value pair in the map.
/// The key in this pair is the maximum key in the map.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(map_first_last)]
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "b");
/// map.insert(2, "a");
/// assert_eq!(map.last_key_value(), Some((&2, &"a")));
/// ```
#[unstable(feature = "map_first_last", issue = "62924")]
pub fn last_key_value(&self) -> Option<(&K, &V)> {
let back = self.root.as_ref()?.as_ref().last_leaf_edge();
back.left_kv().ok().map(Handle::into_kv)
}
/// Returns the last entry in the map for in-place manipulation.
/// The key of this entry is the maximum key in the map.
///
/// # Examples
///
/// ```
/// #![feature(map_first_last)]
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// map.insert(2, "b");
/// if let Some(mut entry) = map.last_entry() {
/// if *entry.key() > 0 {
/// entry.insert("last");
/// }
/// }
/// assert_eq!(*map.get(&1).unwrap(), "a");
/// assert_eq!(*map.get(&2).unwrap(), "last");
/// ```
#[unstable(feature = "map_first_last", issue = "62924")]
pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
let back = self.root.as_mut()?.as_mut().last_leaf_edge();
let kv = back.left_kv().ok()?;
Some(OccupiedEntry {
handle: kv.forget_node_type(),
length: &mut self.length,
_marker: PhantomData,
})
}
/// Removes and returns the last element in the map.
/// The key of this element is the maximum key that was in the map.
///
/// # Examples
///
/// Draining elements in descending order, while keeping a usable map each iteration.
///
/// ```
/// #![feature(map_first_last)]
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// map.insert(2, "b");
/// while let Some((key, _val)) = map.pop_last() {
/// assert!(map.iter().all(|(k, _v)| *k < key));
/// }
/// assert!(map.is_empty());
/// ```
#[unstable(feature = "map_first_last", issue = "62924")]
pub fn pop_last(&mut self) -> Option<(K, V)> {
self.last_entry().map(|entry| entry.remove_entry())
}
/// Returns `true` if the map contains a value for the specified key.
///
/// The key may be any borrowed form of the map's key type, but the ordering
/// on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.contains_key(&1), true);
/// assert_eq!(map.contains_key(&2), false);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Ord,
{
self.get(key).is_some()
}
/// Returns a mutable reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the map's key type, but the ordering
/// on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// if let Some(x) = map.get_mut(&1) {
/// *x = "b";
/// }
/// assert_eq!(map[&1], "b");
/// ```
// See `get` for implementation notes, this is basically a copy-paste with mut's added
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
where
K: Borrow<Q>,
Q: Ord,
{
match search::search_tree(self.root.as_mut()?.as_mut(), key) {
Found(handle) => Some(handle.into_kv_mut().1),
GoDown(_) => None,
}
}
/// Inserts a key-value pair into the map.
///
/// If the map did not have this key present, `None` is returned.
///
/// If the map did have this key present, the value is updated, and the old
/// value is returned. The key is not updated, though; this matters for
/// types that can be `==` without being identical. See the [module-level
/// documentation] for more.
///
/// [module-level documentation]: index.html#insert-and-complex-keys
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// assert_eq!(map.insert(37, "a"), None);
/// assert_eq!(map.is_empty(), false);
///
/// map.insert(37, "b");
/// assert_eq!(map.insert(37, "c"), Some("b"));
/// assert_eq!(map[&37], "c");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
match self.entry(key) {
Occupied(mut entry) => Some(entry.insert(value)),
Vacant(entry) => {
entry.insert(value);
None
}
}
}
/// Removes a key from the map, returning the value at the key if the key
/// was previously in the map.
///
/// The key may be any borrowed form of the map's key type, but the ordering
/// on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.remove(&1), Some("a"));
/// assert_eq!(map.remove(&1), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Ord,
{
self.remove_entry(key).map(|(_, v)| v)
}
/// Removes a key from the map, returning the stored key and value if the key
/// was previously in the map.
///
/// The key may be any borrowed form of the map's key type, but the ordering
/// on the borrowed form *must* match the ordering on the key type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.remove_entry(&1), Some((1, "a")));
/// assert_eq!(map.remove_entry(&1), None);
/// ```
#[stable(feature = "btreemap_remove_entry", since = "1.44.0")]
pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
where
K: Borrow<Q>,
Q: Ord,
{
match search::search_tree(self.root.as_mut()?.as_mut(), key) {
Found(handle) => Some(
OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
.remove_entry(),
),
GoDown(_) => None,
}
}
/// Moves all elements from `other` into `Self`, leaving `other` empty.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// a.insert(1, "a");
/// a.insert(2, "b");
/// a.insert(3, "c");
///
/// let mut b = BTreeMap::new();
/// b.insert(3, "d");
/// b.insert(4, "e");
/// b.insert(5, "f");
///
/// a.append(&mut b);
///
/// assert_eq!(a.len(), 5);
/// assert_eq!(b.len(), 0);
///
/// assert_eq!(a[&1], "a");
/// assert_eq!(a[&2], "b");
/// assert_eq!(a[&3], "d");
/// assert_eq!(a[&4], "e");
/// assert_eq!(a[&5], "f");
/// ```
#[stable(feature = "btree_append", since = "1.11.0")]
pub fn append(&mut self, other: &mut Self) {
// Do we have to append anything at all?
if other.is_empty() {
return;
}
// We can just swap `self` and `other` if `self` is empty.
if self.is_empty() {
mem::swap(self, other);
return;
}
// First, we merge `self` and `other` into a sorted sequence in linear time.
let self_iter = mem::take(self).into_iter();
let other_iter = mem::take(other).into_iter();
let iter = MergeIter { left: self_iter.peekable(), right: other_iter.peekable() };
// Second, we build a tree from the sorted sequence in linear time.
self.from_sorted_iter(iter);
self.fix_right_edge();
}
/// Constructs a double-ended iterator over a sub-range of elements in the map.
/// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
/// yield elements from min (inclusive) to max (exclusive).
/// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
/// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
/// range from 4 to 10.
///
/// # Panics
///
/// Panics if range `start > end`.
/// Panics if range `start == end` and both bounds are `Excluded`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
/// use std::ops::Bound::Included;
///
/// let mut map = BTreeMap::new();
/// map.insert(3, "a");
/// map.insert(5, "b");
/// map.insert(8, "c");
/// for (&key, &value) in map.range((Included(&4), Included(&8))) {
/// println!("{}: {}", key, value);
/// }
/// assert_eq!(Some((&5, &"b")), map.range(4..).next());
/// ```
#[stable(feature = "btree_range", since = "1.17.0")]
pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
where
T: Ord,
K: Borrow<T>,
R: RangeBounds<T>,
{
if let Some(root) = &self.root {
let (f, b) = range_search(root.as_ref(), range);
Range { front: Some(f), back: Some(b) }
} else {
Range { front: None, back: None }
}
}
/// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
/// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
/// yield elements from min (inclusive) to max (exclusive).
/// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
/// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
/// range from 4 to 10.
///
/// # Panics
///
/// Panics if range `start > end`.
/// Panics if range `start == end` and both bounds are `Excluded`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
/// .iter()
/// .map(|&s| (s, 0))
/// .collect();
/// for (_, balance) in map.range_mut("B".."Cheryl") {
/// *balance += 100;
/// }
/// for (name, balance) in &map {
/// println!("{} => {}", name, balance);
/// }
/// ```
#[stable(feature = "btree_range", since = "1.17.0")]
pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
where
T: Ord,
K: Borrow<T>,
R: RangeBounds<T>,
{
if let Some(root) = &mut self.root {
let (f, b) = range_search(root.as_mut(), range);
RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
} else {
RangeMut { front: None, back: None, _marker: PhantomData }
}
}
/// Gets the given key's corresponding entry in the map for in-place manipulation.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
///
/// // count the number of occurrences of letters in the vec
/// for x in vec!["a","b","a","c","a","b"] {
/// *count.entry(x).or_insert(0) += 1;
/// }
///
/// assert_eq!(count["a"], 3);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
// FIXME(@porglezomp) Avoid allocating if we don't insert
self.ensure_root_is_owned();
match search::search_tree(self.root.as_mut().unwrap().as_mut(), &key) {
Found(handle) => {
Occupied(OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData })
}
GoDown(handle) => {
Vacant(VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData })
}
}
}
fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
self.ensure_root_is_owned();
let mut cur_node = self.root.as_mut().unwrap().as_mut().last_leaf_edge().into_node();
// Iterate through all key-value pairs, pushing them into nodes at the right level.
for (key, value) in iter {
// Try to push key-value pair into the current leaf node.
if cur_node.len() < node::CAPACITY {
cur_node.push(key, value);
} else {
// No space left, go up and push there.
let mut open_node;
let mut test_node = cur_node.forget_type();
loop {
match test_node.ascend() {
Ok(parent) => {
let parent = parent.into_node();
if parent.len() < node::CAPACITY {
// Found a node with space left, push here.
open_node = parent;
break;
} else {
// Go up again.
test_node = parent.forget_type();
}
}
Err(node) => {
// We are at the top, create a new root node and push there.
open_node = node.into_root_mut().push_level();
break;
}
}
}
// Push key-value pair and new right subtree.
let tree_height = open_node.height() - 1;
let mut right_tree = node::Root::new_leaf();
for _ in 0..tree_height {
right_tree.push_level();
}
open_node.push(key, value, right_tree);
// Go down to the right-most leaf again.
cur_node = open_node.forget_type().last_leaf_edge().into_node();
}
self.length += 1;
}
}
fn fix_right_edge(&mut self) {
// Handle underfull nodes, start from the top.
let mut cur_node = self.root.as_mut().unwrap().as_mut();
while let Internal(internal) = cur_node.force() {
// Check if right-most child is underfull.
let mut last_edge = internal.last_edge();
let right_child_len = last_edge.reborrow().descend().len();
if right_child_len < node::MIN_LEN {
// We need to steal.
let mut last_kv = match last_edge.left_kv() {
Ok(left) => left,
Err(_) => unreachable!(),
};
last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
last_edge = last_kv.right_edge();
}
// Go further down.
cur_node = last_edge.descend();
}
}
/// Splits the collection into two at the given key. Returns everything after the given key,
/// including the key.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// a.insert(1, "a");
/// a.insert(2, "b");
/// a.insert(3, "c");
/// a.insert(17, "d");
/// a.insert(41, "e");
///
/// let b = a.split_off(&3);
///
/// assert_eq!(a.len(), 2);
/// assert_eq!(b.len(), 3);
///
/// assert_eq!(a[&1], "a");
/// assert_eq!(a[&2], "b");
///
/// assert_eq!(b[&3], "c");
/// assert_eq!(b[&17], "d");
/// assert_eq!(b[&41], "e");
/// ```
#[stable(feature = "btree_split_off", since = "1.11.0")]
pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
where
K: Borrow<Q>,
{
if self.is_empty() {
return Self::new();
}
let total_num = self.len();
let mut right = Self::new();
let right_root = right.ensure_root_is_owned();
for _ in 0..(self.root.as_ref().unwrap().as_ref().height()) {
right_root.push_level();
}
{
let mut left_node = self.root.as_mut().unwrap().as_mut();
let mut right_node = right.root.as_mut().unwrap().as_mut();
loop {
let mut split_edge = match search::search_node(left_node, key) {
// key is going to the right tree
Found(handle) => handle.left_edge(),
GoDown(handle) => handle,
};
split_edge.move_suffix(&mut right_node);
match (split_edge.force(), right_node.force()) {
(Internal(edge), Internal(node)) => {
left_node = edge.descend();
right_node = node.first_edge().descend();
}
(Leaf(_), Leaf(_)) => {
break;
}
_ => {
unreachable!();
}
}
}
}
self.fix_right_border();
right.fix_left_border();
if self.root.as_ref().unwrap().as_ref().height()
< right.root.as_ref().unwrap().as_ref().height()
{
self.recalc_length();
right.length = total_num - self.len();
} else {
right.recalc_length();
self.length = total_num - right.len();
}
right
}
/// Creates an iterator which uses a closure to determine if an element should be removed.
///
/// If the closure returns true, the element is removed from the map and yielded.
/// If the closure returns false, or panics, the element remains in the map and will not be
/// yielded.
///
/// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
/// whether you choose to keep or remove it.
///
/// If the iterator is only partially consumed or not consumed at all, each of the remaining
/// elements will still be subjected to the closure and removed and dropped if it returns true.
///
/// It is unspecified how many more elements will be subjected to the closure
/// if a panic occurs in the closure, or a panic occurs while dropping an element,
/// or if the `DrainFilter` value is leaked.
///
/// # Examples
///
/// Splitting a map into even and odd keys, reusing the original map:
///
/// ```
/// #![feature(btree_drain_filter)]
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
/// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
/// let odds = map;
/// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
/// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
/// ```
#[unstable(feature = "btree_drain_filter", issue = "70530")]
pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
where
F: FnMut(&K, &mut V) -> bool,
{
DrainFilter { pred, inner: self.drain_filter_inner() }
}
pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> {
let front = self.root.as_mut().map(|r| r.as_mut().first_leaf_edge());
DrainFilterInner { length: &mut self.length, cur_leaf_edge: front }
}
/// Calculates the number of elements if it is incorrect.
fn recalc_length(&mut self) {
fn dfs<'a, K, V>(node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>) -> usize
where
K: 'a,
V: 'a,
{
let mut res = node.len();
if let Internal(node) = node.force() {
let mut edge = node.first_edge();
loop {
res += dfs(edge.reborrow().descend());
match edge.right_kv() {
Ok(right_kv) => {
edge = right_kv.right_edge();
}
Err(_) => {
break;
}
}
}
}
res
}
self.length = dfs(self.root.as_ref().unwrap().as_ref());
}
/// Removes empty levels on the top.
fn fix_top(&mut self) {
loop {
{
let node = self.root.as_ref().unwrap().as_ref();
if node.height() == 0 || node.len() > 0 {
break;
}
}
self.root.as_mut().unwrap().pop_level();
}
}
fn fix_right_border(&mut self) {
self.fix_top();
{
let mut cur_node = self.root.as_mut().unwrap().as_mut();
while let Internal(node) = cur_node.force() {
let mut last_kv = node.last_kv();
if last_kv.can_merge() {
cur_node = last_kv.merge().descend();
} else {
let right_len = last_kv.reborrow().right_edge().descend().len();
// `MINLEN + 1` to avoid readjust if merge happens on the next level.
if right_len < node::MIN_LEN + 1 {
last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
}
cur_node = last_kv.right_edge().descend();
}
}
}
self.fix_top();
}
/// The symmetric clone of `fix_right_border`.
fn fix_left_border(&mut self) {
self.fix_top();
{
let mut cur_node = self.root.as_mut().unwrap().as_mut();
while let Internal(node) = cur_node.force() {
let mut first_kv = node.first_kv();
if first_kv.can_merge() {
cur_node = first_kv.merge().descend();
} else {
let left_len = first_kv.reborrow().left_edge().descend().len();
if left_len < node::MIN_LEN + 1 {
first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
}
cur_node = first_kv.left_edge().descend();
}
}
}
self.fix_top();
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
fn into_iter(self) -> Iter<'a, K, V> {
self.iter()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<(&'a K, &'a V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
unsafe { Some(self.range.next_unchecked()) }
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.length, Some(self.length))
}
fn last(mut self) -> Option<(&'a K, &'a V)> {
self.next_back()
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<K, V> FusedIterator for Iter<'_, K, V> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
unsafe { Some(self.range.next_back_unchecked()) }
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
fn len(&self) -> usize {
self.length
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> Clone for Iter<'_, K, V> {
fn clone(&self) -> Self {
Iter { range: self.range.clone(), length: self.length }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>;
fn into_iter(self) -> IterMut<'a, K, V> {
self.iter_mut()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
let (k, v) = unsafe { self.range.next_unchecked() };
Some((k, v)) // coerce k from `&mut K` to `&K`
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.length, Some(self.length))
}
fn last(mut self) -> Option<(&'a K, &'a mut V)> {
self.next_back()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
let (k, v) = unsafe { self.range.next_back_unchecked() };
Some((k, v)) // coerce k from `&mut K` to `&K`
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
fn len(&self) -> usize {
self.length
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<K, V> FusedIterator for IterMut<'_, K, V> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> IntoIterator for BTreeMap<K, V> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> IntoIter<K, V> {
let mut me = ManuallyDrop::new(self);
if let Some(root) = me.root.as_mut() {
let root1 = unsafe { ptr::read(root).into_ref() };
let root2 = unsafe { ptr::read(root).into_ref() };
let len = me.length;
IntoIter {
front: Some(root1.first_leaf_edge()),
back: Some(root2.last_leaf_edge()),
length: len,
}
} else {
IntoIter { front: None, back: None, length: 0 }
}
}
}
#[stable(feature = "btree_drop", since = "1.7.0")]
impl<K, V> Drop for IntoIter<K, V> {
fn drop(&mut self) {
struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
impl<'a, K, V> Drop for DropGuard<'a, K, V> {
fn drop(&mut self) {
// Continue the same loop we perform below. This only runs when unwinding, so we
// don't have to care about panics this time (they'll abort).
while let Some(_) = self.0.next() {}
unsafe {
let mut node =
unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
while let Some(parent) = node.deallocate_and_ascend() {
node = parent.into_node().forget_type();
}
}
}
}
while let Some(pair) = self.next() {
let guard = DropGuard(self);
drop(pair);
mem::forget(guard);
}
unsafe {
if let Some(front) = ptr::read(&self.front) {
let mut node = front.into_node().forget_type();
// Most of the nodes have been deallocated while traversing
// but one pile from a leaf up to the root is left standing.
while let Some(parent) = node.deallocate_and_ascend() {
node = parent.into_node().forget_type();
}
}
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> Iterator for IntoIter<K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.length, Some(self.length))
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
fn next_back(&mut self) -> Option<(K, V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> ExactSizeIterator for IntoIter<K, V> {
fn len(&self) -> usize {
self.length
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<K, V> FusedIterator for IntoIter<K, V> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K, V> Iterator for Keys<'a, K, V> {
type Item = &'a K;
fn next(&mut self) -> Option<&'a K> {
self.inner.next().map(|(k, _)| k)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn last(mut self) -> Option<&'a K> {
self.next_back()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
fn next_back(&mut self) -> Option<&'a K> {
self.inner.next_back().map(|(k, _)| k)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
fn len(&self) -> usize {
self.inner.len()
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<K, V> FusedIterator for Keys<'_, K, V> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> Clone for Keys<'_, K, V> {
fn clone(&self) -> Self {
Keys { inner: self.inner.clone() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K, V> Iterator for Values<'a, K, V> {
type Item = &'a V;
fn next(&mut self) -> Option<&'a V> {
self.inner.next().map(|(_, v)| v)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn last(mut self) -> Option<&'a V> {
self.next_back()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
fn next_back(&mut self) -> Option<&'a V> {
self.inner.next_back().map(|(_, v)| v)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> ExactSizeIterator for Values<'_, K, V> {
fn len(&self) -> usize {
self.inner.len()
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<K, V> FusedIterator for Values<'_, K, V> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> Clone for Values<'_, K, V> {
fn clone(&self) -> Self {
Values { inner: self.inner.clone() }
}
}
/// An iterator produced by calling `drain_filter` on BTreeMap.
#[unstable(feature = "btree_drain_filter", issue = "70530")]
pub struct DrainFilter<'a, K, V, F>
where
K: 'a,
V: 'a,
F: 'a + FnMut(&K, &mut V) -> bool,
{
pred: F,
inner: DrainFilterInner<'a, K, V>,
}
pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
length: &'a mut usize,
cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
}
#[unstable(feature = "btree_drain_filter", issue = "70530")]
impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
where
F: FnMut(&K, &mut V) -> bool,
{
fn drop(&mut self) {
self.for_each(drop);
}
}
#[unstable(feature = "btree_drain_filter", issue = "70530")]
impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
where
K: fmt::Debug,
V: fmt::Debug,
F: FnMut(&K, &mut V) -> bool,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
}
}
#[unstable(feature = "btree_drain_filter", issue = "70530")]
impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
where
F: FnMut(&K, &mut V) -> bool,
{
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
self.inner.next(&mut self.pred)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
/// Allow Debug implementations to predict the next element.
pub(super) fn peek(&self) -> Option<(&K, &V)> {
let edge = self.cur_leaf_edge.as_ref()?;
edge.reborrow().next_kv().ok().map(|kv| kv.into_kv())
}
unsafe fn next_kv(
&mut self,
) -> Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>> {
let edge = self.cur_leaf_edge.as_ref()?;
ptr::read(edge).next_kv().ok()
}
/// Implementation of a typical `DrainFilter::next` method, given the predicate.
pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
where
F: FnMut(&K, &mut V) -> bool,
{
while let Some(mut kv) = unsafe { self.next_kv() } {
let (k, v) = kv.kv_mut();
if pred(k, v) {
*self.length -= 1;
let (k, v, leaf_edge_location) = kv.remove_kv_tracking();
self.cur_leaf_edge = Some(leaf_edge_location);
return Some((k, v));
}
self.cur_leaf_edge = Some(kv.next_leaf_edge());
}
None
}
/// Implementation of a typical `DrainFilter::size_hint` method.
pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(*self.length))
}
}
#[unstable(feature = "btree_drain_filter", issue = "70530")]
impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
#[stable(feature = "btree_range", since = "1.17.0")]
impl<'a, K, V> Iterator for Range<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<(&'a K, &'a V)> {
if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
}
fn last(mut self) -> Option<(&'a K, &'a V)> {
self.next_back()
}
}
#[stable(feature = "map_values_mut", since = "1.10.0")]
impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
type Item = &'a mut V;
fn next(&mut self) -> Option<&'a mut V> {
self.inner.next().map(|(_, v)| v)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn last(mut self) -> Option<&'a mut V> {
self.next_back()
}
}
#[stable(feature = "map_values_mut", since = "1.10.0")]
impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
fn next_back(&mut self) -> Option<&'a mut V> {
self.inner.next_back().map(|(_, v)| v)
}
}
#[stable(feature = "map_values_mut", since = "1.10.0")]
impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
fn len(&self) -> usize {
self.inner.len()
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
impl<'a, K, V> Range<'a, K, V> {
fn is_empty(&self) -> bool {
self.front == self.back
}
unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
unwrap_unchecked(self.front.as_mut()).next_unchecked()
}
}
#[stable(feature = "btree_range", since = "1.17.0")]
impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
}
}
impl<'a, K, V> Range<'a, K, V> {
unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
unwrap_unchecked(self.back.as_mut()).next_back_unchecked()
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<K, V> FusedIterator for Range<'_, K, V> {}
#[stable(feature = "btree_range", since = "1.17.0")]
impl<K, V> Clone for Range<'_, K, V> {
fn clone(&self) -> Self {
Range { front: self.front, back: self.back }
}
}
#[stable(feature = "btree_range", since = "1.17.0")]
impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
if self.is_empty() {
None
} else {
let (k, v) = unsafe { self.next_unchecked() };
Some((k, v)) // coerce k from `&mut K` to `&K`
}
}
fn last(mut self) -> Option<(&'a K, &'a mut V)> {
self.next_back()
}
}
impl<'a, K, V> RangeMut<'a, K, V> {
fn is_empty(&self) -> bool {
self.front == self.back
}
unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
unwrap_unchecked(self.front.as_mut()).next_unchecked()
}
}
#[stable(feature = "btree_range", since = "1.17.0")]
impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
if self.is_empty() {
None
} else {
let (k, v) = unsafe { self.next_back_unchecked() };
Some((k, v)) // coerce k from `&mut K` to `&K`
}
}
}
#[stable(feature = "fused", since = "1.26.0")]
impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
impl<'a, K, V> RangeMut<'a, K, V> {
unsafe fn next_back_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
unwrap_unchecked(self.back.as_mut()).next_back_unchecked()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
let mut map = BTreeMap::new();
map.extend(iter);
map
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
#[inline]
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
iter.into_iter().for_each(move |(k, v)| {
self.insert(k, v);
});
}
}
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
fn hash<H: Hasher>(&self, state: &mut H) {
for elt in self {
elt.hash(state);
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Ord, V> Default for BTreeMap<K, V> {
/// Creates an empty `BTreeMap<K, V>`.
fn default() -> BTreeMap<K, V> {
BTreeMap::new()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
fn eq(&self, other: &BTreeMap<K, V>) -> bool {
self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
#[inline]
fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
self.iter().partial_cmp(other.iter())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
#[inline]
fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
self.iter().cmp(other.iter())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
where
K: Borrow<Q>,
Q: Ord,
{
type Output = V;
/// Returns a reference to the value corresponding to the supplied key.
///
/// # Panics
///
/// Panics if the key is not present in the `BTreeMap`.
#[inline]
fn index(&self, key: &Q) -> &V {
self.get(key).expect("no entry found for key")
}
}
fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>(
root: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
range: R,
) -> (
Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
)
where
Q: Ord,
K: Borrow<Q>,
{
match (range.start_bound(), range.end_bound()) {
(Excluded(s), Excluded(e)) if s == e => {
panic!("range start and end are equal and excluded in BTreeMap")
}
(Included(s) | Excluded(s), Included(e) | Excluded(e)) if s > e => {
panic!("range start is greater than range end in BTreeMap")
}
_ => {}
};
// We duplicate the root NodeRef here -- we will never access it in a way
// that overlaps references obtained from the root.
let mut min_node = unsafe { ptr::read(&root) };
let mut max_node = root;
let mut min_found = false;
let mut max_found = false;
loop {
let front = match (min_found, range.start_bound()) {
(false, Included(key)) => match search::search_node(min_node, key) {
Found(kv) => {
min_found = true;
kv.left_edge()
}
GoDown(edge) => edge,
},
(false, Excluded(key)) => match search::search_node(min_node, key) {
Found(kv) => {
min_found = true;
kv.right_edge()
}
GoDown(edge) => edge,
},
(true, Included(_)) => min_node.last_edge(),
(true, Excluded(_)) => min_node.first_edge(),
(_, Unbounded) => min_node.first_edge(),
};
let back = match (max_found, range.end_bound()) {
(false, Included(key)) => match search::search_node(max_node, key) {
Found(kv) => {
max_found = true;
kv.right_edge()
}
GoDown(edge) => edge,
},
(false, Excluded(key)) => match search::search_node(max_node, key) {
Found(kv) => {
max_found = true;
kv.left_edge()
}
GoDown(edge) => edge,
},
(true, Included(_)) => max_node.first_edge(),
(true, Excluded(_)) => max_node.last_edge(),
(_, Unbounded) => max_node.last_edge(),
};
if front.partial_cmp(&back) == Some(Ordering::Greater) {
panic!("Ord is ill-defined in BTreeMap range");
}
match (front.force(), back.force()) {
(Leaf(f), Leaf(b)) => {
return (f, b);
}
(Internal(min_int), Internal(max_int)) => {
min_node = min_int.descend();
max_node = max_int.descend();
}
_ => unreachable!("BTreeMap has different depths"),
};
}
}
impl<K, V> BTreeMap<K, V> {
/// Gets an iterator over the entries of the map, sorted by key.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(3, "c");
/// map.insert(2, "b");
/// map.insert(1, "a");
///
/// for (key, value) in map.iter() {
/// println!("{}: {}", key, value);
/// }
///
/// let (first_key, first_value) = map.iter().next().unwrap();
/// assert_eq!((*first_key, *first_value), (1, "a"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter(&self) -> Iter<'_, K, V> {
Iter {
range: Range {
front: self.root.as_ref().map(|r| r.as_ref().first_leaf_edge()),
back: self.root.as_ref().map(|r| r.as_ref().last_leaf_edge()),
},
length: self.length,
}
}
/// Gets a mutable iterator over the entries of the map, sorted by key.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert("a", 1);
/// map.insert("b", 2);
/// map.insert("c", 3);
///
/// // add 10 to the value if the key isn't "a"
/// for (key, value) in map.iter_mut() {
/// if key != &"a" {
/// *value += 10;
/// }
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
IterMut {
range: if let Some(root) = &mut self.root {
let root1 = root.as_mut();
let root2 = unsafe { ptr::read(&root1) };
RangeMut {
front: Some(root1.first_leaf_edge()),
back: Some(root2.last_leaf_edge()),
_marker: PhantomData,
}
} else {
RangeMut { front: None, back: None, _marker: PhantomData }
},
length: self.length,
}
}
/// Gets an iterator over the keys of the map, in sorted order.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// a.insert(2, "b");
/// a.insert(1, "a");
///
/// let keys: Vec<_> = a.keys().cloned().collect();
/// assert_eq!(keys, [1, 2]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn keys(&self) -> Keys<'_, K, V> {
Keys { inner: self.iter() }
}
/// Gets an iterator over the values of the map, in order by key.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// a.insert(1, "hello");
/// a.insert(2, "goodbye");
///
/// let values: Vec<&str> = a.values().cloned().collect();
/// assert_eq!(values, ["hello", "goodbye"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn values(&self) -> Values<'_, K, V> {
Values { inner: self.iter() }
}
/// Gets a mutable iterator over the values of the map, in order by key.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// a.insert(1, String::from("hello"));
/// a.insert(2, String::from("goodbye"));
///
/// for value in a.values_mut() {
/// value.push_str("!");
/// }
///
/// let values: Vec<String> = a.values().cloned().collect();
/// assert_eq!(values, [String::from("hello!"),
/// String::from("goodbye!")]);
/// ```
#[stable(feature = "map_values_mut", since = "1.10.0")]
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
ValuesMut { inner: self.iter_mut() }
}
/// Returns the number of elements in the map.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// assert_eq!(a.len(), 0);
/// a.insert(1, "a");
/// assert_eq!(a.len(), 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn len(&self) -> usize {
self.length
}
/// Returns `true` if the map contains no elements.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// assert!(a.is_empty());
/// a.insert(1, "a");
/// assert!(!a.is_empty());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// If the root node is the empty (non-allocated) root node, allocate our
/// own node.
fn ensure_root_is_owned(&mut self) -> &mut node::Root<K, V> {
self.root.get_or_insert_with(node::Root::new_leaf)
}
}
impl<'a, K: Ord, V> Entry<'a, K, V> {
/// Ensures a value is in the entry by inserting the default if empty, and returns
/// a mutable reference to the value in the entry.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// map.entry("poneyland").or_insert(12);
///
/// assert_eq!(map["poneyland"], 12);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(default),
}
}
/// Ensures a value is in the entry by inserting the result of the default function if empty,
/// and returns a mutable reference to the value in the entry.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<&str, String> = BTreeMap::new();
/// let s = "hoho".to_string();
///
/// map.entry("poneyland").or_insert_with(|| s);
///
/// assert_eq!(map["poneyland"], "hoho".to_string());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
match self {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(default()),
}
}
#[unstable(feature = "or_insert_with_key", issue = "71024")]
/// Ensures a value is in the entry by inserting, if empty, the result of the default function,
/// which takes the key as its argument, and returns a mutable reference to the value in the
/// entry.
///
/// # Examples
///
/// ```
/// #![feature(or_insert_with_key)]
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
///
/// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
///
/// assert_eq!(map["poneyland"], 9);
/// ```
#[inline]
pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
match self {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => {
let value = default(entry.key());
entry.insert(value)
}
}
}
/// Returns a reference to this entry's key.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// assert_eq!(map.entry("poneyland").key(), &"poneyland");
/// ```
#[stable(feature = "map_entry_keys", since = "1.10.0")]
pub fn key(&self) -> &K {
match *self {
Occupied(ref entry) => entry.key(),
Vacant(ref entry) => entry.key(),
}
}
/// Provides in-place mutable access to an occupied entry before any
/// potential inserts into the map.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
///
/// map.entry("poneyland")
/// .and_modify(|e| { *e += 1 })
/// .or_insert(42);
/// assert_eq!(map["poneyland"], 42);
///
/// map.entry("poneyland")
/// .and_modify(|e| { *e += 1 })
/// .or_insert(42);
/// assert_eq!(map["poneyland"], 43);
/// ```
#[stable(feature = "entry_and_modify", since = "1.26.0")]
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut V),
{
match self {
Occupied(mut entry) => {
f(entry.get_mut());
Occupied(entry)
}
Vacant(entry) => Vacant(entry),
}
}
}
impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
#[stable(feature = "entry_or_default", since = "1.28.0")]
/// Ensures a value is in the entry by inserting the default value if empty,
/// and returns a mutable reference to the value in the entry.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
/// map.entry("poneyland").or_default();
///
/// assert_eq!(map["poneyland"], None);
/// ```
pub fn or_default(self) -> &'a mut V {
match self {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(Default::default()),
}
}
}
impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
/// Gets a reference to the key that would be used when inserting a value
/// through the VacantEntry.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// assert_eq!(map.entry("poneyland").key(), &"poneyland");
/// ```
#[stable(feature = "map_entry_keys", since = "1.10.0")]
pub fn key(&self) -> &K {
&self.key
}
/// Take ownership of the key.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
/// use std::collections::btree_map::Entry;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
///
/// if let Entry::Vacant(v) = map.entry("poneyland") {
/// v.into_key();
/// }
/// ```
#[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
pub fn into_key(self) -> K {
self.key
}
/// Sets the value of the entry with the `VacantEntry`'s key,
/// and returns a mutable reference to it.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
///
/// // count the number of occurrences of letters in the vec
/// for x in vec!["a","b","a","c","a","b"] {
/// *count.entry(x).or_insert(0) += 1;
/// }
///
/// assert_eq!(count["a"], 3);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn insert(self, value: V) -> &'a mut V {
*self.length += 1;
let out_ptr;
let mut ins_k;
let mut ins_v;
let mut ins_edge;
let mut cur_parent = match self.handle.insert(self.key, value) {
(Fit(handle), _) => return handle.into_kv_mut().1,
(Split(left, k, v, right), ptr) => {
ins_k = k;
ins_v = v;
ins_edge = right;
out_ptr = ptr;
left.ascend().map_err(|n| n.into_root_mut())
}
};
loop {
match cur_parent {
Ok(parent) => match parent.insert(ins_k, ins_v, ins_edge) {
Fit(_) => return unsafe { &mut *out_ptr },
Split(left, k, v, right) => {
ins_k = k;
ins_v = v;
ins_edge = right;
cur_parent = left.ascend().map_err(|n| n.into_root_mut());
}
},
Err(root) => {
root.push_level().push(ins_k, ins_v, ins_edge);
return unsafe { &mut *out_ptr };
}
}
}
}
}
impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
/// Gets a reference to the key in the entry.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// map.entry("poneyland").or_insert(12);
/// assert_eq!(map.entry("poneyland").key(), &"poneyland");
/// ```
#[stable(feature = "map_entry_keys", since = "1.10.0")]
pub fn key(&self) -> &K {
self.handle.reborrow().into_kv().0
}
/// Take ownership of the key and value from the map.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
/// use std::collections::btree_map::Entry;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// map.entry("poneyland").or_insert(12);
///
/// if let Entry::Occupied(o) = map.entry("poneyland") {
/// // We delete the entry from the map.
/// o.remove_entry();
/// }
///
/// // If now try to get the value, it will panic:
/// // println!("{}", map["poneyland"]);
/// ```
#[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
pub fn remove_entry(self) -> (K, V) {
self.remove_kv()
}
/// Gets a reference to the value in the entry.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
/// use std::collections::btree_map::Entry;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// map.entry("poneyland").or_insert(12);
///
/// if let Entry::Occupied(o) = map.entry("poneyland") {
/// assert_eq!(o.get(), &12);
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get(&self) -> &V {
self.handle.reborrow().into_kv().1
}
/// Gets a mutable reference to the value in the entry.
///
/// If you need a reference to the `OccupiedEntry` that may outlive the
/// destruction of the `Entry` value, see [`into_mut`].
///
/// [`into_mut`]: #method.into_mut
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
/// use std::collections::btree_map::Entry;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// map.entry("poneyland").or_insert(12);
///
/// assert_eq!(map["poneyland"], 12);
/// if let Entry::Occupied(mut o) = map.entry("poneyland") {
/// *o.get_mut() += 10;
/// assert_eq!(*o.get(), 22);
///
/// // We can use the same Entry multiple times.
/// *o.get_mut() += 2;
/// }
/// assert_eq!(map["poneyland"], 24);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get_mut(&mut self) -> &mut V {
self.handle.kv_mut().1
}
/// Converts the entry into a mutable reference to its value.
///
/// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
///
/// [`get_mut`]: #method.get_mut
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
/// use std::collections::btree_map::Entry;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// map.entry("poneyland").or_insert(12);
///
/// assert_eq!(map["poneyland"], 12);
/// if let Entry::Occupied(o) = map.entry("poneyland") {
/// *o.into_mut() += 10;
/// }
/// assert_eq!(map["poneyland"], 22);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_mut(self) -> &'a mut V {
self.handle.into_kv_mut().1
}
/// Sets the value of the entry with the `OccupiedEntry`'s key,
/// and returns the entry's old value.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
/// use std::collections::btree_map::Entry;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// map.entry("poneyland").or_insert(12);
///
/// if let Entry::Occupied(mut o) = map.entry("poneyland") {
/// assert_eq!(o.insert(15), 12);
/// }
/// assert_eq!(map["poneyland"], 15);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn insert(&mut self, value: V) -> V {
mem::replace(self.get_mut(), value)
}
/// Takes the value of the entry out of the map, and returns it.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
/// use std::collections::btree_map::Entry;
///
/// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
/// map.entry("poneyland").or_insert(12);
///
/// if let Entry::Occupied(o) = map.entry("poneyland") {
/// assert_eq!(o.remove(), 12);
/// }
/// // If we try to get "poneyland"'s value, it'll panic:
/// // println!("{}", map["poneyland"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn remove(self) -> V {
self.remove_kv().1
}
fn remove_kv(self) -> (K, V) {
*self.length -= 1;
let (old_key, old_val, _) = self.handle.remove_kv_tracking();
(old_key, old_val)
}
}
impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV> {
/// Removes a key/value-pair from the map, and returns that pair, as well as
/// the leaf edge corresponding to that former pair.
fn remove_kv_tracking(
self,
) -> (K, V, Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>) {
let (mut pos, old_key, old_val, was_internal) = match self.force() {
Leaf(leaf) => {
let (hole, old_key, old_val) = leaf.remove();
(hole, old_key, old_val, false)
}
Internal(mut internal) => {
// Replace the location freed in the internal node with the next KV,
// and remove that next KV from its leaf.
let key_loc = internal.kv_mut().0 as *mut K;
let val_loc = internal.kv_mut().1 as *mut V;
// Deleting from the left side is typically faster since we can
// just pop an element from the end of the KV array without
// needing to shift the other values.
let to_remove = internal.left_edge().descend().last_leaf_edge().left_kv().ok();
let to_remove = unsafe { unwrap_unchecked(to_remove) };
let (hole, key, val) = to_remove.remove();
let old_key = unsafe { mem::replace(&mut *key_loc, key) };
let old_val = unsafe { mem::replace(&mut *val_loc, val) };
(hole, old_key, old_val, true)
}
};
// Handle underflow
let mut cur_node = unsafe { ptr::read(&pos).into_node().forget_type() };
let mut at_leaf = true;
while cur_node.len() < node::MIN_LEN {
match handle_underfull_node(cur_node) {
AtRoot => break,
Merged(edge, merged_with_left, offset) => {
// If we merged with our right sibling then our tracked
// position has not changed. However if we merged with our
// left sibling then our tracked position is now dangling.
if at_leaf && merged_with_left {
let idx = pos.idx() + offset;
let node = match unsafe { ptr::read(&edge).descend().force() } {
Leaf(leaf) => leaf,
Internal(_) => unreachable!(),
};
pos = unsafe { Handle::new_edge(node, idx) };
}
let parent = edge.into_node();
if parent.len() == 0 {
// We must be at the root
parent.into_root_mut().pop_level();
break;
} else {
cur_node = parent.forget_type();
at_leaf = false;
}
}
Stole(stole_from_left) => {
// Adjust the tracked position if we stole from a left sibling
if stole_from_left && at_leaf {
// SAFETY: This is safe since we just added an element to our node.
unsafe {
pos.next_unchecked();
}
}
break;
}
}
}
// If we deleted from an internal node then we need to compensate for
// the earlier swap and adjust the tracked position to point to the
// next element.
if was_internal {
pos = unsafe { unwrap_unchecked(pos.next_kv().ok()).next_leaf_edge() };
}
(old_key, old_val, pos)
}
}
enum UnderflowResult<'a, K, V> {
AtRoot,
Merged(Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge>, bool, usize),
Stole(bool),
}
fn handle_underfull_node<K, V>(
node: NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal>,
) -> UnderflowResult<'_, K, V> {
let parent = match node.ascend() {
Ok(parent) => parent,
Err(_) => return AtRoot,
};
let (is_left, mut handle) = match parent.left_kv() {
Ok(left) => (true, left),
Err(parent) => {
let right = unsafe { unwrap_unchecked(parent.right_kv().ok()) };
(false, right)
}
};
if handle.can_merge() {
let offset = if is_left { handle.reborrow().left_edge().descend().len() + 1 } else { 0 };
Merged(handle.merge(), is_left, offset)
} else {
if is_left {
handle.steal_left();
} else {
handle.steal_right();
}
Stole(is_left)
}
}
impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
let res = match (self.left.peek(), self.right.peek()) {
(Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => return None,
};
// Check which elements comes first and only advance the corresponding iterator.
// If two keys are equal, take the value from `right`.
match res {
Ordering::Less => self.left.next(),
Ordering::Greater => self.right.next(),
Ordering::Equal => {
self.left.next();
self.right.next()
}
}
}
}
| 32.311475 | 100 | 0.516619 |
23b37141d8c0ad98308bfc8b5a5a09c2f3771921 | 321 | // 函数
fn main() {
fn1();
fn2(45);
let res3 = fn3(3);
println!("res3={}", res3);
}
// 无参数无返回值
fn fn1() {
println!("call fn1");
}
// 有参数无返回值
fn fn2(num: i32) {
println!("call fn2, arg num={}", num);
}
// 有参数有返回值
fn fn3(num: i32) -> i64 {
println!("call fn3");
return (num * 2).into();
}
| 12.84 | 42 | 0.492212 |
90fc4c607d53733bee3da67962915decd6832f5c | 1,062 | #[doc = "Reader of register OTPMK1"]
pub type R = crate::R<u32, super::OTPMK1>;
#[doc = "Writer for register OTPMK1"]
pub type W = crate::W<u32, super::OTPMK1>;
#[doc = "Register OTPMK1 `reset()`'s with value 0"]
impl crate::ResetValue for super::OTPMK1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `BITS`"]
pub type BITS_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `BITS`"]
pub struct BITS_W<'a> {
w: &'a mut W,
}
impl<'a> BITS_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - BITS"]
#[inline(always)]
pub fn bits_(&self) -> BITS_R {
BITS_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - BITS"]
#[inline(always)]
pub fn bits_(&mut self) -> BITS_W {
BITS_W { w: self }
}
}
| 25.902439 | 84 | 0.562147 |
7998674235050a6d689d8af8b76f228fec604b38 | 1,839 | use std::fmt::Debug;
use std::sync::Arc;
use snafu::{ResultExt, Snafu};
use tokio::net::TcpListener;
use tokio_stream::wrappers::TcpListenerStream;
use data_types::error::ErrorLogger;
use server::{ConnectionManager, Server};
pub mod error;
mod flight;
mod management;
mod storage;
mod testing;
mod write;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("gRPC server error: {}", source))]
ServerError { source: tonic::transport::Error },
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Instantiate a server listening on the specified address
/// implementing the IOx, Storage, and Flight gRPC interfaces, the
/// underlying hyper server instance. Resolves when the server has
/// shutdown.
pub async fn make_server<M>(socket: TcpListener, server: Arc<Server<M>>) -> Result<()>
where
M: ConnectionManager + Send + Sync + Debug + 'static,
{
let stream = TcpListenerStream::new(socket);
let (mut health_reporter, health_service) = tonic_health::server::health_reporter();
let services = [
generated_types::STORAGE_SERVICE,
generated_types::IOX_TESTING_SERVICE,
generated_types::ARROW_SERVICE,
];
for service in &services {
health_reporter
.set_service_status(service, tonic_health::ServingStatus::Serving)
.await;
}
tonic::transport::Server::builder()
.add_service(health_service)
.add_service(testing::make_server())
.add_service(storage::make_server(Arc::clone(&server)))
.add_service(flight::make_server(Arc::clone(&server)))
.add_service(write::make_server(Arc::clone(&server)))
.add_service(management::make_server(server))
.serve_with_incoming(stream)
.await
.context(ServerError {})
.log_if_error("Running Tonic Server")
}
| 29.66129 | 88 | 0.68298 |
f5fc6f7190d50675f952e735d3af48f52ba18967 | 479 | // cargo run -p conversion --bin expression2
#[allow(unused_must_use)]
fn main() {
let x = 5u32;
let y = {
let x_squared = x * x;
let x_cube = x_squared * x;
// This expression will be assigned to `y`
x_cube + x_squared + x
};
let z = {
// The semicolon suppresses this expression and `()` is assigned to `z`
2 * x;
};
println!("x is {}", x);
println!("y is {}", y);
println!("z is {:?}", z);
} | 20.826087 | 79 | 0.505219 |
d6fcf2fbca4aaee7b5b8406ef0123798edf3bfd3 | 425 | use crate::extn::prelude::*;
pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {
if interp.is_class_defined::<Range>() {
return Ok(());
}
let spec = class::Spec::new("Range", None, None)?;
interp.def_class::<Range>(spec)?;
let _ = interp.eval(&include_bytes!("range.rb")[..])?;
trace!("Patched Range onto interpreter");
Ok(())
}
#[derive(Debug, Clone, Copy)]
pub struct Range;
| 26.5625 | 61 | 0.604706 |
216f0ea61971833499c833936c72966ed445eefc | 2,007 | #[doc = "Reader of register AESAKEY"]
pub type R = crate::R<u16, super::AESAKEY>;
#[doc = "Writer for register AESAKEY"]
pub type W = crate::W<u16, super::AESAKEY>;
#[doc = "Register AESAKEY `reset()`'s with value 0"]
impl crate::ResetValue for super::AESAKEY {
type Type = u16;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `AESKEY0`"]
pub type AESKEY0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `AESKEY0`"]
pub struct AESKEY0_W<'a> {
w: &'a mut W,
}
impl<'a> AESKEY0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0xff) | ((value as u16) & 0xff);
self.w
}
}
#[doc = "Reader of field `AESKEY1`"]
pub type AESKEY1_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `AESKEY1`"]
pub struct AESKEY1_W<'a> {
w: &'a mut W,
}
impl<'a> AESKEY1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u16) & 0xff) << 8);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - 7:0\\]
AES key byte n when AESAKEY is written as half-word"]
#[inline(always)]
pub fn aeskey0(&self) -> AESKEY0_R {
AESKEY0_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - 15:8\\]
AES key byte n+1 when AESAKEY is written as half-word"]
#[inline(always)]
pub fn aeskey1(&self) -> AESKEY1_R {
AESKEY1_R::new(((self.bits >> 8) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - 7:0\\]
AES key byte n when AESAKEY is written as half-word"]
#[inline(always)]
pub fn aeskey0(&mut self) -> AESKEY0_W {
AESKEY0_W { w: self }
}
#[doc = "Bits 8:15 - 15:8\\]
AES key byte n+1 when AESAKEY is written as half-word"]
#[inline(always)]
pub fn aeskey1(&mut self) -> AESKEY1_W {
AESKEY1_W { w: self }
}
}
| 29.086957 | 84 | 0.570503 |
907ff43202285c1992a5d68bddeed2d3979ebf15 | 3,960 | /*
* Copyright 2018 Intel Corporation
* Copyright 2019 Cargill Incorporated
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ------------------------------------------------------------------------------
*/
use std::fs::{self, OpenOptions};
use std::io::prelude::*;
use std::os::unix::fs::OpenOptionsExt;
use std::path::PathBuf;
use sawtooth_sdk::signing;
use users::get_current_username;
use crate::error::CliError;
/// Generates a public/private key pair that can be used to sign transactions.
/// If no directory is provided, the keys are created in the default directory
///
/// $HOME/.grid/keys/
///
/// If no key_name is provided the key name is set to USER environment variable.
pub fn generate_keys(
key_name: Option<&str>,
force: bool,
key_directory: Option<&str>,
) -> Result<(), CliError> {
let key_name = match key_name {
Some(name) => name.to_string(),
None => get_current_username()
.ok_or(0)
.and_then(|os_str| os_str.into_string().map_err(|_| 0))
.map_err(|_| {
CliError::UserError(String::from(
"Could not determine key name, please provide one.",
))
})?,
};
let key_dir = match key_directory {
Some(path) => {
let dir = PathBuf::from(&path);
if !dir.exists() {
return Err(CliError::UserError(format!("No such directory: {}", path)));
}
dir
}
None => {
let key_path = dirs::home_dir()
.ok_or_else(|| {
CliError::UserError(String::from("Unable to determine home directory"))
})
.map(|mut p| {
p.push(".grid");
p.push("keys");
p
})?;
if !key_path.exists() {
fs::create_dir_all(key_path.clone())?;
}
key_path
}
};
let mut public_key_path = key_dir.clone();
public_key_path.push(format!("{}.pub", &key_name));
let mut private_key_path = key_dir.clone();
private_key_path.push(format!("{}.priv", &key_name));
if (public_key_path.exists() || private_key_path.exists()) && !force {
return Err(CliError::UserError(format!(
"Key files already exist at {:?}. Rerun with --force to overwrite existing files",
key_dir
)));
}
let context = signing::create_context("secp256k1")?;
let private_key = context.new_random_private_key()?;
let public_key = context.get_public_key(&*private_key)?;
if public_key_path.exists() {
info!("Overwriting file: {}", &public_key_path.display());
} else {
info!("Writing file: {}", &public_key_path.display());
}
let public_key_file = OpenOptions::new()
.write(true)
.create(true)
.mode(0o644)
.open(public_key_path.as_path())?;
writeln!(&public_key_file, "{}", public_key.as_hex())?;
if private_key_path.exists() {
info!("Overwriting file: {}", &private_key_path.display());
} else {
info!("Writing file: {}", &private_key_path.display());
}
let private_key_file = OpenOptions::new()
.write(true)
.create(true)
.mode(0o640)
.open(private_key_path.as_path())?;
writeln!(&private_key_file, "{}", &private_key.as_hex())?;
Ok(())
}
| 32.195122 | 94 | 0.575 |
f9ba53d20533ba549890663c8199a4fd55d14d5f | 497 | #[derive(Debug, Clone)]
pub struct UserInfo {
pub name: String,
}
impl UserInfo {
pub fn new(name: String) -> Self {
UserInfo {
name
}
}
}
fn main() {
let name = String::from("mhb");
let user_info = UserInfo::new(name);
println!("user_info: {:?}", user_info);
let copied_user_info = user_info.clone();
println!("copied_user_info: {:?}", copied_user_info);
println!("user_info: {:?}", user_info);
println!("Hello, world!");
}
| 19.88 | 57 | 0.571429 |
6467986f66fdf831d1f14b185a6f025df0b7b1c2 | 34 | pub mod ansii;
pub mod vga_buffer; | 17 | 19 | 0.794118 |
5bb1dd07245a9bac0337e26dad5ed543fa4d4c14 | 407 | /*!
A submodule for testing the DocTree constructor function.
Copyright © 2020 Santtu Söderholm
*/
use super::*;
#[cfg(test)]
#[test]
fn new_doctree() {
let doc_name = PathBuf::from("abc");
let dt = DocTree::new(doc_name);
let root_is_root: bool = match dt.shared_node().shared_data() {
TreeNodeType::Document { .. } => true,
_ => false,
};
assert!(root_is_root);
}
| 18.5 | 67 | 0.621622 |
28f89d6a76b9edd9ee39168a82285f30eeff5f62 | 6,000 | #![allow(dead_code)]
use std::arch::x86_64::*;
use std::fmt;
#[derive(Clone, Copy, Debug)]
pub struct AVX2VectorBuilder(());
impl AVX2VectorBuilder {
pub fn new() -> Option<AVX2VectorBuilder> {
if is_x86_feature_detected!("avx2") {
Some(AVX2VectorBuilder(()))
} else {
None
}
}
/// Create a new u8x32 AVX2 vector where all of the bytes are set to
/// the given value.
#[inline]
pub fn u8x32_splat(self, n: u8) -> u8x32 {
// Safe because we know AVX2 is enabled.
unsafe { u8x32::splat(n) }
}
/// Load 32 bytes from the given slice, with bounds checks.
#[inline]
pub fn u8x32_load_unaligned(self, slice: &[u8]) -> u8x32 {
// Safe because we know AVX2 is enabled.
unsafe { u8x32::load_unaligned(slice) }
}
/// Load 32 bytes from the given slice, without bounds checks.
#[inline]
pub unsafe fn u8x32_load_unchecked_unaligned(self, slice: &[u8]) -> u8x32 {
// Safe because we know AVX2 is enabled, but still unsafe
// because we aren't doing bounds checks.
u8x32::load_unchecked_unaligned(slice)
}
/// Load 32 bytes from the given slice, with bound and alignment checks.
#[inline]
pub fn u8x32_load(self, slice: &[u8]) -> u8x32 {
// Safe because we know AVX2 is enabled.
unsafe { u8x32::load(slice) }
}
/// Load 32 bytes from the given slice, without bound or alignment checks.
#[inline]
pub unsafe fn u8x32_load_unchecked(self, slice: &[u8]) -> u8x32 {
// Safe because we know AVX2 is enabled, but still unsafe
// because we aren't doing bounds checks.
u8x32::load_unchecked(slice)
}
}
// We define our union with a macro so that our code continues to compile on
// Rust 1.12.
macro_rules! defunion {
() => {
#[derive(Clone, Copy)]
#[allow(non_camel_case_types)]
pub union u8x32 {
vector: __m256i,
bytes: [u8; 32],
}
}
}
defunion!();
impl u8x32 {
#[inline]
unsafe fn splat(n: u8) -> u8x32 {
u8x32 { vector: _mm256_set1_epi8(n as i8) }
}
#[inline]
unsafe fn load_unaligned(slice: &[u8]) -> u8x32 {
assert!(slice.len() >= 32);
u8x32::load_unchecked_unaligned(slice)
}
#[inline]
unsafe fn load_unchecked_unaligned(slice: &[u8]) -> u8x32 {
let p = slice.as_ptr() as *const u8 as *const __m256i;
u8x32 { vector: _mm256_loadu_si256(p) }
}
#[inline]
unsafe fn load(slice: &[u8]) -> u8x32 {
assert!(slice.len() >= 32);
assert!(slice.as_ptr() as usize % 32 == 0);
u8x32::load_unchecked(slice)
}
#[inline]
unsafe fn load_unchecked(slice: &[u8]) -> u8x32 {
let p = slice.as_ptr() as *const u8 as *const __m256i;
u8x32 { vector: _mm256_load_si256(p) }
}
#[inline]
pub fn extract(self, i: usize) -> u8 {
// Safe because `bytes` is always accessible.
unsafe { self.bytes[i] }
}
#[inline]
pub fn replace(&mut self, i: usize, byte: u8) {
// Safe because `bytes` is always accessible.
unsafe { self.bytes[i] = byte; }
}
#[inline]
pub fn shuffle(self, indices: u8x32) -> u8x32 {
// Safe because we know AVX2 is enabled.
unsafe {
u8x32 { vector: _mm256_shuffle_epi8(self.vector, indices.vector) }
}
}
#[inline]
pub fn ne(self, other: u8x32) -> u8x32 {
// Safe because we know AVX2 is enabled.
unsafe {
let boolv = _mm256_cmpeq_epi8(self.vector, other.vector);
let ones = _mm256_set1_epi8(0xFF as u8 as i8);
u8x32 { vector: _mm256_andnot_si256(boolv, ones) }
}
}
#[inline]
pub fn and(self, other: u8x32) -> u8x32 {
// Safe because we know AVX2 is enabled.
unsafe {
u8x32 { vector: _mm256_and_si256(self.vector, other.vector) }
}
}
#[inline]
pub fn movemask(self) -> u32 {
// Safe because we know AVX2 is enabled.
unsafe {
_mm256_movemask_epi8(self.vector) as u32
}
}
#[inline]
pub fn alignr_14(self, other: u8x32) -> u8x32 {
// Safe because we know AVX2 is enabled.
unsafe {
// Credit goes to jneem for figuring this out:
// https://github.com/jneem/teddy/blob/9ab5e899ad6ef6911aecd3cf1033f1abe6e1f66c/src/x86/teddy_simd.rs#L145-L184
//
// TL;DR avx2's PALIGNR instruction is actually just two 128-bit
// PALIGNR instructions, which is not what we want, so we need to
// do some extra shuffling.
let v = _mm256_permute2x128_si256(other.vector, self.vector, 0x21);
let v = _mm256_alignr_epi8(self.vector, v, 14);
u8x32 { vector: v }
}
}
#[inline]
pub fn alignr_15(self, other: u8x32) -> u8x32 {
// Safe because we know AVX2 is enabled.
unsafe {
// Credit goes to jneem for figuring this out:
// https://github.com/jneem/teddy/blob/9ab5e899ad6ef6911aecd3cf1033f1abe6e1f66c/src/x86/teddy_simd.rs#L145-L184
//
// TL;DR avx2's PALIGNR instruction is actually just two 128-bit
// PALIGNR instructions, which is not what we want, so we need to
// do some extra shuffling.
let v = _mm256_permute2x128_si256(other.vector, self.vector, 0x21);
let v = _mm256_alignr_epi8(self.vector, v, 15);
u8x32 { vector: v }
}
}
#[inline]
pub fn bit_shift_right_4(self) -> u8x32 {
// Safe because we know AVX2 is enabled.
unsafe {
u8x32 { vector: _mm256_srli_epi16(self.vector, 4) }
}
}
}
impl fmt::Debug for u8x32 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Safe because `bytes` is always accessible.
unsafe { self.bytes.fmt(f) }
}
}
| 30.612245 | 123 | 0.5795 |
e6e678436c14045ad7181ba6febaf31e30f1d7ce | 1,350 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::fmt;
use {Args, Context, MessagePart};
/// A string that should be output. Used for the text in between
/// formats.
#[derive(Debug, PartialEq)]
pub struct PlainText {
/// The text that should be output.
pub text: String,
}
impl PlainText {
/// Construct a `PlainText`.
pub fn new(text: &str) -> Self {
PlainText {
text: text.to_string(),
}
}
}
impl MessagePart for PlainText {
fn apply_format(
&self,
_ctx: &Context,
stream: &mut dyn fmt::Write,
_args: &dyn Args,
) -> fmt::Result {
stream.write_str(self.text.as_str())?;
Ok(())
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(test)]
mod tests {
use super::PlainText;
use {Context, Message};
#[test]
fn it_works() {
let ctx = Context::default();
let msg = Message::new(vec![Box::new(PlainText::new("Test text."))]);
let output = format_message!(ctx, &msg);
assert_eq!("Test text.", output);
}
}
| 23.275862 | 77 | 0.593333 |
b9feab6e5cf8b8d06c1d3431b738b5c231affd88 | 3,481 | use crate::issues::*;
pub fn validate(gtfs: >fs_structures::Gtfs) -> Vec<Issue> {
let missing_price = gtfs
.fare_attributes
.values()
.filter(|fare_attributes| !has_price(*fare_attributes))
.map(|fare_attributes| make_issue(fare_attributes, IssueType::MissingPrice));
let invalid_currency = gtfs
.fare_attributes
.values()
.filter(|fare_attributes| !valid_currency(*fare_attributes))
.map(|fare_attributes| make_issue(fare_attributes, IssueType::InvalidCurrency));
let invalid_transfers = gtfs
.fare_attributes
.values()
.filter(|fare_attributes| !valid_transfers(*fare_attributes))
.map(|fare_attributes| make_issue(fare_attributes, IssueType::InvalidTransfers));
let invalid_duration = gtfs
.fare_attributes
.values()
.filter(|fare_attributes| !valid_duration(*fare_attributes))
.map(|fare_attributes| make_issue(fare_attributes, IssueType::InvalidTransferDuration));
missing_price
.chain(invalid_currency)
.chain(invalid_transfers)
.chain(invalid_duration)
.collect()
}
fn make_issue<T: gtfs_structures::Id>(o: &T, issue_type: IssueType) -> Issue {
Issue::new(Severity::Error, issue_type, o.id()).object_type(gtfs_structures::ObjectType::Fare)
}
fn has_price(fare_attributes: >fs_structures::FareAttribute) -> bool {
!fare_attributes.price.is_empty()
}
fn valid_currency(fare_attributes: >fs_structures::FareAttribute) -> bool {
iso4217::alpha3(&fare_attributes.currency).is_some()
}
fn valid_transfers(fare_attributes: >fs_structures::FareAttribute) -> bool {
!matches!(
fare_attributes.transfers,
gtfs_structures::Transfers::Other(_)
)
}
fn valid_duration(fare_attributes: >fs_structures::FareAttribute) -> bool {
fare_attributes.transfer_duration.is_none() || fare_attributes.transfer_duration >= Some(0)
}
#[test]
fn test_missing_price() {
let gtfs = gtfs_structures::Gtfs::new("test_data/fare_attributes").unwrap();
let issues = validate(>fs);
let missing_price_issue: Vec<_> = issues
.iter()
.filter(|issue| issue.issue_type == IssueType::MissingPrice)
.collect();
assert_eq!(1, missing_price_issue.len());
assert_eq!("50", missing_price_issue[0].object_id);
assert_eq!(IssueType::MissingPrice, missing_price_issue[0].issue_type);
}
#[test]
fn test_valid_currency() {
let gtfs = gtfs_structures::Gtfs::new("test_data/fare_attributes").unwrap();
let issues = validate(>fs);
let invalid_currency_issue: Vec<_> = issues
.iter()
.filter(|issue| issue.issue_type == IssueType::InvalidCurrency)
.collect();
assert_eq!(1, invalid_currency_issue.len());
assert_eq!("61", invalid_currency_issue[0].object_id);
assert_eq!(
IssueType::InvalidCurrency,
invalid_currency_issue[0].issue_type
);
}
#[test]
fn test_valid_transfers() {
let gtfs = gtfs_structures::Gtfs::new("test_data/fare_attributes").unwrap();
let issues = validate(>fs);
let invalid_transfers_issue: Vec<_> = issues
.iter()
.filter(|issue| issue.issue_type == IssueType::InvalidTransfers)
.collect();
assert_eq!(1, invalid_transfers_issue.len());
assert_eq!("61", invalid_transfers_issue[0].object_id);
assert_eq!(
IssueType::InvalidTransfers,
invalid_transfers_issue[0].issue_type
);
}
| 34.465347 | 98 | 0.688021 |
22009fb0535fd7abf68b8ae2f95f7981c297d8ca | 1,579 | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright 2018-2021 Robonomics Network <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
//! Set of approaches to handle economical aspects of agreement.
use crate::traits::Economical;
use frame_support::traits::Currency;
///
/// Well, when we get communism it'll all be fucking great.
/// It will come soon, we just have to wait.
/// Everything will be free there, everything will be an upper.
/// We'll probably not even have to die.
///
pub struct Communism;
impl Economical for Communism {
// No parameters, because everything is free.
type Parameter = ();
}
/// Open market as approach for liability price estimation.
pub struct OpenMarket<T, A>(sp_std::marker::PhantomData<(T, A)>);
impl<T: Currency<A>, A> Economical for OpenMarket<T, A> {
// Price as economical parameter for liability.
type Parameter = <T as Currency<A>>::Balance;
}
| 38.512195 | 79 | 0.648512 |
0e6babf79f5facf64a82624d9c48440130b5a3e9 | 4,157 | // Generated from definition io.k8s.api.core.v1.ResourceQuotaStatus
/// ResourceQuotaStatus defines the enforced hard limits and observed use.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ResourceQuotaStatus {
/// Hard is the set of enforced hard limits for each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/
pub hard: Option<::std::collections::BTreeMap<String, ::v1_12::apimachinery::pkg::api::resource::Quantity>>,
/// Used is the current observed total usage of the resource in the namespace.
pub used: Option<::std::collections::BTreeMap<String, ::v1_12::apimachinery::pkg::api::resource::Quantity>>,
}
impl<'de> ::serde::Deserialize<'de> for ResourceQuotaStatus {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_hard,
Key_used,
Other,
}
impl<'de> ::serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'de> {
struct Visitor;
impl<'de> ::serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: ::serde::de::Error {
Ok(match v {
"hard" => Field::Key_hard,
"used" => Field::Key_used,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> ::serde::de::Visitor<'de> for Visitor {
type Value = ResourceQuotaStatus;
fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "struct ResourceQuotaStatus")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: ::serde::de::MapAccess<'de> {
let mut value_hard: Option<::std::collections::BTreeMap<String, ::v1_12::apimachinery::pkg::api::resource::Quantity>> = None;
let mut value_used: Option<::std::collections::BTreeMap<String, ::v1_12::apimachinery::pkg::api::resource::Quantity>> = None;
while let Some(key) = ::serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_hard => value_hard = ::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_used => value_used = ::serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: ::serde::de::IgnoredAny = ::serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(ResourceQuotaStatus {
hard: value_hard,
used: value_used,
})
}
}
deserializer.deserialize_struct(
"ResourceQuotaStatus",
&[
"hard",
"used",
],
Visitor,
)
}
}
impl ::serde::Serialize for ResourceQuotaStatus {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer {
let mut state = serializer.serialize_struct(
"ResourceQuotaStatus",
0 +
self.hard.as_ref().map_or(0, |_| 1) +
self.used.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.hard {
::serde::ser::SerializeStruct::serialize_field(&mut state, "hard", value)?;
}
if let Some(value) = &self.used {
::serde::ser::SerializeStruct::serialize_field(&mut state, "used", value)?;
}
::serde::ser::SerializeStruct::end(state)
}
}
| 40.754902 | 143 | 0.526582 |
87688fb62050d388503444fd10d7984a29ab8126 | 1,813 | use axum::{extract::Extension, Json};
use domain::UsersManager;
use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::{
app_request::{AuthUser, ValidatedPath},
app_response::AppError,
AppState,
};
#[derive(Default, Deserialize, Debug, Clone, Validate)]
pub struct FavoriteForm {
#[validate(range(min = 1, message = "id not correct"))]
id: i64,
}
#[derive(Serialize)]
pub struct FavoriteResponse {
favorited: bool,
}
enum Action {
Favorite,
Unfavorite,
}
#[tracing::instrument(skip(auth_user, state))]
pub async fn favorite(
ValidatedPath(form): ValidatedPath<FavoriteForm>,
AuthUser(auth_user): AuthUser,
Extension(state): Extension<AppState>,
) -> Result<Json<FavoriteResponse>, AppError> {
process(form, AuthUser(auth_user), state, Action::Favorite).await
}
#[tracing::instrument(skip(auth_user, state))]
pub async fn unfavorite(
ValidatedPath(form): ValidatedPath<FavoriteForm>,
AuthUser(auth_user): AuthUser,
Extension(state): Extension<AppState>,
) -> Result<Json<FavoriteResponse>, AppError> {
process(form, AuthUser(auth_user), state, Action::Unfavorite).await
}
async fn process(
form: FavoriteForm,
AuthUser(auth_user): AuthUser,
state: AppState,
action: Action,
) -> Result<Json<FavoriteResponse>, AppError> {
let manager = &state.users_manager;
let user = manager.get_user_by_username(auth_user.get_name()).await?;
match action {
Action::Favorite => {
user.favorite(form.id, &state.favorites_manager).await?;
Ok(FavoriteResponse { favorited: true }.into())
}
Action::Unfavorite => {
user.unfavorite(form.id, &state.favorites_manager).await?;
Ok(FavoriteResponse { favorited: false }.into())
}
}
}
| 26.661765 | 73 | 0.677882 |
fe5e30c113591ccd2fdfed7b2be8a40bcd2843a2 | 4,382 | // This file is part of Substrate.
// Copyright (C) 2018-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Test utilities
#![cfg(test)]
use sp_runtime::{
traits::IdentityLookup,
testing::Header,
};
use sp_core::H256;
use sp_io;
use frame_support::parameter_types;
use frame_support::weights::{Weight, DispatchInfo, IdentityFee};
use pallet_transaction_payment::CurrencyAdapter;
use crate::{
self as pallet_balances,
Pallet, Config, decl_tests,
};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
}
);
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub BlockWeights: frame_system::limits::BlockWeights =
frame_system::limits::BlockWeights::simple_max(1024);
pub static ExistentialDeposit: u64 = 0;
}
impl frame_system::Config for Test {
type BaseCallFilter = ();
type BlockWeights = BlockWeights;
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Call = Call;
type Hash = H256;
type Hashing = ::sp_runtime::traits::BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = super::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
}
parameter_types! {
pub const TransactionByteFee: u64 = 1;
}
impl pallet_transaction_payment::Config for Test {
type OnChargeTransaction = CurrencyAdapter<Pallet<Test>, ()>;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = IdentityFee<u64>;
type FeeMultiplierUpdate = ();
}
parameter_types! {
pub const DailyLimit: u64 = 1_000_000_000_000_000_000;
pub const MonthlyLimit: u64 = 1_000_000_000_000_000_000;
pub const YearlyLimit: u64 = 1_000_000_000_000_000_000;
}
impl Config for Test {
type Balance = u64;
type DustRemoval = ();
type Event = Event;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = frame_system::Pallet<Test>;
type MaxLocks = ();
type WeightInfo = ();
type DailyLimit = DailyLimit;
type MonthlyLimit = MonthlyLimit;
type YearlyLimit = YearlyLimit;
}
pub struct ExtBuilder {
existential_deposit: u64,
monied: bool,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self {
existential_deposit: 1,
monied: false,
}
}
}
impl ExtBuilder {
pub fn existential_deposit(mut self, existential_deposit: u64) -> Self {
self.existential_deposit = existential_deposit;
self
}
pub fn monied(mut self, monied: bool) -> Self {
self.monied = monied;
self
}
pub fn set_associated_consts(&self) {
EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit);
}
pub fn build(self) -> sp_io::TestExternalities {
self.set_associated_consts();
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: if self.monied {
vec![
(1, 10 * self.existential_deposit),
(2, 20 * self.existential_deposit),
(3, 30 * self.existential_deposit),
(4, 40 * self.existential_deposit),
(12, 10 * self.existential_deposit)
]
} else {
vec![]
},
}.assimilate_storage(&mut t).unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
}
decl_tests!{ Test, ExtBuilder, EXISTENTIAL_DEPOSIT } | 28.640523 | 86 | 0.727065 |
71730b21ea47059048aae26a9cda816ea7646c88 | 12,406 | // Copyright 2019 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Interface to the operating system's random number generator.
//!
//! # Supported targets
//!
//! | Target | Target Triple | Implementation
//! | ----------------- | ------------------ | --------------
//! | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random` |
//! | Windows | `*‑windows‑*` | [`BCryptGenRandom`][3] |
//! | macOS | `*‑apple‑darwin` | [`getentropy()`][19] if available, otherwise [`/dev/random`][20] (identical to `/dev/urandom`)
//! | iOS | `*‑apple‑ios` | [`SecRandomCopyBytes`][4]
//! | FreeBSD | `*‑freebsd` | [`getrandom()`][21] if available, otherwise [`kern.arandom`][5]
//! | OpenBSD | `*‑openbsd` | [`getentropy`][6]
//! | NetBSD | `*‑netbsd` | [`kern.arandom`][7]
//! | Dragonfly BSD | `*‑dragonfly` | [`getrandom()`][22] if available, otherwise [`/dev/random`][8]
//! | Solaris, illumos | `*‑solaris`, `*‑illumos` | [`getrandom()`][9] if available, otherwise [`/dev/random`][10]
//! | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`][11]
//! | Redox | `*‑redox` | [`/dev/urandom`][12]
//! | Haiku | `*‑haiku` | `/dev/random` (identical to `/dev/urandom`)
//! | Hermit | `x86_64-*-hermit` | [`RDRAND`][18]
//! | SGX | `x86_64‑*‑sgx` | [RDRAND][18]
//! | VxWorks | `*‑wrs‑vxworks‑*` | `randABytes` after checking entropy pool initialization with `randSecure`
//! | Emscripten | `*‑emscripten` | `/dev/random` (identical to `/dev/urandom`)
//! | WASI | `wasm32‑wasi` | [`random_get`][17]
//! | Web Browser | `wasm32‑*‑unknown` | [`Crypto.getRandomValues()`][14], see [WebAssembly support][16]
//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomBytes`][15], see [WebAssembly support][16]
//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
//!
//! There is no blanket implementation on `unix` targets that reads from
//! `/dev/urandom`. This ensures all supported targets are using the recommended
//! interface and respect maximum buffer sizes.
//!
//! Pull Requests that add support for new targets to `getrandom` are always welcome.
//!
//! ## Unsupported targets
//!
//! By default, `getrandom` will not compile on unsupported targets, but certain
//! features allow a user to select a "fallback" implementation if no supported
//! implementation exists.
//!
//! All of the below mechanisms only affect unsupported
//! targets. Supported targets will _always_ use their supported implementations.
//! This prevents a crate from overriding a secure source of randomness
//! (either accidentally or intentionally).
//!
//! ### RDRAND on x86
//!
//! *If the `"rdrand"` Cargo feature is enabled*, `getrandom` will fallback to using
//! the [`RDRAND`][18] instruction to get randomness on `no_std` `x86`/`x86_64`
//! targets. This feature has no effect on other CPU architectures.
//!
//! ### WebAssembly support
//!
//! This crate fully supports the
//! [`wasm32-wasi`](https://github.com/CraneStation/wasi) and
//! [`wasm32-unknown-emscripten`](https://www.hellorust.com/setup/emscripten/)
//! targets. However, the `wasm32-unknown-unknown` target (i.e. the target used
//! by `wasm-pack`) is not automatically
//! supported since, from the target name alone, we cannot deduce which
//! JavaScript interface is in use (or if JavaScript is available at all).
//!
//! Instead, *if the `"js"` Cargo feature is enabled*, this crate will assume
//! that you are building for an environment containing JavaScript, and will
//! call the appropriate methods. Both web browser (main window and Web Workers)
//! and Node.js environments are supported, invoking the methods
//! [described above](#supported-targets) using the
//! [wasm-bindgen](https://github.com/rust-lang/rust-bindgen) toolchain.
//!
//! This feature has no effect on targets other than `wasm32-unknown-unknown`.
//!
//! ### Custom implementations
//!
//! The [`register_custom_getrandom!`] macro allows a user to mark their own
//! function as the backing implementation for [`getrandom`]. See the macro's
//! documentation for more information about writing and registering your own
//! custom implementations.
//!
//! Note that registering a custom implementation only has an effect on targets
//! that would otherwise not compile. Any supported targets (including those
//! using `"rdrand"` and `"js"` Cargo features) continue using their normal
//! implementations even if a function is registered.
//!
//! ### Indirect Dependencies
//!
//! If `getrandom` is not a direct dependency of your crate, you can still
//! enable any of the above fallback behaviors by enabling the relevant
//! feature in your root crate's `Cargo.toml`:
//! ```toml
//! [dependencies]
//! getrandom = { version = "0.2", features = ["js"] }
//! ```
//!
//! ## Early boot
//!
//! Sometimes, early in the boot process, the OS has not collected enough
//! entropy to securely seed its RNG. This is especially common on virtual
//! machines, where standard "random" events are hard to come by.
//!
//! Some operating system interfaces always block until the RNG is securely
//! seeded. This can take anywhere from a few seconds to more than a minute.
//! A few (Linux, NetBSD and Solaris) offer a choice between blocking and
//! getting an error; in these cases, we always choose to block.
//!
//! On Linux (when the `getrandom` system call is not available), reading from
//! `/dev/urandom` never blocks, even when the OS hasn't collected enough
//! entropy yet. To avoid returning low-entropy bytes, we first poll
//! `/dev/random` and only switch to `/dev/urandom` once this has succeeded.
//!
//! ## Error handling
//!
//! We always choose failure over returning insecure "random" bytes. In general,
//! on supported platforms, failure is highly unlikely, though not impossible.
//! If an error does occur, then it is likely that it will occur on every call to
//! `getrandom`, hence after the first successful call one can be reasonably
//! confident that no errors will occur.
//!
//! [1]: http://man7.org/linux/man-pages/man2/getrandom.2.html
//! [2]: http://man7.org/linux/man-pages/man4/urandom.4.html
//! [3]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom
//! [4]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc
//! [5]: https://www.freebsd.org/cgi/man.cgi?query=random&sektion=4
//! [6]: https://man.openbsd.org/getentropy.2
//! [7]: https://man.netbsd.org/sysctl.7
//! [8]: https://leaf.dragonflybsd.org/cgi/web-man?command=random§ion=4
//! [9]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html
//! [10]: https://docs.oracle.com/cd/E86824_01/html/E54777/random-7d.html
//! [11]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw
//! [12]: https://github.com/redox-os/randd/blob/master/src/main.rs
//! [14]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues
//! [15]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
//! [16]: #webassembly-support
//! [17]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
//! [18]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
//! [19]: https://www.unix.com/man-page/mojave/2/getentropy/
//! [20]: https://www.unix.com/man-page/mojave/4/random/
//! [21]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable
//! [22]: https://leaf.dragonflybsd.org/cgi/web-man?command=getrandom
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://docs.rs/getrandom/0.2.3"
)]
#![no_std]
#![warn(rust_2018_idioms, unused_lifetimes, missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#[macro_use]
extern crate cfg_if;
mod error;
mod util;
// To prevent a breaking change when targets are added, we always export the
// register_custom_getrandom macro, so old Custom RNG crates continue to build.
#[cfg(feature = "custom")]
mod custom;
#[cfg(feature = "std")]
mod error_impls;
pub use crate::error::Error;
// System-specific implementations.
//
// These should all provide getrandom_inner with the same signature as getrandom.
cfg_if! {
if #[cfg(any(target_os = "emscripten", target_os = "haiku",
target_os = "redox"))] {
mod util_libc;
#[path = "use_file.rs"] mod imp;
} else if #[cfg(any(target_os = "android", target_os = "linux"))] {
mod util_libc;
mod use_file;
#[path = "linux_android.rs"] mod imp;
} else if #[cfg(any(target_os = "illumos", target_os = "solaris"))] {
mod util_libc;
mod use_file;
#[path = "solaris_illumos.rs"] mod imp;
} else if #[cfg(any(target_os = "freebsd", target_os = "netbsd"))] {
mod util_libc;
#[path = "bsd_arandom.rs"] mod imp;
} else if #[cfg(target_os = "dragonfly")] {
mod util_libc;
mod use_file;
#[path = "dragonfly.rs"] mod imp;
} else if #[cfg(target_os = "fuchsia")] {
#[path = "fuchsia.rs"] mod imp;
} else if #[cfg(target_os = "ios")] {
#[path = "ios.rs"] mod imp;
} else if #[cfg(target_os = "macos")] {
mod util_libc;
mod use_file;
#[path = "macos.rs"] mod imp;
} else if #[cfg(target_os = "openbsd")] {
mod util_libc;
#[path = "openbsd.rs"] mod imp;
} else if #[cfg(target_os = "wasi")] {
#[path = "wasi.rs"] mod imp;
} else if #[cfg(all(target_arch = "x86_64", target_os = "hermit"))] {
#[path = "rdrand.rs"] mod imp;
} else if #[cfg(target_os = "vxworks")] {
mod util_libc;
#[path = "vxworks.rs"] mod imp;
} else if #[cfg(target_os = "solid_asp3")] {
#[path = "solid.rs"] mod imp;
} else if #[cfg(windows)] {
#[path = "windows.rs"] mod imp;
} else if #[cfg(all(target_arch = "x86_64", target_env = "sgx"))] {
#[path = "rdrand.rs"] mod imp;
} else if #[cfg(all(feature = "rdrand",
any(target_arch = "x86_64", target_arch = "x86")))] {
#[path = "rdrand.rs"] mod imp;
} else if #[cfg(all(feature = "js",
target_arch = "wasm32", target_os = "unknown"))] {
#[path = "js.rs"] mod imp;
} else if #[cfg(feature = "custom")] {
use custom as imp;
} else if #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] {
compile_error!("the wasm32-unknown-unknown target is not supported by \
default, you may need to enable the \"js\" feature. \
For more information see: \
https://docs.rs/getrandom/#webassembly-support");
} else {
compile_error!("target is not supported, for more information see: \
https://docs.rs/getrandom/#unsupported-targets");
}
}
/// Fill `dest` with random bytes from the system's preferred random number
/// source.
///
/// This function returns an error on any failure, including partial reads. We
/// make no guarantees regarding the contents of `dest` on error. If `dest` is
/// empty, `getrandom` immediately returns success, making no calls to the
/// underlying operating system.
///
/// Blocking is possible, at least during early boot; see module documentation.
///
/// In general, `getrandom` will be fast enough for interactive usage, though
/// significantly slower than a user-space CSPRNG; for the latter consider
/// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html).
pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
if dest.is_empty() {
return Ok(());
}
imp::getrandom_inner(dest)
}
| 48.84252 | 162 | 0.643882 |
e26d48ed4a235095f16195bd0052894635fcbeab | 5,773 | mod bars;
mod display;
mod format;
mod theme;
use clap::arg_enum;
use clap::crate_authors;
use colored::Color;
use display::{Elements, Fail};
use macchina_read::Readouts;
use structopt::StructOpt;
#[macro_use]
extern crate lazy_static;
use macchina_read::traits::*;
pub const AUTHORS: &str = crate_authors!();
pub const ABOUT: &str = "System information fetcher";
lazy_static! {
pub(crate) static ref READOUTS: Readouts = Readouts {
battery: macchina_read::BatteryReadout::new(),
kernel: macchina_read::KernelReadout::new(),
memory: macchina_read::MemoryReadout::new(),
general: macchina_read::GeneralReadout::new(),
product: macchina_read::ProductReadout::new(),
packages: macchina_read::PackageReadout::new()
};
}
arg_enum! {
#[derive(Debug)]
pub enum MacchinaColor {
Red,
Green,
Blue,
Yellow,
Cyan,
Magenta,
Black,
White
}
}
impl MacchinaColor {
/// Convert arguments passed to `--color` to their respective color.
fn get_color(&self) -> Color {
match self {
MacchinaColor::Red => Color::Red,
MacchinaColor::Green => Color::Green,
MacchinaColor::Blue => Color::Blue,
MacchinaColor::Yellow => Color::Yellow,
MacchinaColor::Cyan => Color::Cyan,
MacchinaColor::Magenta => Color::Magenta,
MacchinaColor::Black => Color::Black,
MacchinaColor::White => Color::White,
}
}
}
#[derive(StructOpt, Debug)]
#[structopt(author = AUTHORS, about = ABOUT)]
pub struct Opt {
#[structopt(short = "p", long = "palette", help = "Displays color palette")]
palette: bool,
#[structopt(
short = "P",
long = "padding",
default_value = "4",
help = "Specifies the amount of left padding to use"
)]
padding: usize,
#[structopt(
short = "s",
long = "spacing",
help = "Specifies the amount of spacing to use"
)]
spacing: Option<usize>,
#[structopt(short = "n", long = "no-color", help = "Disables color")]
no_color: bool,
#[structopt(
short = "c",
long = "color",
possible_values = &MacchinaColor::variants(),
case_insensitive = true,
default_value = "Blue",
help = "Specifies the key color"
)]
color: MacchinaColor,
#[structopt(
short = "b",
long = "bar",
help = "Displays bars instead of numerical values"
)]
bar: bool,
#[structopt(
short = "C",
long = "separator-color",
possible_values = &MacchinaColor::variants(),
case_insensitive = true,
default_value = "White",
help = "Specifies the separator color"
)]
separator_color: MacchinaColor,
#[structopt(
short = "r",
long = "random-color",
help = "Picks a random key color for you"
)]
random_color: bool,
#[structopt(
short = "R",
long = "random-sep-color",
help = "Picks a random separator color for you"
)]
random_sep_color: bool,
#[structopt(
short = "H",
long = "hide",
possible_values = &theme::ReadoutKey::variants(),
case_insensitive = true,
help = "Hides the specified elements",
min_values = 1
)]
hide: Option<Vec<theme::ReadoutKey>>,
#[structopt(
short = "X",
long = "show-only",
possible_values = &theme::ReadoutKey::variants(),
case_insensitive = true,
help = " Displays only the specified elements",
min_values = 1
)]
show_only: Option<Vec<theme::ReadoutKey>>,
#[structopt(short = "d", long = "debug", help = "Prints debug information")]
debug: bool,
#[structopt(short = "U", long = "short-uptime", help = "Shortens uptime output")]
short_uptime: bool,
#[structopt(short = "S", long = "short-shell", help = "Shortens shell output")]
short_shell: bool,
#[structopt(
short = "t",
long = "theme",
default_value = "Hydrogen",
possible_values = &theme::Themes::variants(),
help = "Specifies the theme to use"
)]
theme: theme::Themes,
}
fn main() {
let opt = Opt::from_args();
// Instantiate Macchina's elements.
let mut elems = Elements::new();
let mut fail = Fail::new();
elems.set_theme(opt.theme.create_instance(), &mut fail);
let longest_key = elems.longest_key(&mut fail);
let mut misc = elems.theme.misc_mut();
misc.longest_key = longest_key;
misc.padding = opt.padding;
misc.color = opt.color.get_color();
misc.separator_color = opt.separator_color.get_color();
if let Some(spacing) = opt.spacing {
misc.spacing = spacing;
}
if opt.no_color {
misc.color = Color::White;
misc.separator_color = Color::White;
}
if let Some(ref elements_to_hide) = opt.hide {
display::hide(elems, &opt, &mut fail, elements_to_hide);
std::process::exit(0); //todo: refactor, don't make display::hide() also print_info...
}
if let Some(ref show_only) = opt.show_only {
elems.hide_all();
display::unhide(elems, &opt, &mut fail, show_only);
std::process::exit(0); //todo: refactor, don't make display::unhide() also print_info...
}
if opt.debug {
elems.init_elements_for_debug(&mut fail, &opt);
display::debug(&mut fail);
std::process::exit(0);
}
if opt.random_color {
misc.color = display::randomize_color();
}
if opt.random_sep_color {
misc.separator_color = display::randomize_color();
}
display::print_info(elems, &opt, &mut fail);
}
| 26.481651 | 96 | 0.587909 |
e2fc23e187963c9efefaf432983026eb8dd06023 | 5,410 | use crate::command_prelude::*;
use cargo::ops::{self, CompileFilter, FilterRule};
pub fn cli() -> App {
subcommand("fix")
.about("Automatically fix lint warnings reported by rustc")
.arg_package_spec(
"Package(s) to fix",
"Fix all packages in the workspace",
"Exclude packages from the fixes",
)
.arg_jobs()
.arg_targets_all(
"Fix only this package's library",
"Fix only the specified binary",
"Fix all binaries",
"Fix only the specified example",
"Fix all examples",
"Fix only the specified test target",
"Fix all tests",
"Fix only the specified bench target",
"Fix all benches",
"Fix all targets (default)",
)
.arg_release("Fix artifacts in release mode, with optimizations")
.arg(opt("profile", "Profile to build the selected target for").value_name("PROFILE"))
.arg_features()
.arg_target_triple("Fix for the target triple")
.arg_target_dir()
.arg_manifest_path()
.arg_message_format()
.arg(
Arg::with_name("broken-code")
.long("broken-code")
.help("Fix code even if it already has compiler errors"),
)
.arg(
Arg::with_name("edition")
.long("edition")
.help("Fix in preparation for the next edition"),
)
.arg(
// This is a deprecated argument, we'll want to phase it out
// eventually.
Arg::with_name("prepare-for")
.long("prepare-for")
.help("Fix warnings in preparation of an edition upgrade")
.takes_value(true)
.possible_values(&["2018"])
.conflicts_with("edition")
.hidden(true),
)
.arg(
Arg::with_name("idioms")
.long("edition-idioms")
.help("Fix warnings to migrate to the idioms of an edition"),
)
.arg(
Arg::with_name("allow-no-vcs")
.long("allow-no-vcs")
.help("Fix code even if a VCS was not detected"),
)
.arg(
Arg::with_name("allow-dirty")
.long("allow-dirty")
.help("Fix code even if the working directory is dirty"),
)
.arg(
Arg::with_name("allow-staged")
.long("allow-staged")
.help("Fix code even if the working directory has staged changes"),
)
.after_help(
"\
This Cargo subcommand will automatically take rustc's suggestions from
diagnostics like warnings and apply them to your source code. This is intended
to help automate tasks that rustc itself already knows how to tell you to fix!
The `cargo fix` subcommand is also being developed for the Rust 2018 edition
to provide code the ability to easily opt-in to the new edition without having
to worry about any breakage.
Executing `cargo fix` will under the hood execute `cargo check`. Any warnings
applicable to your crate will be automatically fixed (if possible) and all
remaining warnings will be displayed when the check process is finished. For
example if you'd like to prepare for the 2018 edition, you can do so by
executing:
cargo fix --edition
which behaves the same as `cargo check --all-targets`. Similarly if you'd like
to fix code for different platforms you can do:
cargo fix --edition --target x86_64-pc-windows-gnu
or if your crate has optional features:
cargo fix --edition --no-default-features --features foo
If you encounter any problems with `cargo fix` or otherwise have any questions
or feature requests please don't hesitate to file an issue at
https://github.com/rust-lang/cargo
",
)
}
pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
let ws = args.workspace(config)?;
let test = match args.value_of("profile") {
Some("test") => true,
None => false,
Some(profile) => {
let err = format_err!(
"unknown profile: `{}`, only `test` is \
currently supported",
profile
);
return Err(CliError::new(err, 101));
}
};
let mode = CompileMode::Check { test };
// Unlike other commands default `cargo fix` to all targets to fix as much
// code as we can.
let mut opts = args.compile_options(config, mode)?;
if let CompileFilter::Default { .. } = opts.filter {
opts.filter = CompileFilter::Only {
all_targets: true,
lib: true,
bins: FilterRule::All,
examples: FilterRule::All,
benches: FilterRule::All,
tests: FilterRule::All,
}
}
ops::fix(
&ws,
&mut ops::FixOptions {
edition: args.is_present("edition"),
prepare_for: args.value_of("prepare-for"),
idioms: args.is_present("idioms"),
compile_opts: opts,
allow_dirty: args.is_present("allow-dirty"),
allow_no_vcs: args.is_present("allow-no-vcs"),
allow_staged: args.is_present("allow-staged"),
broken_code: args.is_present("broken-code"),
},
)?;
Ok(())
}
| 35.827815 | 94 | 0.575231 |
484b5a5785e1dc35be45a12ba4ffb5572f071770 | 1,454 | use hassle_rs::*;
#[repr(C)]
#[repr(packed)]
pub struct MinimalHeader {
four_cc: u32,
hash_digest: [u32; 4],
}
// zero_digest & get_digest from https://github.com/gwihlidal/dxil-signing/blob/master/rust/src/main.rs
fn zero_digest(buffer: &mut [u8]) {
let buffer_ptr: *mut u8 = buffer.as_mut_ptr();
let header_ptr: *mut MinimalHeader = buffer_ptr as *mut _;
let header_mut: &mut MinimalHeader = unsafe { &mut *header_ptr };
header_mut.hash_digest[0] = 0x0;
header_mut.hash_digest[1] = 0x0;
header_mut.hash_digest[2] = 0x0;
header_mut.hash_digest[3] = 0x0;
}
fn get_digest(buffer: &[u8]) -> [u32; 4] {
let buffer_ptr: *const u8 = buffer.as_ptr();
let header_ptr: *const MinimalHeader = buffer_ptr as *const _;
let header_ref: &MinimalHeader = unsafe { &*header_ptr };
let digest: [u32; 4] = [
header_ref.hash_digest[0],
header_ref.hash_digest[1],
header_ref.hash_digest[2],
header_ref.hash_digest[3],
];
digest
}
fn main() {
let source = include_str!("copy.hlsl");
let mut dxil = compile_hlsl("copy.hlsl", source, "copyCs", "cs_6_0", &[], &[]).unwrap();
zero_digest(&mut dxil);
let without_digest = get_digest(&dxil);
println!("Before validation: {:?}", without_digest);
let validated_dxil = validate_dxil(&dxil).unwrap();
let with_digest = get_digest(&validated_dxil);
println!("After validation: {:?}", with_digest);
}
| 28.509804 | 103 | 0.650619 |
1ae1d4512296abfacefc14aa2de4ade2c0acc063 | 1,030 | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use std::{
io::Write,
path::{Path, PathBuf},
time::Instant,
};
/// Helper function to iterate through all the files in the given directory, skipping hidden files,
/// and return an iterator of their paths.
pub fn iterate_directory(path: &Path) -> impl Iterator<Item = PathBuf> {
walkdir::WalkDir::new(path)
.into_iter()
.map(::std::result::Result::unwrap)
.filter(|entry| {
entry.file_type().is_file()
&& entry
.file_name()
.to_str()
.map_or(false, |s| !s.starts_with('.')) // Skip hidden files
})
.map(|entry| entry.path().to_path_buf())
}
pub fn time_it<F, R>(msg: &str, f: F) -> R
where
F: FnOnce() -> R,
{
let now = Instant::now();
print!("{} ... ", msg);
let _ = std::io::stdout().flush();
let res = f();
println!("(took {:.3}s)", now.elapsed().as_secs_f64());
res
}
| 27.837838 | 99 | 0.54466 |
e625db43e90d077729d662957c2911931076209d | 2,641 | #![feature(test)]
extern crate bytes;
extern crate futures;
extern crate simproto;
extern crate test;
use bytes::BytesMut;
use futures::executor::{block_on, spawn};
use futures::future::ok;
use futures::prelude::*;
use simproto::sim::{Handler, Sim};
use simproto::util::PairIO;
use test::{black_box, Bencher};
#[bench]
fn rpc(b: &mut Bencher) {
let mut handler = Handler::new();
let topic_echo = BytesMut::from(r"echo").freeze();
handler.on_rpc(topic_echo.clone(), Box::new(|req| Box::new(ok(req))));
let sim = Sim::new(handler);
let (io1, io2) = PairIO::new();
let (req1, fut) = sim.add(io1);
block_on(spawn(fut.map_err(|e| panic!("io1 sim fut panic {:?}", e)))).unwrap();
let (_req2, fut) = sim.add(io2);
block_on(spawn(fut.map_err(|e| panic!("io2 sim fut panic {:?}", e)))).unwrap();
let hello = BytesMut::from(r"hello").freeze();
let req1 = black_box(req1);
b.iter(|| {
let f = req1.clone().rpc(topic_echo.clone(), hello.clone());
let _ = block_on(f).unwrap();
});
}
#[bench]
fn simple_notify(b: &mut Bencher) {
let mut handler = Handler::new();
let topic_once = BytesMut::from(r"once").freeze();
let (one_sink, fut) = handler.on_subs(
topic_once.clone(),
Box::new(|req| Box::new(ok(req))),
Box::new(|req| Box::new(ok(req))),
);
block_on(spawn(fut.map_err(|e| panic!("on_sub fut panic {:?}", e)))).unwrap();
let sim = Sim::new(handler);
let (io1, io2) = PairIO::new();
let (req1, fut) = sim.add(io1);
block_on(spawn(fut.map_err(|e| panic!("io1 sim fut panic {:?}", e)))).unwrap();
let (_req2, fut) = sim.add(io2);
block_on(spawn(fut.map_err(|e| panic!("io2 sim fut panic {:?}", e)))).unwrap();
let receiver = req1
.sub(topic_once, BytesMut::from(&[] as &[u8]).freeze())
.and_then(|(_, _, receiver)| ok(receiver.unwrap()));
let receiver = block_on(receiver).unwrap();
let mut inner = Some((one_sink, receiver));
b.iter(|| {
if let Some((one_sink, receiver)) = std::mem::replace(&mut inner, None) {
let fut = one_sink
.send(BytesMut::from(b"hello" as &[u8]).freeze())
.map_err(|e| panic!("Sending notification panic {:?}", e))
.and_then(|s| {
receiver.next().map(|(msg, r)| {
msg.unwrap();
(s, r)
})
})
.map_err(|_| panic!("Receiving notification panic"));
inner = Some(block_on(fut).unwrap());
} else {
unreachable!();
}
});
}
| 32.604938 | 83 | 0.550928 |
714dee6759aca9fb5c6a0a050c098f4b41208abf | 53 | pub mod cmp;
pub mod io;
pub mod math;
pub mod path;
| 10.6 | 13 | 0.698113 |
f49df1e1423a3f00dd7b35a7c9bca24c9e99b80e | 1,807 | #![allow(dead_code, unused_assignments, unused_variables)]
use sgx_types::*;
pub const JSON_RPC_ERROR_WORKER_NOT_AUTHORIZED: i64 =-32001;
pub const JSON_RPC_ERROR_ILLEGAL_STATE: i64 =-32002;
// error while requesting to produce a quote (registration)
#[derive(Fail, Debug)]
#[fail(display = "Error while producing a quote sgx_status = {}. info = ({})", status, message)]
pub struct ProduceQuoteErr {
pub status: sgx_status_t,
pub message: String,
}
// error while requesting the public signing key (the registration key)
#[derive(Fail, Debug)]
#[fail(display = "Error while retrieving the registration signing public key sgx_status = {}. info = ({})", status, message)]
pub struct GetRegisterKeyErr {
pub status: sgx_status_t,
pub message: String,
}
// error while request attestation service
#[derive(Fail, Debug)]
#[fail(display = "Error while using the attestation service info = ({})", message)]
pub struct AttestationServiceErr {
pub message: String,
}
#[derive(Fail, Debug)]
#[fail(display = "Error inside the Enclave = ({:?})", err)]
pub struct EnclaveFailError {
pub err: enigma_types::EnclaveReturn,
pub status: sgx_status_t,
}
#[derive(Fail, Debug)]
#[fail(display = "Operation not allowed while the EpochState is transitioning. Current state = {}", current_state)]
pub struct EpochStateTransitionErr {
pub current_state: String
}
#[derive(Fail, Debug)]
#[fail(display = "info = ({})", message)]
pub struct EpochStateIOErr {
pub message: String,
}
#[derive(Fail, Debug)]
#[fail(display = "The EpochState is undefined")]
pub struct EpochStateUndefinedErr {}
#[derive(Fail, Debug)]
#[fail(display = "Value error in JSON-RPC request: {}. info = ({})", request, message)]
pub struct RequestValueErr {
pub request: String,
pub message: String,
}
| 30.116667 | 125 | 0.712784 |
89496a5aedb4f84bc244e5dfcd9b92ca4bfea3ab | 4,346 | /*
* ISC License
*
* Copyright (c) 2021 Mitama Lab
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#![allow(clippy::nonstandard_macro_braces)]
use rand::distributions::{Distribution, Uniform};
use strum_macros::EnumIter;
use thiserror::Error;
struct MinMax(i32, i32);
impl std::fmt::Display for MinMax {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut rng = rand::thread_rng();
let uniform = Uniform::new_inclusive(self.0, self.1);
write!(f, "{}", uniform.sample(&mut rng))
}
}
#[derive(Debug, Error, PartialEq, Eq, Hash, EnumIter)]
pub enum Order {
#[error("アイテムの持ち込み数1個(弾・ビンを除く)")]
Order1,
#[error("{}種類の状態異常にする", MinMax(1, 3))]
Order2,
#[error("{}回操竜する", MinMax(1, 4))]
Order3,
}
#[derive(Debug, Error, PartialEq, Eq, Hash, EnumIter)]
pub enum Objective {
// for Great Sword
#[error("1回スタンさせる")]
GreatSword1,
#[error("真溜め斬りを{}回当てる", MinMax(1, 3))]
GreatSword2,
#[error("睡眠真溜め斬りを1回成功させる")]
GreatSword3,
// for Long Sword
#[error("居合抜刀気刃斬りを{}回成功させる", MinMax(1, 3))]
LongSword1,
#[error("真溜め斬りを{}回当てる", MinMax(1, 3))]
LongSword2,
#[error("兜割りを{}回全ヒットさせる", MinMax(1, 3))]
LongSword3,
// for Sword and Shield
#[error("1回スタンさせる")]
SwordAndShield1,
#[error("滅・昇竜拳のカウンターを{}回成功させる", MinMax(2, 5))]
SwordAndShield2,
#[error("ジャストラッシュを{}回成功させる", MinMax(5, 10))]
SwordAndShield3,
// for Dual Blades
#[error("朧翔の回避を{}回成功させる", MinMax(2, 5))]
DualBlades1,
#[error("鉄蟲斬糸を{}回成功させる", MinMax(5, 10))]
DualBlades2,
#[error("空中鬼人化から空中回転乱舞を出してモンスターに当てる")]
DualBlades3,
// for Lance
#[error("スタンを{}回とる", MinMax(2, 5))]
Lance1,
#[error("ジャストガードを{}回成功させる", MinMax(2, 5))]
Lance2,
#[error("アンカーレイジで黄色をもらう")]
Lance3,
// for Gunlance
#[error("竜撃砲を{}回当てる", MinMax(2, 5))]
Gunlance1,
#[error("ガードエッジを{}回成功させる", MinMax(2, 5))]
Gunlance2,
#[error("空中フルバーストを1回成功させる")]
Gunlance3,
// for Hammer
#[error("スタンを{}回とる", MinMax(2, 5))]
Hammer1,
#[error("水面打ちを{}回成功させる", MinMax(2, 5))]
Hammer2,
// #[error("減気ひるみインパクトクレーターを1回成功させる")]
#[error("睡眠インパクトクレーターを1回成功させる")]
Hammer3,
// for Hunting Horn
#[error("操竜を{}回する", MinMax(2, 5))]
HuntingHorn1,
#[error("体力回復の旋律で{}回以上回復する", MinMax(2, 5))]
HuntingHorn2,
#[error("震打を{}回当てる", MinMax(2, 5))]
HuntingHorn3,
// for Switch Axe
#[error("金剛連斧で{}回ゴリ押す", MinMax(2, 5))]
SwitchAxe1,
#[error("飛翔竜剣を{}回当てる", MinMax(2, 5))]
SwitchAxe2,
#[error("零距離属性解放突きを{}回成功させる", MinMax(2, 5))]
SwitchAxe3,
// for Charge Blade
#[error("高出力属性解放斬りを{}回当てる", MinMax(2, 5))]
ChargeBlade1,
#[error("カウンターフルチャージを{}回成功させる", MinMax(2, 5))]
ChargeBlade2,
#[error("アックスホッパーからの空中高出力属性解放斬りを当てる")]
ChargeBlade3,
// for Insect Glaive
#[error("降竜を{}回以上当てる", MinMax(5, 10))]
InsectGlaive1,
#[error("跳躍で{}回攻撃を回避する", MinMax(2, 5))]
InsectGlaive2,
#[error("跳躍で回攻撃を回避したあとに降竜を当てる")]
InsectGlaive3,
// for Light Bowgun
#[error("状態異常を{}種類以上いれる", MinMax(1, 2))]
LightBowgun1,
#[error("回復弾で味方を{}回以上回復する", MinMax(2, 5))]
LightBowgun2,
#[error("起爆榴弾直挿しを{}回成功させる", MinMax(1, 3))]
LightBowgun3,
// for Heavy Bowgun
#[error("狙撃竜弾を{}回使う", MinMax(1, 3))]
HeavyBowgun1,
#[error("カウンターショットを{}回成功させる", MinMax(2, 5))]
HeavyBowgun2,
#[error("タックルのスーパーアーマーで{}回攻撃を耐える", MinMax(1, 3))]
HeavyBowgun3,
// for Bow
#[error("身躱し矢切りを{}回成功させる", MinMax(1, 3))]
Bow1,
#[error("状態異常を1回いれる")]
Bow2,
#[error("身躱し矢切り竜の一矢を成功させる")]
Bow3,
}
| 29.364865 | 75 | 0.626323 |
eb7925a14e6ef3967e59cba954a66828a92a887f | 3,018 | use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
// Read input file
let filename = "./input";
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
// Grab record lines from input file and store them in a Vector.
let mut input_vec = Vec::new();
for line in reader.lines() {
let line = line.unwrap();
input_vec.push(line);
}
let mut count_old = 0;
let mut count_new = 0;
for record in input_vec.iter() {
let parsed_record_old = parse_record(record);
let parsed_record_new = parsed_record_old.clone();
let valid_old = compare_old(parsed_record_old.0, parsed_record_old.1, parsed_record_old.2, parsed_record_old.3);
if valid_old {
count_old += 1;
}
let valid_new = compare_new(parsed_record_new.0, parsed_record_new.1, parsed_record_new.2, parsed_record_new.3);
if valid_new {
count_new += 1;
}
}
println!("Total count of valid old passwords: {}", count_old);
println!("Total count of valid new passwords: {}", count_new);
}
// Implement custom parsing logic for input file lines.
fn parse_record(record: &String) -> (i32, i32, String, String) {
// 1 - Split on ':' to separate between the policy and the password.
let record_split: Vec<&str> = record.split(":").collect();
// Strip whitespace from password.
let password_vec: Vec<&str> = record_split[1].split_whitespace().collect();
// 2 - Break up the policy portion into three discrete bits (min, max, policy char).
// Split between min/max and policy char.
let policy_vec: Vec<&str> = record_split[0].split_whitespace().collect();
// Split min/max into their own bits.
let policy_min_max: Vec<&str> = policy_vec[0].split("-").collect();
let password = password_vec[0].to_string();
let min: i32 = policy_min_max[0].parse().unwrap();
let max: i32 = policy_min_max[1].parse().unwrap();
(min, max, policy_vec[1].to_string(), password)
}
// Compare password with password policy and return true if password complies with policy.
fn compare_old(min: i32, max: i32, character: String, password: String) -> bool {
let mut c: char = '-';
for ch in character.chars() {
c = ch;
}
let mut count = 0;
for char in password.chars() {
if char == c {
count += 1;
}
}
if count >= min && count <= max {
return true;
}
false
}
fn compare_new(min: i32, max: i32, character: String, password: String) -> bool {
let mut c: char = '-';
for ch in character.chars() {
c = ch;
}
let min = min as usize;
let max = max as usize;
let password_min = password.chars().nth(min - 1).unwrap();
let password_max = password.chars().nth(max - 1).unwrap();
if password_min == c && password_max != c {
return true;
}
if password_min != c && password_max == c {
return true;
}
false
} | 33.164835 | 120 | 0.615639 |
0efc4893c3c42847a696197a1a223687cd9f0741 | 2,689 | use crate::boxed::Box;
#[rustc_specialization_trait]
pub(super) unsafe trait IsZero {
/// Whether this value is zero
fn is_zero(&self) -> bool;
}
macro_rules! impl_is_zero {
($t:ty, $is_zero:expr) => {
unsafe impl IsZero for $t {
#[inline]
fn is_zero(&self) -> bool {
$is_zero(*self)
}
}
};
}
impl_is_zero!(i16, |x| x == 0);
impl_is_zero!(i32, |x| x == 0);
impl_is_zero!(i64, |x| x == 0);
impl_is_zero!(i128, |x| x == 0);
impl_is_zero!(isize, |x| x == 0);
impl_is_zero!(u16, |x| x == 0);
impl_is_zero!(u32, |x| x == 0);
impl_is_zero!(u64, |x| x == 0);
impl_is_zero!(u128, |x| x == 0);
impl_is_zero!(usize, |x| x == 0);
impl_is_zero!(bool, |x| x == false);
impl_is_zero!(char, |x| x == '\0');
impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
unsafe impl<T> IsZero for *const T {
#[inline]
fn is_zero(&self) -> bool {
(*self).is_null()
}
}
unsafe impl<T> IsZero for *mut T {
#[inline]
fn is_zero(&self) -> bool {
(*self).is_null()
}
}
// `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
// For fat pointers, the bytes that would be the pointer metadata in the `Some`
// variant are padding in the `None` variant, so ignoring them and
// zero-initializing instead is ok.
// `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
// `SpecFromElem`.
unsafe impl<T: ?Sized> IsZero for Option<&T> {
#[inline]
fn is_zero(&self) -> bool {
self.is_none()
}
}
unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
#[inline]
fn is_zero(&self) -> bool {
self.is_none()
}
}
// `Option<num::NonZeroU32>` and similar have a representation guarantee that
// they're the same size as the corresponding `u32` type, as well as a guarantee
// that transmuting between `NonZeroU32` and `Option<num::NonZeroU32>` works.
// While the documentation officially makes it UB to transmute from `None`,
// we're the standard library so we can make extra inferences, and we know that
// the only niche available to represent `None` is the one that's all zeros.
macro_rules! impl_is_zero_option_of_nonzero {
($($t:ident,)+) => {$(
unsafe impl IsZero for Option<core::num::$t> {
#[inline]
fn is_zero(&self) -> bool {
self.is_none()
}
}
)+};
}
impl_is_zero_option_of_nonzero!(
NonZeroU8,
NonZeroU16,
NonZeroU32,
NonZeroU64,
NonZeroU128,
NonZeroI8,
NonZeroI16,
NonZeroI32,
NonZeroI64,
NonZeroI128,
NonZeroUsize,
NonZeroIsize,
);
| 25.609524 | 80 | 0.601339 |
892808386deef4c79bc5b3cad93d7fd711d066d1 | 20,583 | use crate::dep_graph::{DepNode, WorkProduct, WorkProductId};
use crate::ty::{subst::InternalSubsts, Instance, InstanceDef, SymbolName, TyCtxt};
use rustc_attr::InlineAttr;
use rustc_data_structures::base_n;
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc_hir::ItemId;
use rustc_query_system::ich::{NodeIdHashingMode, StableHashingContext};
use rustc_session::config::OptLevel;
use rustc_span::source_map::Span;
use rustc_span::symbol::Symbol;
use std::fmt;
use std::hash::Hash;
/// Describes how a monomorphization will be instantiated in object files.
#[derive(PartialEq)]
pub enum InstantiationMode {
/// There will be exactly one instance of the given MonoItem. It will have
/// external linkage so that it can be linked to from other codegen units.
GloballyShared {
/// In some compilation scenarios we may decide to take functions that
/// are typically `LocalCopy` and instead move them to `GloballyShared`
/// to avoid codegenning them a bunch of times. In this situation,
/// however, our local copy may conflict with other crates also
/// inlining the same function.
///
/// This flag indicates that this situation is occurring, and informs
/// symbol name calculation that some extra mangling is needed to
/// avoid conflicts. Note that this may eventually go away entirely if
/// ThinLTO enables us to *always* have a globally shared instance of a
/// function within one crate's compilation.
may_conflict: bool,
},
/// Each codegen unit containing a reference to the given MonoItem will
/// have its own private copy of the function (with internal linkage).
LocalCopy,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
pub enum MonoItem<'tcx> {
Fn(Instance<'tcx>),
Static(DefId),
GlobalAsm(ItemId),
}
impl<'tcx> MonoItem<'tcx> {
/// Returns `true` if the mono item is user-defined (i.e. not compiler-generated, like shims).
pub fn is_user_defined(&self) -> bool {
match *self {
MonoItem::Fn(instance) => matches!(instance.def, InstanceDef::Item(..)),
MonoItem::Static(..) | MonoItem::GlobalAsm(..) => true,
}
}
pub fn size_estimate(&self, tcx: TyCtxt<'tcx>) -> usize {
match *self {
MonoItem::Fn(instance) => {
// Estimate the size of a function based on how many statements
// it contains.
tcx.instance_def_size_estimate(instance.def)
}
// Conservatively estimate the size of a static declaration
// or assembly to be 1.
MonoItem::Static(_) | MonoItem::GlobalAsm(_) => 1,
}
}
pub fn is_generic_fn(&self) -> bool {
match *self {
MonoItem::Fn(ref instance) => instance.substs.non_erasable_generics().next().is_some(),
MonoItem::Static(..) | MonoItem::GlobalAsm(..) => false,
}
}
pub fn symbol_name(&self, tcx: TyCtxt<'tcx>) -> SymbolName<'tcx> {
match *self {
MonoItem::Fn(instance) => tcx.symbol_name(instance),
MonoItem::Static(def_id) => tcx.symbol_name(Instance::mono(tcx, def_id)),
MonoItem::GlobalAsm(item_id) => {
SymbolName::new(tcx, &format!("global_asm_{:?}", item_id.def_id))
}
}
}
pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
let generate_cgu_internal_copies = tcx
.sess
.opts
.debugging_opts
.inline_in_all_cgus
.unwrap_or_else(|| tcx.sess.opts.optimize != OptLevel::No)
&& !tcx.sess.link_dead_code();
match *self {
MonoItem::Fn(ref instance) => {
let entry_def_id = tcx.entry_fn(()).map(|(id, _)| id);
// If this function isn't inlined or otherwise has an extern
// indicator, then we'll be creating a globally shared version.
if tcx.codegen_fn_attrs(instance.def_id()).contains_extern_indicator()
|| !instance.def.generates_cgu_internal_copy(tcx)
|| Some(instance.def_id()) == entry_def_id
{
return InstantiationMode::GloballyShared { may_conflict: false };
}
// At this point we don't have explicit linkage and we're an
// inlined function. If we're inlining into all CGUs then we'll
// be creating a local copy per CGU.
if generate_cgu_internal_copies {
return InstantiationMode::LocalCopy;
}
// Finally, if this is `#[inline(always)]` we're sure to respect
// that with an inline copy per CGU, but otherwise we'll be
// creating one copy of this `#[inline]` function which may
// conflict with upstream crates as it could be an exported
// symbol.
match tcx.codegen_fn_attrs(instance.def_id()).inline {
InlineAttr::Always => InstantiationMode::LocalCopy,
_ => InstantiationMode::GloballyShared { may_conflict: true },
}
}
MonoItem::Static(..) | MonoItem::GlobalAsm(..) => {
InstantiationMode::GloballyShared { may_conflict: false }
}
}
}
pub fn explicit_linkage(&self, tcx: TyCtxt<'tcx>) -> Option<Linkage> {
let def_id = match *self {
MonoItem::Fn(ref instance) => instance.def_id(),
MonoItem::Static(def_id) => def_id,
MonoItem::GlobalAsm(..) => return None,
};
let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
codegen_fn_attrs.linkage
}
/// Returns `true` if this instance is instantiable - whether it has no unsatisfied
/// predicates.
///
/// In order to codegen an item, all of its predicates must hold, because
/// otherwise the item does not make sense. Type-checking ensures that
/// the predicates of every item that is *used by* a valid item *do*
/// hold, so we can rely on that.
///
/// However, we codegen collector roots (reachable items) and functions
/// in vtables when they are seen, even if they are not used, and so they
/// might not be instantiable. For example, a programmer can define this
/// public function:
///
/// pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
/// <&mut () as Clone>::clone(&s);
/// }
///
/// That function can't be codegened, because the method `<&mut () as Clone>::clone`
/// does not exist. Luckily for us, that function can't ever be used,
/// because that would require for `&'a mut (): Clone` to hold, so we
/// can just not emit any code, or even a linker reference for it.
///
/// Similarly, if a vtable method has such a signature, and therefore can't
/// be used, we can just not emit it and have a placeholder (a null pointer,
/// which will never be accessed) in its place.
pub fn is_instantiable(&self, tcx: TyCtxt<'tcx>) -> bool {
debug!("is_instantiable({:?})", self);
let (def_id, substs) = match *self {
MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
MonoItem::Static(def_id) => (def_id, InternalSubsts::empty()),
// global asm never has predicates
MonoItem::GlobalAsm(..) => return true,
};
!tcx.subst_and_check_impossible_predicates((def_id, &substs))
}
pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option<Span> {
match *self {
MonoItem::Fn(Instance { def, .. }) => def.def_id().as_local(),
MonoItem::Static(def_id) => def_id.as_local(),
MonoItem::GlobalAsm(item_id) => Some(item_id.def_id),
}
.map(|def_id| tcx.def_span(def_id))
}
// Only used by rustc_codegen_cranelift
pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
crate::dep_graph::make_compile_mono_item(tcx, self)
}
/// Returns the item's `CrateNum`
pub fn krate(&self) -> CrateNum {
match self {
MonoItem::Fn(ref instance) => instance.def_id().krate,
MonoItem::Static(def_id) => def_id.krate,
MonoItem::GlobalAsm(..) => LOCAL_CRATE,
}
}
}
impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for MonoItem<'tcx> {
fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
::std::mem::discriminant(self).hash_stable(hcx, hasher);
match *self {
MonoItem::Fn(ref instance) => {
instance.hash_stable(hcx, hasher);
}
MonoItem::Static(def_id) => {
def_id.hash_stable(hcx, hasher);
}
MonoItem::GlobalAsm(item_id) => {
hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
item_id.hash_stable(hcx, hasher);
})
}
}
}
}
impl<'tcx> fmt::Display for MonoItem<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
MonoItem::Fn(instance) => write!(f, "fn {}", instance),
MonoItem::Static(def_id) => {
write!(f, "static {}", Instance::new(def_id, InternalSubsts::empty()))
}
MonoItem::GlobalAsm(..) => write!(f, "global_asm"),
}
}
}
#[derive(Debug)]
pub struct CodegenUnit<'tcx> {
/// A name for this CGU. Incremental compilation requires that
/// name be unique amongst **all** crates. Therefore, it should
/// contain something unique to this crate (e.g., a module path)
/// as well as the crate name and disambiguator.
name: Symbol,
items: FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)>,
size_estimate: Option<usize>,
primary: bool,
/// True if this is CGU is used to hold code coverage information for dead code,
/// false otherwise.
is_code_coverage_dead_code_cgu: bool,
}
/// Specifies the linkage type for a `MonoItem`.
///
/// See <https://llvm.org/docs/LangRef.html#linkage-types> for more details about these variants.
#[derive(Copy, Clone, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
pub enum Linkage {
External,
AvailableExternally,
LinkOnceAny,
LinkOnceODR,
WeakAny,
WeakODR,
Appending,
Internal,
Private,
ExternalWeak,
Common,
}
#[derive(Copy, Clone, PartialEq, Debug, HashStable)]
pub enum Visibility {
Default,
Hidden,
Protected,
}
impl<'tcx> CodegenUnit<'tcx> {
#[inline]
pub fn new(name: Symbol) -> CodegenUnit<'tcx> {
CodegenUnit {
name,
items: Default::default(),
size_estimate: None,
primary: false,
is_code_coverage_dead_code_cgu: false,
}
}
pub fn name(&self) -> Symbol {
self.name
}
pub fn set_name(&mut self, name: Symbol) {
self.name = name;
}
pub fn is_primary(&self) -> bool {
self.primary
}
pub fn make_primary(&mut self) {
self.primary = true;
}
pub fn items(&self) -> &FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
&self.items
}
pub fn items_mut(&mut self) -> &mut FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
&mut self.items
}
pub fn is_code_coverage_dead_code_cgu(&self) -> bool {
self.is_code_coverage_dead_code_cgu
}
/// Marks this CGU as the one used to contain code coverage information for dead code.
pub fn make_code_coverage_dead_code_cgu(&mut self) {
self.is_code_coverage_dead_code_cgu = true;
}
pub fn mangle_name(human_readable_name: &str) -> String {
// We generate a 80 bit hash from the name. This should be enough to
// avoid collisions and is still reasonably short for filenames.
let mut hasher = StableHasher::new();
human_readable_name.hash(&mut hasher);
let hash: u128 = hasher.finish();
let hash = hash & ((1u128 << 80) - 1);
base_n::encode(hash, base_n::CASE_INSENSITIVE)
}
pub fn estimate_size(&mut self, tcx: TyCtxt<'tcx>) {
// Estimate the size of a codegen unit as (approximately) the number of MIR
// statements it corresponds to.
self.size_estimate = Some(self.items.keys().map(|mi| mi.size_estimate(tcx)).sum());
}
#[inline]
pub fn size_estimate(&self) -> usize {
// Should only be called if `estimate_size` has previously been called.
self.size_estimate.expect("estimate_size must be called before getting a size_estimate")
}
pub fn modify_size_estimate(&mut self, delta: usize) {
assert!(self.size_estimate.is_some());
if let Some(size_estimate) = self.size_estimate {
self.size_estimate = Some(size_estimate + delta);
}
}
pub fn contains_item(&self, item: &MonoItem<'tcx>) -> bool {
self.items().contains_key(item)
}
pub fn work_product_id(&self) -> WorkProductId {
WorkProductId::from_cgu_name(self.name().as_str())
}
pub fn work_product(&self, tcx: TyCtxt<'_>) -> WorkProduct {
let work_product_id = self.work_product_id();
tcx.dep_graph
.previous_work_product(&work_product_id)
.unwrap_or_else(|| panic!("Could not find work-product for CGU `{}`", self.name()))
}
pub fn items_in_deterministic_order(
&self,
tcx: TyCtxt<'tcx>,
) -> Vec<(MonoItem<'tcx>, (Linkage, Visibility))> {
// The codegen tests rely on items being process in the same order as
// they appear in the file, so for local items, we sort by node_id first
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct ItemSortKey<'tcx>(Option<usize>, SymbolName<'tcx>);
fn item_sort_key<'tcx>(tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>) -> ItemSortKey<'tcx> {
ItemSortKey(
match item {
MonoItem::Fn(ref instance) => {
match instance.def {
// We only want to take HirIds of user-defined
// instances into account. The others don't matter for
// the codegen tests and can even make item order
// unstable.
InstanceDef::Item(def) => Some(def.did.index.as_usize()),
InstanceDef::VtableShim(..)
| InstanceDef::ReifyShim(..)
| InstanceDef::Intrinsic(..)
| InstanceDef::FnPtrShim(..)
| InstanceDef::Virtual(..)
| InstanceDef::ClosureOnceShim { .. }
| InstanceDef::DropGlue(..)
| InstanceDef::CloneShim(..) => None,
}
}
MonoItem::Static(def_id) => Some(def_id.index.as_usize()),
MonoItem::GlobalAsm(item_id) => {
Some(item_id.def_id.to_def_id().index.as_usize())
}
},
item.symbol_name(tcx),
)
}
let mut items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i));
items
}
pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
crate::dep_graph::make_compile_codegen_unit(tcx, self.name())
}
}
impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for CodegenUnit<'tcx> {
fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
let CodegenUnit {
ref items,
name,
// The size estimate is not relevant to the hash
size_estimate: _,
primary: _,
is_code_coverage_dead_code_cgu,
} = *self;
name.hash_stable(hcx, hasher);
is_code_coverage_dead_code_cgu.hash_stable(hcx, hasher);
let mut items: Vec<(Fingerprint, _)> = items
.iter()
.map(|(mono_item, &attrs)| {
let mut hasher = StableHasher::new();
mono_item.hash_stable(hcx, &mut hasher);
let mono_item_fingerprint = hasher.finish();
(mono_item_fingerprint, attrs)
})
.collect();
items.sort_unstable_by_key(|i| i.0);
items.hash_stable(hcx, hasher);
}
}
pub struct CodegenUnitNameBuilder<'tcx> {
tcx: TyCtxt<'tcx>,
cache: FxHashMap<CrateNum, String>,
}
impl<'tcx> CodegenUnitNameBuilder<'tcx> {
pub fn new(tcx: TyCtxt<'tcx>) -> Self {
CodegenUnitNameBuilder { tcx, cache: Default::default() }
}
/// CGU names should fulfill the following requirements:
/// - They should be able to act as a file name on any kind of file system
/// - They should not collide with other CGU names, even for different versions
/// of the same crate.
///
/// Consequently, we don't use special characters except for '.' and '-' and we
/// prefix each name with the crate-name and crate-disambiguator.
///
/// This function will build CGU names of the form:
///
/// ```
/// <crate-name>.<crate-disambiguator>[-in-<local-crate-id>](-<component>)*[.<special-suffix>]
/// <local-crate-id> = <local-crate-name>.<local-crate-disambiguator>
/// ```
///
/// The '.' before `<special-suffix>` makes sure that names with a special
/// suffix can never collide with a name built out of regular Rust
/// identifiers (e.g., module paths).
pub fn build_cgu_name<I, C, S>(
&mut self,
cnum: CrateNum,
components: I,
special_suffix: Option<S>,
) -> Symbol
where
I: IntoIterator<Item = C>,
C: fmt::Display,
S: fmt::Display,
{
let cgu_name = self.build_cgu_name_no_mangle(cnum, components, special_suffix);
if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names {
cgu_name
} else {
Symbol::intern(&CodegenUnit::mangle_name(cgu_name.as_str()))
}
}
/// Same as `CodegenUnit::build_cgu_name()` but will never mangle the
/// resulting name.
pub fn build_cgu_name_no_mangle<I, C, S>(
&mut self,
cnum: CrateNum,
components: I,
special_suffix: Option<S>,
) -> Symbol
where
I: IntoIterator<Item = C>,
C: fmt::Display,
S: fmt::Display,
{
use std::fmt::Write;
let mut cgu_name = String::with_capacity(64);
// Start out with the crate name and disambiguator
let tcx = self.tcx;
let crate_prefix = self.cache.entry(cnum).or_insert_with(|| {
// Whenever the cnum is not LOCAL_CRATE we also mix in the
// local crate's ID. Otherwise there can be collisions between CGUs
// instantiating stuff for upstream crates.
let local_crate_id = if cnum != LOCAL_CRATE {
let local_stable_crate_id = tcx.sess.local_stable_crate_id();
format!(
"-in-{}.{:08x}",
tcx.crate_name(LOCAL_CRATE),
local_stable_crate_id.to_u64() as u32,
)
} else {
String::new()
};
let stable_crate_id = tcx.sess.local_stable_crate_id();
format!(
"{}.{:08x}{}",
tcx.crate_name(cnum),
stable_crate_id.to_u64() as u32,
local_crate_id,
)
});
write!(cgu_name, "{}", crate_prefix).unwrap();
// Add the components
for component in components {
write!(cgu_name, "-{}", component).unwrap();
}
if let Some(special_suffix) = special_suffix {
// We add a dot in here so it cannot clash with anything in a regular
// Rust identifier
write!(cgu_name, ".{}", special_suffix).unwrap();
}
Symbol::intern(&cgu_name)
}
}
| 37.491803 | 99 | 0.580528 |
fcfad609d740e758c2691bac984069bbd8497498 | 5,357 | use std::{
collections::HashMap,
path::{Path, PathBuf},
};
use xtask::{
codegen::{self, Mode},
not_bash::fs2,
project_root, run_rustfmt, rust_files,
};
#[test]
fn generated_grammar_is_fresh() {
if let Err(error) = codegen::generate_syntax(Mode::Verify) {
panic!("{}. Please update it by running `cargo xtask codegen`", error);
}
}
#[test]
fn generated_tests_are_fresh() {
if let Err(error) = codegen::generate_parser_tests(Mode::Verify) {
panic!("{}. Please update tests by running `cargo xtask codegen`", error);
}
}
#[test]
fn generated_assists_are_fresh() {
if let Err(error) = codegen::generate_assists_tests(Mode::Verify) {
panic!("{}. Please update assists by running `cargo xtask codegen`", error);
}
}
#[test]
fn check_code_formatting() {
if let Err(error) = run_rustfmt(Mode::Verify) {
panic!("{}. Please format the code by running `cargo format`", error);
}
}
#[test]
fn rust_files_are_tidy() {
let mut tidy_docs = TidyDocs::default();
for path in rust_files(&project_root().join("crates")) {
let text = fs2::read_to_string(&path).unwrap();
check_todo(&path, &text);
check_trailing_ws(&path, &text);
tidy_docs.visit(&path, &text);
}
tidy_docs.finish();
}
fn check_todo(path: &Path, text: &str) {
let need_todo = &[
// This file itself obviously needs to use todo (<- like this!).
"tests/cli.rs",
// Some of our assists generate `todo!()`.
"tests/generated.rs",
"handlers/add_missing_impl_members.rs",
"handlers/add_turbo_fish.rs",
"handlers/generate_function.rs",
// To support generating `todo!()` in assists, we have `expr_todo()` in
// `ast::make`.
"ast/make.rs",
];
if need_todo.iter().any(|p| path.ends_with(p)) {
return;
}
if text.contains("TODO") || text.contains("TOOD") || text.contains("todo!") {
panic!(
"\nTODO markers or todo! macros should not be committed to the master branch,\n\
use FIXME instead\n\
{}\n",
path.display(),
)
}
}
fn check_trailing_ws(path: &Path, text: &str) {
if is_exclude_dir(path, &["test_data"]) {
return;
}
for (line_number, line) in text.lines().enumerate() {
if line.chars().last().map(char::is_whitespace) == Some(true) {
panic!("Trailing whitespace in {} at line {}", path.display(), line_number)
}
}
}
#[derive(Default)]
struct TidyDocs {
missing_docs: Vec<String>,
contains_fixme: Vec<PathBuf>,
}
impl TidyDocs {
fn visit(&mut self, path: &Path, text: &str) {
// Test hopefully don't really need comments, and for assists we already
// have special comments which are source of doc tests and user docs.
if is_exclude_dir(path, &["tests", "test_data"]) {
return;
}
if is_exclude_file(path) {
return;
}
let first_line = match text.lines().next() {
Some(it) => it,
None => return,
};
if first_line.starts_with("//!") {
if first_line.contains("FIXME") {
self.contains_fixme.push(path.to_path_buf());
}
} else {
if text.contains("// Feature:") || text.contains("// Assist:") {
return;
}
self.missing_docs.push(path.display().to_string());
}
fn is_exclude_file(d: &Path) -> bool {
let file_names = ["tests.rs"];
d.file_name()
.unwrap_or_default()
.to_str()
.map(|f_n| file_names.iter().any(|name| *name == f_n))
.unwrap_or(false)
}
}
fn finish(self) {
if !self.missing_docs.is_empty() {
panic!(
"\nMissing docs strings\n\n\
modules:\n{}\n\n",
self.missing_docs.join("\n")
)
}
let poorly_documented = [
"ra_hir",
"ra_hir_expand",
"ra_ide",
"ra_mbe",
"ra_parser",
"ra_prof",
"ra_project_model",
"ra_syntax",
"ra_tt",
"ra_hir_ty",
];
let mut has_fixmes =
poorly_documented.iter().map(|it| (*it, false)).collect::<HashMap<&str, bool>>();
'outer: for path in self.contains_fixme {
for krate in poorly_documented.iter() {
if path.components().any(|it| it.as_os_str() == *krate) {
has_fixmes.insert(krate, true);
continue 'outer;
}
}
panic!("FIXME doc in a fully-documented crate: {}", path.display())
}
for (krate, has_fixme) in has_fixmes.iter() {
if !has_fixme {
panic!("crate {} is fully documented :tada:, remove it from the list of poorly documented crates", krate)
}
}
}
}
fn is_exclude_dir(p: &Path, dirs_to_exclude: &[&str]) -> bool {
p.strip_prefix(project_root())
.unwrap()
.components()
.rev()
.skip(1)
.filter_map(|it| it.as_os_str().to_str())
.any(|it| dirs_to_exclude.contains(&it))
}
| 28.956757 | 121 | 0.536494 |
ff9d98dce33e3fff09deeb741e4dfdeac5ab2706 | 6,179 | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::shared::unique_map::UniqueMap;
use crate::{
parser::ast::{
BinOp, Field, FunctionName, FunctionVisibility, Kind, ModuleIdent, ResourceLoc, StructName,
UnaryOp, Value, Var,
},
shared::*,
};
use std::{collections::VecDeque, fmt};
//**************************************************************************************************
// Program
//**************************************************************************************************
#[derive(Debug)]
pub struct Program {
pub modules: UniqueMap<ModuleIdent, ModuleDefinition>,
pub main: Option<(Address, FunctionName, Function)>,
}
//**************************************************************************************************
// Modules
//**************************************************************************************************
#[derive(Debug)]
pub struct ModuleDefinition {
pub is_source_module: bool,
pub structs: UniqueMap<StructName, StructDefinition>,
pub functions: UniqueMap<FunctionName, Function>,
}
//**************************************************************************************************
// Structs
//**************************************************************************************************
pub type Fields<T> = UniqueMap<Field, (usize, T)>;
#[derive(Debug, PartialEq)]
pub struct StructDefinition {
pub resource_opt: ResourceLoc,
pub type_parameters: Vec<(Name, Kind)>,
pub fields: StructFields,
}
#[derive(Debug, PartialEq)]
pub enum StructFields {
Defined(Fields<SingleType>),
Native(Loc),
}
//**************************************************************************************************
// Functions
//**************************************************************************************************
#[derive(PartialEq, Debug)]
pub struct FunctionSignature {
pub type_parameters: Vec<(Name, Kind)>,
pub parameters: Vec<(Var, SingleType)>,
pub return_type: Type,
}
#[derive(PartialEq, Debug)]
pub enum FunctionBody_ {
Defined(Sequence),
Native,
}
pub type FunctionBody = Spanned<FunctionBody_>;
#[derive(PartialEq, Debug)]
pub struct Function {
pub visibility: FunctionVisibility,
pub signature: FunctionSignature,
pub acquires: Vec<SingleType>,
pub body: FunctionBody,
}
//**************************************************************************************************
// Types
//**************************************************************************************************
#[derive(Debug, PartialEq, Clone)]
pub enum TypeName_ {
Name(Name),
ModuleType(ModuleIdent, StructName),
}
pub type TypeName = Spanned<TypeName_>;
#[derive(Debug, PartialEq, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum SingleType_ {
Apply(TypeName, Vec<SingleType>),
Ref(bool, Box<SingleType>),
UnresolvedError,
}
pub type SingleType = Spanned<SingleType_>;
#[derive(Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum Type_ {
Unit,
Single(SingleType),
Multiple(Vec<SingleType>),
}
pub type Type = Spanned<Type_>;
//**************************************************************************************************
// Expressions
//**************************************************************************************************
#[derive(Debug, PartialEq)]
pub enum Assign_ {
Var(Var),
Unpack(TypeName, Option<Vec<SingleType>>, Fields<Assign>),
}
pub type Assign = Spanned<Assign_>;
pub type AssignList = Spanned<Vec<Assign>>;
#[derive(Debug, PartialEq)]
pub enum Bind_ {
Var(Var),
Unpack(TypeName, Option<Vec<SingleType>>, Fields<Bind>),
}
pub type Bind = Spanned<Bind_>;
pub type BindList = Spanned<Vec<Bind>>;
#[derive(Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum ExpDotted_ {
Exp(Exp),
Dot(Box<ExpDotted>, Name),
}
pub type ExpDotted = Spanned<ExpDotted_>;
#[derive(Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum Exp_ {
Value(Value),
Move(Var),
Copy(Var),
Name(Name),
MName(Name),
ModuleIdent(ModuleIdent),
GlobalCall(Box<Exp>, Option<Vec<SingleType>>, Box<Exp>),
Call(Box<Exp>, Option<Vec<SingleType>>, Box<Exp>),
IfElse(Box<Exp>, Box<Exp>, Box<Exp>),
While(Box<Exp>, Box<Exp>),
Loop(Box<Exp>),
Block(Sequence),
Assign(AssignList, Box<Exp>),
Mutate(Box<ExpDotted>, Box<Exp>),
Return(Box<Exp>),
Abort(Box<Exp>),
Break,
Continue,
Dereference(Box<Exp>),
UnaryExp(UnaryOp, Box<Exp>),
BinopExp(Box<Exp>, BinOp, Box<Exp>),
Pack(TypeName, Option<Vec<SingleType>>, Fields<Exp>),
ExpList(Vec<Exp>),
Unit,
Borrow(bool, Box<Exp>),
ExpDotted(Box<ExpDotted>),
Annotate(Box<Exp>, Type),
UnresolvedError,
}
pub type Exp = Spanned<Exp_>;
pub type Sequence = VecDeque<SequenceItem>;
#[derive(Debug, PartialEq)]
pub enum SequenceItem_ {
Seq(Exp),
Declare(BindList, Option<Type>),
Bind(BindList, Exp),
}
pub type SequenceItem = Spanned<SequenceItem_>;
//**************************************************************************************************
// Display
//**************************************************************************************************
impl fmt::Display for TypeName_ {
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
use TypeName_::*;
match self {
Name(n) => write!(f, "{}", n),
ModuleType(m, n) => write!(f, "{}.{}", m, n),
}
}
}
impl fmt::Display for SingleType_ {
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
use SingleType_::*;
match self {
UnresolvedError => write!(f, "_"),
Apply(n, tys) => {
write!(f, "{}", n)?;
if !tys.is_empty() {
write!(f, "<")?;
write!(f, "{}", format_comma(tys))?;
write!(f, ">")?;
}
Ok(())
}
Ref(mut_, ty) => write!(f, "&{}{}", if *mut_ { "mut " } else { "" }, ty),
}
}
}
| 27.959276 | 100 | 0.482117 |
dd67740952f5b7382b7a5b41aa7fcf587eb2e2e7 | 281 | pub fn square_of_sum(n: usize) -> u64 {
u64::pow((1..).take(n).fold(0, |sum, i| sum + i), 2)
}
pub fn sum_of_squares(n: usize) -> u64 {
(1..).take(n).map(|x| x*x).fold(0, |sum, i| sum + i)
}
pub fn difference(n: usize) -> u64 {
square_of_sum(n) - sum_of_squares(n)
}
| 23.416667 | 56 | 0.565836 |
cc30b06e5ec38f1fd178a1fbed4f35079a0a2209 | 688 | use super::*;
mod pretty;
mod json;
mod terse;
pub(crate) use self::pretty::PrettyFormatter;
pub(crate) use self::json::JsonFormatter;
pub(crate) use self::terse::TerseFormatter;
pub(crate) trait OutputFormatter {
fn write_run_start(&mut self, test_count: usize) -> io::Result<()>;
fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()>;
fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()>;
fn write_result(
&mut self,
desc: &TestDesc,
result: &TestResult,
stdout: &[u8],
state: &ConsoleTestState,
) -> io::Result<()>;
fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool>;
}
| 28.666667 | 81 | 0.639535 |
c1e81f51b68d2876e68ca4d863a91f88c6be3c4e | 2,823 | #[doc = "Register `PACKAGE` reader"]
pub struct R(crate::R<PACKAGE_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<PACKAGE_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<PACKAGE_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<PACKAGE_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Package option\n\nValue on reset: 4294967295"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)]
pub enum PACKAGE_A {
#[doc = "8192: QFxx - 48-pin QFN"]
QF = 8192,
#[doc = "8195: QCxx - 32-pin QFN"]
QC = 8195,
#[doc = "4294967295: Unspecified"]
UNSPECIFIED = 4294967295,
}
impl From<PACKAGE_A> for u32 {
#[inline(always)]
fn from(variant: PACKAGE_A) -> Self {
variant as _
}
}
#[doc = "Field `PACKAGE` reader - Package option"]
pub struct PACKAGE_R(crate::FieldReader<u32, PACKAGE_A>);
impl PACKAGE_R {
#[inline(always)]
pub(crate) fn new(bits: u32) -> Self {
PACKAGE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<PACKAGE_A> {
match self.bits {
8192 => Some(PACKAGE_A::QF),
8195 => Some(PACKAGE_A::QC),
4294967295 => Some(PACKAGE_A::UNSPECIFIED),
_ => None,
}
}
#[doc = "Checks if the value of the field is `QF`"]
#[inline(always)]
pub fn is_qf(&self) -> bool {
**self == PACKAGE_A::QF
}
#[doc = "Checks if the value of the field is `QC`"]
#[inline(always)]
pub fn is_qc(&self) -> bool {
**self == PACKAGE_A::QC
}
#[doc = "Checks if the value of the field is `UNSPECIFIED`"]
#[inline(always)]
pub fn is_unspecified(&self) -> bool {
**self == PACKAGE_A::UNSPECIFIED
}
}
impl core::ops::Deref for PACKAGE_R {
type Target = crate::FieldReader<u32, PACKAGE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:31 - Package option"]
#[inline(always)]
pub fn package(&self) -> PACKAGE_R {
PACKAGE_R::new(self.bits)
}
}
#[doc = "Package option\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [package](index.html) module"]
pub struct PACKAGE_SPEC;
impl crate::RegisterSpec for PACKAGE_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [package::R](R) reader structure"]
impl crate::Readable for PACKAGE_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets PACKAGE to value 0xffff_ffff"]
impl crate::Resettable for PACKAGE_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0xffff_ffff
}
}
| 29.40625 | 224 | 0.597945 |
c175fca498f3a1e6acccc246ebd95e064d9cce27 | 2,457 | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::Ptptsar {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
}
#[doc = r" Value of the field"]
pub struct TsaR {
bits: u32,
}
impl TsaR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _TsaW<'a> {
w: &'a mut W,
}
impl<'a> _TsaW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, bits: u32) -> &'a mut W {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((bits & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:31 - no description available"]
#[inline(always)]
pub fn tsa(&self) -> TsaR {
let bits = {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u32
};
TsaR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:31 - no description available"]
#[inline(always)]
pub fn tsa(&mut self) -> _TsaW {
_TsaW { w: self }
}
}
| 24.326733 | 59 | 0.501832 |
f9cf285aa3462261d7074d1efedd0530b123d02c | 8,379 | #![deny(clippy::all, clippy::pedantic)]
#![feature(test)]
use std::{
convert::TryInto,
env,
fmt::{Display, Formatter},
fs::File,
io::{BufRead, BufReader},
};
extern crate test;
#[derive(Clone, Copy)]
enum Cell {
Floor,
Empty,
Occupied,
}
#[derive(Clone)]
struct Layout {
line_of_sight: bool,
map: Vec<Cell>,
column_count: i32,
row_count: i32,
adjacent_indices: Vec<u16>,
updated_indices: Vec<u16>,
occupied_seats: Vec<bool>,
}
impl Layout {
fn new(line_of_sight: bool) -> Self {
Self {
line_of_sight,
map: Vec::new(),
column_count: -1,
row_count: 0,
adjacent_indices: Vec::new(),
updated_indices: Vec::new(),
occupied_seats: Vec::new(),
}
}
fn add_line(&mut self, line: &str) {
for byte in line.as_bytes() {
self.map.push(match byte {
b'.' => Cell::Floor,
b'L' => Cell::Empty,
b'#' => Cell::Occupied,
_ => panic!("Unexpected byte [{}]", byte),
})
}
let incoming_column_count: i32 = line
.len()
.try_into()
.expect("Couldn't store column count in i32");
if self.column_count < 0 {
self.column_count = incoming_column_count;
} else if incoming_column_count != self.column_count {
panic!(
"Incoming column count {} different from stored column count {}",
incoming_column_count, self.column_count
);
}
self.row_count += 1;
}
fn get_index(&self, row: i32, column: i32) -> u16 {
(row * self.column_count + column)
.try_into()
.expect("Failed to store address in u16")
}
fn get_adjacent_seat_index(
&self,
mut row: i32,
mut column: i32,
delta_x: i32,
delta_y: i32,
) -> Option<u16> {
loop {
row += delta_y;
column += delta_x;
if row < 0 || row >= self.row_count {
return None;
}
if column < 0 || column >= self.column_count {
return None;
}
let index = self.get_index(row, column);
match self
.map
.get(index as usize)
.unwrap_or_else(|| panic!("Index {} not found in map", index))
{
Cell::Floor => (),
Cell::Empty | Cell::Occupied => return Some(index),
}
if !self.line_of_sight {
return None;
}
}
}
fn get_adjacent_indices(&self, row: i32, column: i32) -> Vec<u16> {
let mut indices = Vec::new();
for delta_y in -1..=1 {
for delta_x in -1..=1 {
if delta_x == 0 && delta_y == 0 {
continue;
}
if let Some(index) = self.get_adjacent_seat_index(row, column, delta_x, delta_y) {
indices.push(index);
}
}
}
indices
}
fn finalize(&mut self) {
for row in 0..self.row_count {
for column in 0..self.column_count {
let index = self.get_index(row, column);
if let Cell::Floor = self.map[index as usize] {
self.adjacent_indices.append(&mut vec![u16::max_value(); 8]);
continue;
}
let mut adjacent_indices = self.get_adjacent_indices(row, column);
adjacent_indices.resize(8, u16::max_value());
self.adjacent_indices.append(&mut adjacent_indices);
self.updated_indices.push(index);
}
}
self.occupied_seats
.resize(self.adjacent_indices.len() / 8, false);
}
fn count_adjacent_occupants(&self, index: u16) -> i32 {
let mut count = 0;
for adjacent_index in
&self.adjacent_indices[((index as usize) * 8)..((index as usize) * 8 + 8)]
{
if *adjacent_index == u16::max_value() {
break;
}
if self.occupied_seats[*adjacent_index as usize] {
count += 1;
}
}
count
}
fn collect_changes(&self) -> Vec<u16> {
let mut changes = Vec::new();
let abandonment_threshold = if self.line_of_sight { 5 } else { 4 };
for index in &self.updated_indices {
if self.occupied_seats[*index as usize] {
if self.count_adjacent_occupants(*index) >= abandonment_threshold {
changes.push(*index);
}
} else if self.count_adjacent_occupants(*index) == 0 {
changes.push(*index);
}
}
changes
}
fn apply_changes(&mut self, changes: Vec<u16>) {
for change in &changes {
self.occupied_seats[*change as usize] ^= true;
}
self.updated_indices = changes;
}
fn evolve(&mut self) -> bool {
let changes = self.collect_changes();
if changes.is_empty() {
return false;
}
self.apply_changes(changes);
true
}
fn count_occupants(&self) -> i32 {
self.occupied_seats
.iter()
.map(|occupied| if *occupied { 1 } else { 0 })
.sum()
}
}
impl Display for Layout {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for row in 0..self.row_count {
for column in 0..self.column_count {
let index = self.get_index(row, column);
write!(
f,
"{}",
match self
.map
.get(index as usize)
.unwrap_or_else(|| panic!("Index {} not found in map", index))
{
Cell::Floor => '.',
Cell::Empty => 'L',
Cell::Occupied => '#',
}
)?;
}
writeln!(f)?;
}
Ok(())
}
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 || args.len() > 3 {
return;
}
let line_of_sight = args.len() == 3 && args[2] == "los";
let filename = &args[1];
let file = File::open(filename).unwrap_or_else(|_| panic!("Failed to open file {}", filename));
let mut reader = BufReader::new(file);
let mut layout = Layout::new(line_of_sight);
let mut line = String::new();
loop {
let bytes = reader
.read_line(&mut line)
.unwrap_or_else(|_| panic!("Failed to read line"));
if bytes == 0 {
break;
}
layout.add_line(line.trim());
line.clear();
}
layout.finalize();
while layout.evolve() {}
println!("Occupied seats: {}", layout.count_occupants());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
fn get_layout(line_of_sight: bool) -> Layout {
let file = File::open("input.txt").expect("Failed to open input.txt");
let mut reader = BufReader::new(file);
let mut layout = Layout::new(line_of_sight);
let mut line = String::new();
loop {
let bytes = reader
.read_line(&mut line)
.unwrap_or_else(|_| panic!("Failed to read line"));
if bytes == 0 {
break;
}
layout.add_line(line.trim());
line.clear();
}
layout.finalize();
layout
}
#[bench]
fn bench_adjacent(bencher: &mut Bencher) {
let layout = get_layout(false);
bencher.iter(|| {
let mut cloned = layout.clone();
while cloned.evolve() {}
assert_eq!(cloned.count_occupants(), 2361);
});
}
#[bench]
fn bench_line_of_sight(bencher: &mut Bencher) {
let layout = get_layout(true);
bencher.iter(|| {
let mut cloned = layout.clone();
while cloned.evolve() {}
assert_eq!(cloned.count_occupants(), 2119);
});
}
}
| 26.6 | 99 | 0.480129 |
4aa3d97892c6c4713db17c9df82c285642e55b34 | 3,290 | // Creating mock runtime here
use crate as product_tracking;
use crate::*;
use core::marker::PhantomData;
use frame_support::{parameter_types, traits::EnsureOrigin};
use frame_system as system;
use frame_system::RawOrigin;
use sp_core::{sr25519, Pair, H256};
use sp_runtime::{
testing::{Header, TestXt},
traits::{BlakeTwo256, IdentityLookup},
};
pub use pallet_timestamp::Call as TimestampCall;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
// Configure a mock runtime to test the pallet.
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
System: system::{Pallet, Call, Config, Storage, Event<T>},
Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
ProductTracking: product_tracking::{Pallet, Call, Storage, Event<T>},
}
);
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const SS58Prefix: u8 = 42;
// pub const MinimumPeriod: u64 = 1;
}
impl system::Config for Test {
type BaseCallFilter = ();
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Call = Call;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = sr25519::Public;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = SS58Prefix;
type OnSetCode = ();
}
impl pallet_timestamp::Config for Test {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = ();
type WeightInfo = ();
}
impl product_tracking::Config for Test {
type CreateRoleOrigin = MockOrigin<Test>;
type Event = Event;
}
pub struct MockOrigin<T>(PhantomData<T>);
// pub type ProductTracking = Pallet<Test>;
// pub type Timestamp = pallet_timestamp::Pallet<Test>;
impl<T: Config> EnsureOrigin<T::Origin> for MockOrigin<T> {
type Success = T::AccountId;
fn try_origin(o: T::Origin) -> Result<Self::Success, T::Origin> {
o.into().and_then(|o| match o {
RawOrigin::Signed(ref who) => Ok(who.clone()),
r => Err(T::Origin::from(r)),
})
}
}
// This function basically just builds a genesis storage key/value store according to
// our desired mockup.
pub fn account_key(s: &str) -> sr25519::Public {
sr25519::Pair::from_string(&format!("//{}", s), None)
.expect("static values are valid; qed")
.public()
}
// Offchain worker
type TestExtrinsic = TestXt<Call, ()>;
impl<C> system::offchain::SendTransactionTypes<C> for Test
where
Call: From<C>,
{
type OverarchingCall = Call;
type Extrinsic = TestExtrinsic;
}
pub fn new_test_ext() -> sp_io::TestExternalities {
let t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
} | 26.967213 | 85 | 0.669909 |
f56c5c6908d407a6fd4f01ebd5ecbe8e0072e760 | 373 | use serde::Deserialize;
use serde::Serialize;
use std::fmt;
use thiserror::Error;
#[derive(Serialize, Deserialize, Debug, Error)]
pub struct MissingImplementationContent {
pub message: String,
}
impl fmt::Display for MissingImplementationContent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "error message: {}", self.message)
}
} | 24.866667 | 58 | 0.69437 |
0e0a854e76549c5b6450611f3196fcc7dc629909 | 2,944 | use ferros::cap::role;
use ferros::userland::{Consumer1, Producer};
use net_types::{IpcEthernetFrame, MtuSize};
use smoltcp::phy::{Checksum, Device, DeviceCapabilities, RxToken, TxToken};
use smoltcp::time::Instant;
use smoltcp::Error;
use typenum::Unsigned;
/// An interface for sending and receiving raw network frames
/// over ferros IPC
pub struct IpcPhyDevice {
pub consumer: Consumer1<role::Local, IpcEthernetFrame>,
pub producer: Producer<role::Local, IpcEthernetFrame>,
}
impl<'a> Device<'a> for IpcPhyDevice {
type RxToken = IpcPhyRxToken;
type TxToken = IpcPhyTxToken<'a>;
fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> {
if let Some(data) = self.consumer.poll() {
let rx = IpcPhyRxToken(data);
let tx = IpcPhyTxToken {
producer: &mut self.producer,
};
Some((rx, tx))
} else {
None
}
}
fn transmit(&'a mut self) -> Option<Self::TxToken> {
Some(IpcPhyTxToken {
producer: &mut self.producer,
})
}
fn capabilities(&self) -> DeviceCapabilities {
let mut caps = DeviceCapabilities::default();
// Our max MTU size
caps.max_transmission_unit = MtuSize::USIZE;
// Limit bursts to 1
caps.max_burst_size = Some(1);
// Verify checksum when receiving and compute checksum when sending
caps.checksum.ipv4 = Checksum::Both;
caps.checksum.udp = Checksum::Both;
caps.checksum.tcp = Checksum::Both;
caps.checksum.icmpv4 = Checksum::Both;
caps
}
}
pub struct IpcPhyRxToken(IpcEthernetFrame);
impl RxToken for IpcPhyRxToken {
fn consume<R, F>(mut self, timestamp: Instant, f: F) -> Result<R, Error>
where
F: FnOnce(&mut [u8]) -> Result<R, Error>,
{
log::trace!(
"[ipc-phy-dev] [{}] Receiving {} from L2 driver",
timestamp,
self.0
);
let result = f(self.0.as_mut_slice());
result
}
}
pub struct IpcPhyTxToken<'a> {
producer: &'a mut Producer<role::Local, IpcEthernetFrame>,
}
impl<'a> TxToken for IpcPhyTxToken<'a> {
fn consume<R, F>(self, timestamp: Instant, len: usize, f: F) -> Result<R, Error>
where
F: FnOnce(&mut [u8]) -> Result<R, Error>,
{
let mut data = IpcEthernetFrame::new();
data.truncate(len);
log::trace!(
"[ipc-phy-dev] [{}] Sending {} to L2 driver",
timestamp,
data,
);
let result = f(data.as_mut_slice());
if result.is_ok() && self.producer.send(data).is_err() {
// Drop the data if the queue is full
log::warn!(
"[ipc-phy-dev] [{}] Rejected sending IpcEthernetFrame data to L2 driver",
timestamp
);
return Err(Error::Exhausted);
}
result
}
}
| 27.773585 | 89 | 0.574728 |
796a1d3c30704990911a212933ad97de1968fdba | 4,032 | use crate::core::{LexPattern, LexTable};
use lazy_static;
use regex_engine::core::*;
use regex_engine::ext::*;
use regex_engine::reg;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::sync::Arc;
lazy_static! {
static ref DIGIT_REG: Arc<CharSetExpr> = {
let digit_set: HashSet<char> = HashSet::from_iter(
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
.iter()
.cloned(),
);
reg!(CharSetExpr, digit_set)
};
}
pub fn gen_digit_reg() -> Arc<CharSetExpr> {
DIGIT_REG.clone()
}
lazy_static! {
static ref LETTER_SET: Arc<CharSetExpr> = {
let mut letter_set = HashSet::new();
for i in ('a' as i32)..=('z' as i32) {
letter_set.insert(i as u8 as char);
}
for i in ('A' as i32)..=('Z' as i32) {
letter_set.insert(i as u8 as char);
}
letter_set.insert('_');
reg!(CharSetExpr, letter_set)
};
}
pub fn gen_letter_reg() -> Arc<CharSetExpr> {
LETTER_SET.clone()
}
lazy_static! {
static ref HEX_DIGIT_REG: Arc<AltExpr> = {
let mut letter_set = HashSet::new();
for i in ('a' as i32)..=('f' as i32) {
letter_set.insert(i as u8 as char);
}
for i in ('A' as i32)..=('F' as i32) {
letter_set.insert(i as u8 as char);
}
reg!(AltExpr, reg!(CharSetExpr, letter_set), DIGIT_REG.clone())
};
}
pub fn gen_hex_digit_reg() -> Arc<AltExpr> {
HEX_DIGIT_REG.clone()
}
pub fn gen_exp_reg(digit_reg: Arc<RegexExpr>) -> Arc<SeqExpr> {
reg!(
SeqExpr,
vec![
reg!(AltExpr, reg!(MatchExpr, 'E'), reg!(MatchExpr, 'e')),
reg!(
OptionalExpr,
reg!(AltExpr, reg!(MatchExpr, '+'), reg!(MatchExpr, '-'))
),
reg!(PlusExpr, digit_reg)
]
)
}
lazy_static! {
static ref FS_EXPR: Arc<CharSetExpr> = {
let fs_set: HashSet<char> = HashSet::from_iter(['f', 'F', 'l', 'L'].iter().cloned());
reg!(CharSetExpr, fs_set)
};
}
pub fn gen_fs_expr() -> Arc<CharSetExpr> {
FS_EXPR.clone()
}
lazy_static! {
static ref IS_EXPR: Arc<RepeatExpr> = {
let is_sub_set: HashSet<char> = HashSet::from_iter(['u', 'U', 'l', 'L'].iter().cloned());
reg!(RepeatExpr, reg!(CharSetExpr, is_sub_set))
};
}
pub fn gen_is_expr() -> Arc<RepeatExpr> {
IS_EXPR.clone()
}
pub fn gen_hex_const_expr(hex_digit_expr: Arc<RegexExpr>, is_expr: Arc<RegexExpr>) -> Arc<SeqExpr> {
reg!(
SeqExpr,
vec![
reg!(MatchExpr, '0'),
reg!(AltExpr, reg!(MatchExpr, 'x'), reg!(MatchExpr, 'X')),
reg!(PlusExpr, hex_digit_expr),
reg!(OptionalExpr, is_expr)
]
)
}
pub fn gen_oct_const_expr(digit_expr: Arc<RegexExpr>, is_expr: Arc<RegexExpr>) -> Arc<SeqExpr> {
reg!(
SeqExpr,
vec![
reg!(MatchExpr, '0'),
reg!(PlusExpr, digit_expr),
reg!(OptionalExpr, is_expr)
]
)
}
lazy_static! {
static ref SPACE_PATTERN_EXPR: Arc<CharSetExpr> = {
reg!(
CharSetExpr,
HashSet::from_iter(['\t', '\n', '\r', ' '].iter().cloned())
)
};
}
pub struct SpacePattern {
expr: Arc<CharSetExpr>,
min_len: usize,
max_len: usize,
}
impl SpacePattern {
pub fn new() -> SpacePattern {
SpacePattern {
min_len: 1,
max_len: 1,
expr: SPACE_PATTERN_EXPR.clone(),
}
}
}
impl LexPattern for SpacePattern {
fn get_boundary(&self) -> (usize, usize) {
(self.min_len, self.max_len)
}
fn hook(&self, table: &LexTable, target: &str) -> usize {
table.get(target).0
}
fn register(&self, table: &mut LexTable) {
for kw in &self.expr.set {
table.try_insert(&kw.to_string(), "SPACE");
}
}
fn is_match(&self, target: &str) -> bool {
reg_match(self.expr.clone(), target)
}
}
| 24.736196 | 100 | 0.537946 |
fb40a35c00374edc3fe23b05d3a42d9efa3673eb | 3,671 | //! A TLS validator network function will identify the TLS handshake messages and extract the
//! certificates. The NF will run a configurable TLS version and enforce the validation of the
//! certs. The exact implementation is in `nf.rs`.
#![feature(box_syntax)]
#![feature(asm)]
extern crate e2d2;
extern crate fnv;
extern crate rustls;
extern crate time;
extern crate tlsv;
extern crate webpki;
extern crate webpki_roots;
use e2d2::config::*;
use e2d2::interface::*;
use e2d2::operators::*;
use e2d2::scheduler::*;
use std::env;
use std::fmt::Display;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use tlsv::validator;
const CONVERSION_FACTOR: f64 = 1_000_000_000.;
/// Test for the validator network function to schedule pipelines.
fn validator_test<T, S>(ports: Vec<T>, sched: &mut S)
where
T: PacketRx + PacketTx + Display + Clone + 'static,
S: Scheduler + Sized,
{
// create a pipeline for each port
let pipelines: Vec<_> = ports
.iter()
.map(|port| validator(ReceiveBatch::new(port.clone()), sched).send(port.clone()))
.collect();
println!("Running {} pipelines", pipelines.len());
// schedule pipelines
for pipeline in pipelines {
sched.add_task(pipeline).unwrap();
}
}
/// default main
fn main() {
// setup default parameters
let opts = basic_opts();
let args: Vec<String> = env::args().collect();
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!("{}", f.to_string()),
};
let configuration = read_matches(&matches, &opts);
// configure and start the schedulers
let mut config = initialize_system(&configuration).unwrap();
let duration = configuration.duration;
config.start_schedulers();
config.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| validator_test(p, s)));
config.execute();
let mut pkts_so_far = (0, 0);
let mut last_printed = 0.;
const MAX_PRINT_INTERVAL: f64 = 30.;
//const PRINT_DELAY: f64 = 15.;
const PRINT_DELAY: f64 = 30.;
let sleep_delay = (PRINT_DELAY / 2.) as u64;
let mut start = time::precise_time_ns() as f64 / CONVERSION_FACTOR;
let sleep_time = Duration::from_millis(sleep_delay);
println!("0 OVERALL RX 0.00 TX 0.00 CYCLE_PER_DELAY 0 0 0");
let begining = Instant::now();
loop {
thread::sleep(sleep_time); // Sleep for a bit
let now = time::precise_time_ns() as f64 / CONVERSION_FACTOR;
if now - start > PRINT_DELAY {
let mut rx = 0;
let mut tx = 0;
for port in config.ports.values() {
for q in 0..port.rxqs() {
let (rp, tp) = port.stats(q);
rx += rp;
tx += tp;
}
}
let pkts = (rx, tx);
let rx_pkts = pkts.0 - pkts_so_far.0;
if rx_pkts > 0 || now - last_printed > MAX_PRINT_INTERVAL {
println!(
"{:.2} OVERALL RX {:.2} TX {:.2}",
now - start,
rx_pkts as f64 / (now - start),
(pkts.1 - pkts_so_far.1) as f64 / (now - start)
);
last_printed = now;
start = now;
pkts_so_far = pkts;
}
}
if let Some(d) = duration {
let new_now = Instant::now();
if new_now.duration_since(begining) > Duration::new(d as u64, 0) {
println!("Have run for {:?}, system shutting down", d);
config.shutdown();
break;
}
}
}
}
| 32.486726 | 101 | 0.573141 |
9b51e20c3859aa2affa2cf0f1f2730f6bc1afbbb | 12,281 | use crate::azure::core::errors::{check_status_extract_headers_and_body, AzureError};
use crate::azure::core::headers::LEASE_ACTION;
use crate::azure::core::lease::LeaseId;
use crate::azure::core::{
BlobNameRequired, BlobNameSupport, ClientRequestIdOption, ClientRequestIdSupport, ClientRequired, ContainerNameRequired,
ContainerNameSupport, LeaseIdRequired, LeaseIdSupport, ProposedLeaseIdRequired, ProposedLeaseIdSupport, TimeoutOption, TimeoutSupport,
};
use crate::azure::core::{No, ToAssign, Yes};
use crate::azure::storage::blob::generate_blob_uri;
use crate::azure::storage::blob::responses::ChangeBlobLeaseResponse;
use crate::azure::storage::client::Client;
use futures::future::{done, Future};
use hyper::{Method, StatusCode};
use std::marker::PhantomData;
#[derive(Debug, Clone)]
pub struct ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
client: &'a Client,
p_container_name: PhantomData<ContainerNameSet>,
p_blob_name: PhantomData<BlobNameSet>,
p_lease_id: PhantomData<LeaseIdSet>,
p_proposed_lease_id: PhantomData<ProposedLeaseIdSet>,
container_name: Option<&'a str>,
blob_name: Option<&'a str>,
lease_id: Option<&'a LeaseId>,
proposed_lease_id: Option<&'a LeaseId>,
timeout: Option<u64>,
client_request_id: Option<&'a str>,
}
impl<'a> ChangeBlobLeaseBuilder<'a, No, No, No, No> {
#[inline]
pub(crate) fn new(client: &'a Client) -> ChangeBlobLeaseBuilder<'a, No, No, No, No> {
ChangeBlobLeaseBuilder {
client,
p_container_name: PhantomData {},
container_name: None,
p_blob_name: PhantomData {},
blob_name: None,
p_lease_id: PhantomData {},
lease_id: None,
p_proposed_lease_id: PhantomData {},
proposed_lease_id: None,
timeout: None,
client_request_id: None,
}
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> ClientRequired<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
#[inline]
fn client(&self) -> &'a Client {
self.client
}
}
impl<'a, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> ContainerNameRequired<'a>
for ChangeBlobLeaseBuilder<'a, Yes, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
#[inline]
fn container_name(&self) -> &'a str {
self.container_name.unwrap()
}
}
impl<'a, ContainerNameSet, LeaseIdSet, ProposedLeaseIdSet> BlobNameRequired<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, Yes, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
#[inline]
fn blob_name(&self) -> &'a str {
self.blob_name.unwrap()
}
}
impl<'a, ContainerNameSet, BlobNameSet, ProposedLeaseIdSet> LeaseIdRequired<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, Yes, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
#[inline]
fn lease_id(&self) -> &'a LeaseId {
self.lease_id.unwrap()
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet> ProposedLeaseIdRequired<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, Yes>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
{
#[inline]
fn proposed_lease_id(&self) -> &'a LeaseId {
self.proposed_lease_id.unwrap()
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> TimeoutOption
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
#[inline]
fn timeout(&self) -> Option<u64> {
self.timeout
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> ClientRequestIdOption<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
#[inline]
fn client_request_id(&self) -> Option<&'a str> {
self.client_request_id
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> ContainerNameSupport<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
type O = ChangeBlobLeaseBuilder<'a, Yes, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>;
#[inline]
fn with_container_name(self, container_name: &'a str) -> Self::O {
ChangeBlobLeaseBuilder {
client: self.client,
p_container_name: PhantomData {},
p_blob_name: PhantomData {},
p_lease_id: PhantomData {},
p_proposed_lease_id: PhantomData {},
container_name: Some(container_name),
blob_name: self.blob_name,
lease_id: self.lease_id,
proposed_lease_id: self.proposed_lease_id,
timeout: self.timeout,
client_request_id: self.client_request_id,
}
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> BlobNameSupport<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
type O = ChangeBlobLeaseBuilder<'a, ContainerNameSet, Yes, LeaseIdSet, ProposedLeaseIdSet>;
#[inline]
fn with_blob_name(self, blob_name: &'a str) -> Self::O {
ChangeBlobLeaseBuilder {
client: self.client,
p_container_name: PhantomData {},
p_blob_name: PhantomData {},
p_lease_id: PhantomData {},
p_proposed_lease_id: PhantomData {},
container_name: self.container_name,
blob_name: Some(blob_name),
lease_id: self.lease_id,
proposed_lease_id: self.proposed_lease_id,
timeout: self.timeout,
client_request_id: self.client_request_id,
}
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> LeaseIdSupport<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
type O = ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, Yes, ProposedLeaseIdSet>;
#[inline]
fn with_lease_id(self, lease_id: &'a LeaseId) -> Self::O {
ChangeBlobLeaseBuilder {
client: self.client,
p_container_name: PhantomData {},
p_blob_name: PhantomData {},
p_lease_id: PhantomData {},
p_proposed_lease_id: PhantomData {},
container_name: self.container_name,
blob_name: self.blob_name,
lease_id: Some(lease_id),
proposed_lease_id: self.proposed_lease_id,
timeout: self.timeout,
client_request_id: self.client_request_id,
}
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> ProposedLeaseIdSupport<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
type O = ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, Yes>;
#[inline]
fn with_proposed_lease_id(self, proposed_lease_id: &'a LeaseId) -> Self::O {
ChangeBlobLeaseBuilder {
client: self.client,
p_container_name: PhantomData {},
p_blob_name: PhantomData {},
p_lease_id: PhantomData {},
p_proposed_lease_id: PhantomData {},
container_name: self.container_name,
blob_name: self.blob_name,
lease_id: self.lease_id,
proposed_lease_id: Some(proposed_lease_id),
timeout: self.timeout,
client_request_id: self.client_request_id,
}
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> TimeoutSupport
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
type O = ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>;
#[inline]
fn with_timeout(self, timeout: u64) -> Self::O {
ChangeBlobLeaseBuilder {
client: self.client,
p_container_name: PhantomData {},
p_blob_name: PhantomData {},
p_lease_id: PhantomData {},
p_proposed_lease_id: PhantomData {},
container_name: self.container_name,
blob_name: self.blob_name,
lease_id: self.lease_id,
proposed_lease_id: self.proposed_lease_id,
timeout: Some(timeout),
client_request_id: self.client_request_id,
}
}
}
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet> ClientRequestIdSupport<'a>
for ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
type O = ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>;
#[inline]
fn with_client_request_id(self, client_request_id: &'a str) -> Self::O {
ChangeBlobLeaseBuilder {
client: self.client,
p_container_name: PhantomData {},
p_blob_name: PhantomData {},
p_lease_id: PhantomData {},
p_proposed_lease_id: PhantomData {},
container_name: self.container_name,
blob_name: self.blob_name,
lease_id: self.lease_id,
proposed_lease_id: self.proposed_lease_id,
timeout: self.timeout,
client_request_id: Some(client_request_id),
}
}
}
// methods callable regardless
impl<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
ChangeBlobLeaseBuilder<'a, ContainerNameSet, BlobNameSet, LeaseIdSet, ProposedLeaseIdSet>
where
ContainerNameSet: ToAssign,
BlobNameSet: ToAssign,
LeaseIdSet: ToAssign,
ProposedLeaseIdSet: ToAssign,
{
}
impl<'a> ChangeBlobLeaseBuilder<'a, Yes, Yes, Yes, Yes> {
pub fn finalize(self) -> impl Future<Item = ChangeBlobLeaseResponse, Error = AzureError> {
let mut uri = generate_blob_uri(&self, Some("comp=lease"));
if let Some(nm) = TimeoutOption::to_uri_parameter(&self) {
uri = format!("{}&{}", uri, nm);
}
let req = self.client().perform_request(
&uri,
&Method::PUT,
|ref mut request| {
LeaseIdRequired::add_header(&self, request);
request.header(LEASE_ACTION, "change");
ProposedLeaseIdRequired::add_header(&self, request);
ClientRequestIdOption::add_header(&self, request);
},
None,
);
done(req)
.from_err()
.and_then(move |future_response| check_status_extract_headers_and_body(future_response, StatusCode::OK))
.and_then(|(headers, _body)| done(ChangeBlobLeaseResponse::from_headers(&headers)))
}
}
| 34.594366 | 138 | 0.676981 |
90d18e5728f576cba17473aedef386c6df3558be | 3,436 | use std::str;
use std::sync::Arc;
use hyper::rt::{Future, Stream};
use hyper::{Body, Method, Request, Response, Uri};
use crate::error::RouterError;
use crate::request_forwarder::{ComponentRequest, RequestForwarder};
// Warning: This method is somewhat complicated, since it needs to deal with async stuff
// TODO: Consider making this a method on a struct somewhere
// TODO: Deal with panics bubbling up to this level
pub fn global_request_entrypoint(
handler: Arc<HttpRequestHandler>,
req: Request<Body>,
) -> impl Future<Item = Response<Body>, Error = hyper::error::Error> + Send {
debug!("{:?}", req);
// Pull the verb, uri, and query stuff out of the request
// (It's okay to do this, since it's all quite quick to execute)
let http_verb = req.method().clone();
let uri = req.uri().clone();
let query = uri.query().unwrap_or("").to_string();
// Then get a future representing the body (this is a future, since hyper may not of received the whole body yet)
let body_future = req.into_body().concat2().map(|c| {
// Convert the Chunk into a rust "String", wrapping any error in our error type
str::from_utf8(&c).map(str::to_owned).map_err(RouterError::from)
});
// Next we want to an operation on the body. This needs to happen in a future for two reasons
// 1) We want to handle many requests at once, so we don't want to block a thread
// 2) Hyper literally doesn't let you deal with the body unless you're inside a future context (there is no API to escape this)
// Note: We already have a result (body_result) here, since we might get an Utf8 decode error above
body_future.map(move |body_result| {
debug!("body = {:?}", body_result);
let resp: Response<Body> = body_result
// Delegate to the handler to actually deal with this request
.and_then(|body| handler.handle(http_verb, &uri, query, body))
.unwrap_or_else(|e| {
warn!("Forced to convert error {:?} into a http response", e);
e.into()
});
if resp.status() == 532 {
error!("INTERNAL ROUTER ERROR -- {:?}", resp);
} else {
debug!("{:?}", resp);
}
resp
})
}
#[derive(Debug)]
pub struct HttpRequestHandler {
// Contents of this handler need to be thread-safe
request_forwarder: RequestForwarder,
}
impl HttpRequestHandler {
pub fn new() -> Self {
Self {
request_forwarder: RequestForwarder::new(),
}
}
fn handle(
&self,
http_verb: Method,
uri: &Uri,
query: String,
body: String,
) -> Result<Response<Body>, RouterError> {
// Get the uri path, and then split it around slashes into components
// Note: All URIs start with a slash, so we skip the first entry in the split (which is always just "")
let path_components: Vec<&str> = uri.path().split('/').skip(1).collect();
if path_components.len() < 4 {
return Err(RouterError::PathNotFound(path_components.join("/")));
}
let user = path_components[1].to_string();
let repo = path_components[2].to_string();
let method = path_components[3].to_string();
let request = ComponentRequest::new(http_verb, query, body, user, repo, method);
Ok(self.request_forwarder.forward_request(request)?)
}
}
| 37.758242 | 131 | 0.62922 |
7a9d92dbeb027ac3c86eb2ea3963d8cccaa0bb33 | 5,548 | use bytes::Bytes;
use generated_types::influxdata::platform::storage::{
CapabilitiesResponse, OffsetsResponse, ReadFilterRequest, ReadGroupRequest, ReadResponse,
ReadWindowAggregateRequest, StringValuesResponse, TagKeysRequest, TagValuesRequest,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy)]
pub enum MethodType {
Request,
Response,
}
/// All the GRPC methods this code knows how to decode to native form
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum Method {
/// `/influxdata.platform.storage.Storage/Offsets`
/// No special decoding (yet)
StorageOffsetsRequest(Bytes),
StorageOffsetsResponse(OffsetsResponse),
/// `/influxdata.platform.storage.Storage/TagKeys`
TagKeysRequest(TagKeysRequest),
/// /influxdata.platform.storage.Storage/TagValues
TagValuesRequest(TagValuesRequest),
/// Request: `/influxdata.platform.storage.Storage/Capabilities`
CapabilitiesRequest(),
/// Response: `/influxdata.platform.storage.Storage/Capabilities`
CapabilitiesResponse(CapabilitiesResponse),
/// Request `/influxdata.platform.storage.Storage/ReadFilter`
ReadFilterRequest(ReadFilterRequest),
/// Request `/influxdata.platform.storage.Storage/ReadGroup`
ReadGroupRequest(ReadGroupRequest),
/// Request `/influxdata.platform.storage.Storage/ReadWindowAggregate`
ReadWindowAggregateRequest(ReadWindowAggregateRequest),
/// Response for:
/// `/influxdata.platform.storage.Storage/ReadWindowAggregate`
ReadResponse(ReadResponse),
/// Response for:
/// * `/influxdata.platform.storage.Storage/TagKeys`
/// * `/influxdata.platform.storage.Storage/TagValues`
StringValuesResponse(StringValuesResponse),
/// a gRPC Method we don't (yet) know how to decode
Unknown {
/// The name of the gRPC method
method_name: String,
/// The raw data that went in
bytes: Bytes,
},
}
impl Method {
pub fn new(method_name: impl Into<String>, data: Vec<u8>, method_type: MethodType) -> Self {
use prost::Message;
use MethodType::*;
let method_name = method_name.into();
let bytes: Bytes = data.into();
match (method_name.as_str(), method_type) {
("/influxdata.platform.storage.Storage/Offsets", Request) => {
Self::StorageOffsetsRequest(bytes)
}
("/influxdata.platform.storage.Storage/Offsets", Response) => {
let msg = OffsetsResponse::decode(bytes).expect("Error decoding OffsetsResponse");
Self::StorageOffsetsResponse(msg)
}
("/influxdata.platform.storage.Storage/Capabilities", Request) => {
assert!(
bytes.is_empty(),
"Unexpected request payload for storage/capabilities"
);
Self::CapabilitiesRequest()
}
("/influxdata.platform.storage.Storage/Capabilities", Response) => {
let msg = CapabilitiesResponse::decode(bytes)
.expect("Error decoding CapabilitiesResponse");
Self::CapabilitiesResponse(msg)
}
("/influxdata.platform.storage.Storage/TagKeys", Request) => {
let msg = TagKeysRequest::decode(bytes).expect("Error decoding TagKeysRequest");
Self::TagKeysRequest(msg)
}
("/influxdata.platform.storage.Storage/TagValues", Request) => {
let msg = TagValuesRequest::decode(bytes).expect("Error decoding TagValuesRequest");
Self::TagValuesRequest(msg)
}
("/influxdata.platform.storage.Storage/TagKeys", Response)
| ("/influxdata.platform.storage.Storage/TagValues", Response) => {
let msg = StringValuesResponse::decode(bytes)
.expect("Error decoding StringValuesResponse");
Self::StringValuesResponse(msg)
}
("/influxdata.platform.storage.Storage/ReadWindowAggregate", Request) => {
let msg = ReadWindowAggregateRequest::decode(bytes)
.expect("Error decoding ReadWindowAggregateRequest");
Self::ReadWindowAggregateRequest(msg)
}
("/influxdata.platform.storage.Storage/ReadFilter", Request) => {
let msg = ReadFilterRequest::decode(bytes)
.expect("Error decoding ReadWindowAggregateRequest");
Self::ReadFilterRequest(msg)
}
("/influxdata.platform.storage.Storage/ReadGroup", Request) => {
let msg = ReadGroupRequest::decode(bytes)
.expect("Error decoding ReadWindowAggregateRequest");
Self::ReadGroupRequest(msg)
}
("/influxdata.platform.storage.Storage/ReadFilter", Response)
| ("/influxdata.platform.storage.Storage/ReadGroup", Response)
| ("/influxdata.platform.storage.Storage/ReadWindowAggregate", Response) => {
let msg = ReadResponse::decode(bytes).expect("Error decoding ReadResponse");
Self::ReadResponse(msg)
}
_ => {
// fallback to unknown
println!(
"Unknown how to decode {} from {} bytes",
method_name,
bytes.len()
);
Self::Unknown { method_name, bytes }
}
}
}
}
| 41.096296 | 100 | 0.613374 |
50ecd76cfd001d268a8ba7b8d910e199c8b68923 | 4,784 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use crate::worker::{FunctionType, Worker, WorkerContext};
use mesatee_core::{Error, ErrorKind, Result};
use ring::aead::{self, Aad, BoundKey, Nonce, UnboundKey};
use serde_derive::Deserialize;
use serde_json;
use std::prelude::v1::*;
// INPUT from file-id
#[derive(Deserialize)]
struct AEADKeyConfig {
pub key: Vec<u8>,
pub nonce: Vec<u8>,
pub ad: Vec<u8>,
}
// INPUT: encrypted bytes encoded with base64
// OUTPUT: decypted bytes encoded with base64
pub struct OnlineDecryptWorker {
worker_id: u32,
func_name: String,
func_type: FunctionType,
input: Option<OnlineDecryptWorkerInput>,
}
struct OnlineDecryptWorkerInput {
pub encrypted_bytes: Vec<u8>,
pub aead_file_id: String,
}
impl OnlineDecryptWorker {
pub fn new() -> Self {
OnlineDecryptWorker {
worker_id: 0,
func_name: "decrypt".to_string(),
func_type: FunctionType::Single,
input: None,
}
}
}
impl Worker for OnlineDecryptWorker {
fn function_name(&self) -> &str {
self.func_name.as_str()
}
fn function_type(&self) -> FunctionType {
self.func_type
}
fn set_id(&mut self, worker_id: u32) {
self.worker_id = worker_id;
}
fn id(&self) -> u32 {
self.worker_id
}
fn prepare_input(
&mut self,
dynamic_input: Option<String>,
file_ids: Vec<String>,
) -> Result<()> {
let aead_file_id = match file_ids.get(0) {
Some(value) => value.to_string(),
None => return Err(Error::from(ErrorKind::InvalidInputError)),
};
let encrypted_base64 = match dynamic_input {
Some(value) => value,
None => return Err(Error::from(ErrorKind::InvalidInputError)),
};
let encrypted_bytes: Vec<u8> = base64::decode(&encrypted_base64)
.map_err(|_| Error::from(ErrorKind::InvalidInputError))?;
self.input = Some(OnlineDecryptWorkerInput {
encrypted_bytes,
aead_file_id,
});
Ok(())
}
fn execute(&mut self, context: WorkerContext) -> Result<String> {
let input = self
.input
.take()
.ok_or_else(|| Error::from(ErrorKind::InvalidInputError))?;
let key_bytes = context.read_file(&input.aead_file_id)?;
let key_config: AEADKeyConfig = serde_json::from_slice(&key_bytes)
.map_err(|_| Error::from(ErrorKind::InvalidInputError))?;
let decrypted_bytes = decrypt_data(
input.encrypted_bytes,
&key_config.key,
&key_config.nonce,
&key_config.ad,
)?;
let output_base64 = base64::encode(&decrypted_bytes);
Ok(output_base64)
}
}
struct OneNonceSequence(Option<aead::Nonce>);
impl OneNonceSequence {
/// Constructs the sequence allowing `advance()` to be called
/// `allowed_invocations` times.
fn new(nonce: aead::Nonce) -> Self {
Self(Some(nonce))
}
}
impl aead::NonceSequence for OneNonceSequence {
fn advance(&mut self) -> core::result::Result<aead::Nonce, ring::error::Unspecified> {
self.0.take().ok_or(ring::error::Unspecified)
}
}
fn decrypt_data(
mut data: Vec<u8>,
aes_key: &[u8],
aes_nonce: &[u8],
aes_ad: &[u8],
) -> Result<Vec<u8>> {
let aead_alg = &aead::AES_256_GCM;
let ub = UnboundKey::new(aead_alg, aes_key).map_err(|_| Error::from(ErrorKind::CryptoError))?;
let nonce = Nonce::try_assume_unique_for_key(aes_nonce)
.map_err(|_| mesatee_core::Error::from(mesatee_core::ErrorKind::CryptoError))?;
let filesequence = OneNonceSequence::new(nonce);
let mut o_key = aead::OpeningKey::new(ub, filesequence);
let ad = Aad::from(aes_ad);
let result = o_key.open_in_place(ad, &mut data[..]);
let decrypted_buffer =
result.map_err(|_| mesatee_core::Error::from(mesatee_core::ErrorKind::CryptoError))?;
Ok(decrypted_buffer.to_vec())
}
| 32.544218 | 98 | 0.645485 |
5bf47655f2dde96df1dcbf6ff69011440ccdc51f | 35,888 | //! Support for J-Link Debug probes
use jaylink::{CommunicationSpeed, Interface, JayLink};
use thiserror::Error;
use std::convert::{TryFrom, TryInto};
use std::iter;
use std::sync::Mutex;
use crate::{
architecture::arm::dp::Ctrl,
architecture::arm::{DapError, PortType, Register},
probe::{
DAPAccess, DebugProbe, DebugProbeError, DebugProbeInfo, DebugProbeType, JTAGAccess,
WireProtocol,
},
DebugProbeSelector,
};
#[derive(Debug)]
pub(crate) struct JLink {
handle: Mutex<JayLink>,
/// Idle cycles necessary between consecutive
/// accesses to the DMI register
jtag_idle_cycles: u8,
/// Currently selected protocol
protocol: Option<WireProtocol>,
/// Protocols supported by the connected J-Link probe.
supported_protocols: Vec<WireProtocol>,
current_ir_reg: u32,
speed_khz: u32,
}
impl JLink {
fn idle_cycles(&self) -> u8 {
self.jtag_idle_cycles
}
fn select_interface(
&mut self,
protocol: Option<WireProtocol>,
) -> Result<WireProtocol, DebugProbeError> {
let handle = self.handle.get_mut().unwrap();
let capabilities = handle.read_capabilities()?;
if capabilities.contains(jaylink::Capabilities::SELECT_IF) {
if let Some(protocol) = protocol {
let jlink_interface = match protocol {
WireProtocol::Swd => jaylink::Interface::Swd,
WireProtocol::Jtag => jaylink::Interface::Jtag,
};
if handle
.read_available_interfaces()?
.any(|interface| interface == jlink_interface)
{
// We can select the desired interface
handle.select_interface(jlink_interface)?;
Ok(protocol)
} else {
Err(DebugProbeError::UnsupportedProtocol(protocol))
}
} else {
// No special protocol request
let current_protocol = handle.read_current_interface()?;
match current_protocol {
jaylink::Interface::Swd => Ok(WireProtocol::Swd),
jaylink::Interface::Jtag => Ok(WireProtocol::Jtag),
x => unimplemented!("J-Link: Protocol {} is not yet supported.", x),
}
}
} else {
// Assume JTAG protocol if the probe does not support switching interfaces
match protocol {
Some(WireProtocol::Jtag) => Ok(WireProtocol::Jtag),
Some(p) => Err(DebugProbeError::UnsupportedProtocol(p)),
None => Ok(WireProtocol::Jtag),
}
}
}
fn read_dr(&mut self, register_bits: usize) -> Result<Vec<u8>, DebugProbeError> {
log::debug!("Read {} bits from DR", register_bits);
let tms_enter_shift = [true, false, false];
// Last bit of data is shifted out when we exi the SHIFT-DR State
let tms_shift_out_value = iter::repeat(false).take(register_bits - 1);
let tms_enter_idle = [true, true, false];
let mut tms = Vec::with_capacity(register_bits + 7);
tms.extend_from_slice(&tms_enter_shift);
tms.extend(tms_shift_out_value);
tms.extend_from_slice(&tms_enter_idle);
let tdi = iter::repeat(false).take(tms.len() + self.idle_cycles() as usize);
// We have to stay in the idle cycle a bit
tms.extend(iter::repeat(false).take(self.idle_cycles() as usize));
let jlink = self.handle.get_mut().unwrap();
let mut response = jlink.jtag_io(tms, tdi)?;
log::trace!("Response: {:?}", response);
let _remainder = response.split_off(tms_enter_shift.len());
let mut remaining_bits = register_bits;
let mut result = Vec::new();
while remaining_bits >= 8 {
let byte = bits_to_byte(response.split_off(8)) as u8;
result.push(byte);
remaining_bits -= 8;
}
// Handle leftover bytes
if remaining_bits > 0 {
result.push(bits_to_byte(response.split_off(remaining_bits)) as u8);
}
log::debug!("Read from DR: {:?}", result);
Ok(result)
}
/// Write IR register with the specified data. The
/// IR register might have an odd length, so the dta
/// will be truncated to `len` bits. If data has less
/// than `len` bits, an error will be returned.
fn write_ir(&mut self, data: &[u8], len: usize) -> Result<(), DebugProbeError> {
log::debug!("Write IR: {:?}, len={}", data, len);
// Check the bit length, enough data has to be
// available
if data.len() * 8 < len {
todo!("Proper error for incorrect length");
}
// At least one bit has to be sent
if len < 1 {
todo!("Proper error for incorrect length");
}
let tms_enter_ir_shift = [true, true, false, false];
// The last bit will be transmitted when exiting the shift state,
// so we need to stay in the shift stay for one period less than
// we have bits to transmit
let tms_data = iter::repeat(false).take(len - 1);
let tms_enter_idle = [true, true, false];
let mut tms = Vec::with_capacity(tms_enter_ir_shift.len() + len + tms_enter_ir_shift.len());
tms.extend_from_slice(&tms_enter_ir_shift);
tms.extend(tms_data);
tms.extend_from_slice(&tms_enter_idle);
let tdi_enter_ir_shift = [false, false, false, false];
// This is one less than the enter idle for tms, because
// the last bit is transmitted when exiting the IR shift state
let tdi_enter_idle = [false, false];
let mut tdi = Vec::with_capacity(tdi_enter_ir_shift.len() + tdi_enter_idle.len() + len);
tdi.extend_from_slice(&tdi_enter_ir_shift);
let num_bytes = len / 8;
let num_bits = len - (num_bytes * 8);
for bytes in &data[..num_bytes] {
let mut byte = *bytes;
for _ in 0..8 {
tdi.push(byte & 1 == 1);
byte >>= 1;
}
}
if num_bits > 0 {
let mut remaining_byte = data[num_bytes];
for _ in 0..num_bits {
tdi.push(remaining_byte & 1 == 1);
remaining_byte >>= 1;
}
}
tdi.extend_from_slice(&tdi_enter_idle);
log::trace!("tms: {:?}", tms);
log::trace!("tdi: {:?}", tdi);
let jlink = self.handle.get_mut().unwrap();
let response = jlink.jtag_io(tms, tdi)?;
log::trace!("Response: {:?}", response);
assert!(
len < 8,
"Not yet implemented for IR registers larger than 8 bit"
);
self.current_ir_reg = data[0] as u32;
// Maybe we could return the previous state of the IR register here...
Ok(())
}
fn write_dr(&mut self, data: &[u8], register_bits: usize) -> Result<Vec<u8>, DebugProbeError> {
log::debug!("Write DR: {:?}, len={}", data, register_bits);
let tms_enter_shift = [true, false, false];
// Last bit of data is shifted out when we exi the SHIFT-DR State
let tms_shift_out_value = iter::repeat(false).take(register_bits - 1);
let tms_enter_idle = [true, true, false];
let mut tms = Vec::with_capacity(register_bits + 7);
tms.extend_from_slice(&tms_enter_shift);
tms.extend(tms_shift_out_value);
tms.extend_from_slice(&tms_enter_idle);
let tdi_enter_shift = [false, false, false];
let tdi_enter_idle = [false, false];
// TODO: TDI data
let mut tdi =
Vec::with_capacity(tdi_enter_shift.len() + tdi_enter_idle.len() + register_bits);
tdi.extend_from_slice(&tdi_enter_shift);
let num_bytes = register_bits / 8;
let num_bits = register_bits - (num_bytes * 8);
for bytes in &data[..num_bytes] {
let mut byte = *bytes;
for _ in 0..8 {
tdi.push(byte & 1 == 1);
byte >>= 1;
}
}
if num_bits > 0 {
let mut remaining_byte = data[num_bytes];
for _ in 0..num_bits {
tdi.push(remaining_byte & 1 == 1);
remaining_byte >>= 1;
}
}
tdi.extend_from_slice(&tdi_enter_idle);
// We need to stay in the idle cycle a bit
tms.extend(iter::repeat(false).take(self.idle_cycles() as usize));
tdi.extend(iter::repeat(false).take(self.idle_cycles() as usize));
let jlink = self.handle.get_mut().unwrap();
let mut response = jlink.jtag_io(tms, tdi)?;
log::trace!("Response: {:?}", response);
let _remainder = response.split_off(tms_enter_shift.len());
let mut remaining_bits = register_bits;
let mut result = Vec::new();
while remaining_bits >= 8 {
let byte = bits_to_byte(response.split_off(8)) as u8;
result.push(byte);
remaining_bits -= 8;
}
// Handle leftover bytes
if remaining_bits > 0 {
result.push(bits_to_byte(response.split_off(remaining_bits)) as u8);
}
log::trace!("result: {:?}", result);
Ok(result)
}
}
impl DebugProbe for JLink {
fn new_from_selector(
selector: impl Into<DebugProbeSelector>,
) -> Result<Box<Self>, DebugProbeError> {
let selector = selector.into();
let mut jlinks = jaylink::scan_usb()?
.filter_map(|usb_info| {
if usb_info.vid() == selector.vendor_id && usb_info.pid() == selector.product_id {
let device = usb_info.open();
if let Some(serial_number) = selector.serial_number.as_deref() {
if device
.as_ref()
.map(|d| d.serial_string() == serial_number)
.unwrap_or(false)
{
Some(device)
} else {
None
}
} else {
Some(device)
}
} else {
None
}
})
.collect::<Vec<_>>();
if jlinks.len() == 0 {
return Err(DebugProbeError::ProbeCouldNotBeCreated(
super::ProbeCreationError::NotFound,
));
} else if jlinks.len() > 1 {
log::warn!("More than one matching J-Link was found. Opening the first one.")
}
let jlink_handle = jlinks.pop().unwrap()?;
// Check which protocols are supported by the J-Link.
//
// If the J-Link has the SELECT_IF capability, we can just ask
// it which interfaces it supports. If it doesn't have the capabilty,
// we assume that it justs support JTAG. In that case, we will also
// not be able to change protocols.
let supported_protocols: Vec<WireProtocol> = if jlink_handle
.read_capabilities()?
.contains(jaylink::Capabilities::SELECT_IF)
{
let interfaces = jlink_handle.read_available_interfaces()?;
let protocols: Vec<_> = interfaces.map(WireProtocol::try_from).collect();
protocols
.iter()
.filter(|p| p.is_err())
.for_each(|protocol| {
if let Err(JlinkError::UnknownInterface(interface)) = protocol {
log::warn!(
"J-Link returned interface {:?}, which is not supported by probe-rs.",
interface
);
}
});
// We ignore unknown protocols, the chance that this happens is pretty low,
// and we can just work with the ones we know and support.
protocols.into_iter().filter_map(Result::ok).collect()
} else {
// The J-Link cannot report which interfaces it supports, and cannot
// switch interfaces. We assume it just supports JTAG.
vec![WireProtocol::Jtag]
};
Ok(Box::new(JLink {
handle: Mutex::from(jlink_handle),
supported_protocols: supported_protocols,
jtag_idle_cycles: 0,
protocol: None,
current_ir_reg: 1,
speed_khz: 0,
}))
}
fn select_protocol(&mut self, protocol: WireProtocol) -> Result<(), DebugProbeError> {
// try to select the interface
let actual_protocol = self.select_interface(Some(protocol))?;
if actual_protocol == protocol {
self.protocol = Some(protocol);
Ok(())
} else {
self.protocol = Some(actual_protocol);
Err(DebugProbeError::UnsupportedProtocol(protocol))
}
}
fn get_name(&self) -> &'static str {
"J-Link"
}
fn speed(&self) -> u32 {
self.speed_khz
}
fn set_speed(&mut self, speed_khz: u32) -> Result<u32, DebugProbeError> {
if speed_khz == 0 || speed_khz >= 0xffff {
return Err(DebugProbeError::UnsupportedSpeed(speed_khz));
}
let jlink = self.handle.get_mut().unwrap();
let actual_speed_khz;
if let Ok(speeds) = jlink.read_speeds() {
log::debug!("Supported speeds: {:?}", speeds);
let speed_hz = 1000 * speed_khz;
let div = (speeds.base_freq() + speed_hz - 1) / speed_hz;
log::debug!("Divider: {}", div);
let div = std::cmp::max(div, speeds.min_div() as u32);
actual_speed_khz = ((speeds.base_freq() / div) + 999) / 1000;
assert!(actual_speed_khz <= speed_khz);
} else {
actual_speed_khz = speed_khz;
}
jlink.set_speed(CommunicationSpeed::khz(actual_speed_khz as u16).unwrap())?;
self.speed_khz = actual_speed_khz;
Ok(actual_speed_khz)
}
fn attach(&mut self) -> Result<(), super::DebugProbeError> {
log::debug!("Attaching to J-Link");
let configured_protocol = match self.protocol {
Some(protocol) => protocol,
None => {
if self.supported_protocols.contains(&WireProtocol::Swd) {
WireProtocol::Swd
} else {
// At least one protocol is always supported
*self.supported_protocols.first().unwrap()
}
}
};
let actual_protocol = self.select_interface(Some(configured_protocol))?;
if actual_protocol != configured_protocol {
log::warn!("Protocol {} is configured, but not supported by the probe. Using protocol {} instead", configured_protocol, actual_protocol);
}
log::debug!("Attaching with protocol '{}'", actual_protocol);
// Get reference to JayLink instance
let jlink: &mut JayLink = self.handle.get_mut().unwrap();
let capabilities = jlink.read_capabilities()?;
// Log some information about the probe
let serial = jlink.serial_string().trim_start_matches('0');
log::info!("J-Link: S/N: {}", serial);
log::debug!("J-Link: Capabilities: {:?}", capabilities);
let fw_version = jlink.read_firmware_version().unwrap_or_else(|_| "?".into());
log::info!("J-Link: Firmware version: {}", fw_version);
match jlink.read_hardware_version() {
Ok(hw_version) => log::info!("J-Link: Hardware version: {}", hw_version),
Err(_) => log::info!("J-Link: Hardware version: ?"),
};
// Verify target voltage (VTref pin, mV). If this is 0, the device is not powered.
let target_voltage = jlink.read_target_voltage()?;
if target_voltage == 0 {
log::warn!("J-Link: Target voltage (VTref) is 0 V. Is your target device powered?");
} else {
log::info!(
"J-Link: Target voltage: {:2.2} V",
target_voltage as f32 / 1000f32
);
}
match actual_protocol {
WireProtocol::Jtag => {
// try some JTAG stuff
log::debug!("Resetting JTAG chain using trst");
jlink.reset_trst()?;
log::debug!("Resetting JTAG chain by setting tms high for 32 bits");
// Reset JTAG chain (5 times TMS high), and enter idle state afterwards
let tms = vec![true, true, true, true, true, false];
let tdi = iter::repeat(false).take(6);
let response: Vec<_> = jlink.jtag_io(tms, tdi)?.collect();
log::debug!("Response to reset: {:?}", response);
// try to read the idcode
let idcode_bytes = self.read_dr(32)?;
let idcode = u32::from_le_bytes((&idcode_bytes[..]).try_into().unwrap());
log::debug!("IDCODE: {:#010x}", idcode);
}
WireProtocol::Swd => {
// Construct the JTAG to SWD sequence.
let jtag_to_swd_sequence = [
false, true, true, true, true, false, false, true, true, true, true, false,
false, true, true, true,
];
// Construct the entire init sequence.
let swd_io_sequence =
// Send the reset sequence (> 50 0-bits).
iter::repeat(true).take(64)
// Send the JTAG to SWD sequence.
.chain(jtag_to_swd_sequence.iter().copied())
// Send the reset sequence again in case we were in SWD mode already (> 50 0-bits).
.chain(iter::repeat(true).take(64))
// Send 10 idle line bits.
.chain(iter::repeat(false).take(10));
// Construct the direction sequence for reset sequence.
let direction =
// Send the reset sequence (> 50 0-bits).
iter::repeat(true).take(64)
// Send the JTAG to SWD sequence.
.chain(iter::repeat(true).take(16))
// Send the reset sequence again in case we were in SWD mode already (> 50 0-bits).
.chain(iter::repeat(true).take(64))
// Send 10 idle line bits.
.chain(iter::repeat(true).take(10));
// Send the init sequence.
// We don't actually care about the response here.
// A read on the DPIDR will finalize the init procedure and tell us if it worked.
jlink.swd_io(direction, swd_io_sequence)?;
log::debug!("Sucessfully switched to SWD");
// We are ready to debug.
}
}
log::debug!("Attached succesfully");
Ok(())
}
fn detach(&mut self) -> Result<(), super::DebugProbeError> {
unimplemented!()
}
fn target_reset(&mut self) -> Result<(), super::DebugProbeError> {
Err(super::DebugProbeError::NotImplemented("target_reset"))
}
fn dedicated_memory_interface(&self) -> Option<crate::Memory> {
None
}
fn get_interface_dap(&self) -> Option<&dyn DAPAccess> {
// For now, we only support using SWD for ARM chips, but
// JTAG would be possible as well.
if self.supported_protocols.contains(&WireProtocol::Swd) {
Some(self as _)
} else {
None
}
}
fn get_interface_dap_mut(&mut self) -> Option<&mut dyn DAPAccess> {
// For now, we only support using SWD for ARM chips, but
// JTAG would be possible as well.
if self.supported_protocols.contains(&WireProtocol::Swd) {
Some(self as _)
} else {
None
}
}
fn get_interface_jtag(&self) -> Option<&dyn JTAGAccess> {
if self.supported_protocols.contains(&WireProtocol::Jtag) {
Some(self as _)
} else {
None
}
}
fn get_interface_jtag_mut(&mut self) -> Option<&mut dyn JTAGAccess> {
if self.supported_protocols.contains(&WireProtocol::Jtag) {
Some(self as _)
} else {
None
}
}
}
impl JTAGAccess for JLink {
/// Read the data register
fn read_register(&mut self, address: u32, len: u32) -> Result<Vec<u8>, DebugProbeError> {
let address_bits = address.to_le_bytes();
// TODO: This is limited to 5 bit addresses for now
assert!(
address <= 0x1f,
"JTAG Register addresses are fixed to 5 bits"
);
if self.current_ir_reg != address {
// Write IR register
self.write_ir(&address_bits[..1], 5)?;
}
// read DR register
self.read_dr(len as usize)
}
/// Write the data register
fn write_register(
&mut self,
address: u32,
data: &[u8],
len: u32,
) -> Result<Vec<u8>, DebugProbeError> {
let address_bits = address.to_le_bytes();
// TODO: This is limited to 5 bit addresses for now
assert!(
address <= 0x1f,
"JTAG Register addresses are fixed to 5 bits"
);
if self.current_ir_reg != address {
// Write IR register
self.write_ir(&address_bits[..1], 5)?;
}
// write DR register
self.write_dr(data, len as usize)
}
fn set_idle_cycles(&mut self, idle_cycles: u8) {
self.jtag_idle_cycles = idle_cycles;
}
}
impl DAPAccess for JLink {
fn read_register(&mut self, port: PortType, address: u16) -> Result<u32, DebugProbeError> {
// JLink operates on raw SWD bit sequences.
// So we need to manually assemble the read and write bitsequences.
// The following code with the comments hopefully explains well enough how it works.
// `true` means `1` and `false` means `0` for the SWDIO sequence.
// `true` means `drive line` and `false` means `open drain` for the direction sequence.
// First we determine the APnDP bit.
let port = match port {
PortType::DebugPort => false,
PortType::AccessPort(_) => true,
};
// Then we determine the address bits.
// Only bits 2 and 3 are relevant as we use byte addressing but can only read 32bits
// which means we can skip bits 0 and 1. The ADI specification is defined like this.
let a2 = (address >> 2) & 0x01 == 1;
let a3 = (address >> 3) & 0x01 == 1;
// Now we assemble an SWD read request.
let mut swd_io_sequence = vec![
// First we make sure we have the SDWIO line on idle for at least 2 clock cylces.
false, // Line idle.
false, // Line idle.
// Then we assemble the actual request.
true, // Start bit (always 1).
port, // APnDP (0 for DP, 1 for AP).
true, // RnW (0 for Write, 1 for Read).
a2, // Address bit 2.
a3, // Address bit 3,
port ^ true ^ a2 ^ a3, // Odd parity bit over APnDP, RnW a2 and a3
false, // Stop bit (always 0).
true, // Park bit (always 1).
// Theoretically the spec says that there is a turnaround bit required here, where no clock is driven.
// This seems to not be the case in actual implementations. So we do not insert this bit either!
// false, // Turnaround bit.
false, // ACK bit.
false, // ACK bit.
false, // ACK bit.
];
// Add the data bits to the SWDIO sequence.
for _ in 0..32 {
swd_io_sequence.push(false);
}
// Add the parity bit to the sequence.
swd_io_sequence.push(false);
// Finally add the turnaround bit to the sequence.
swd_io_sequence.push(false);
// Assemble the direction sequence.
let direction = iter::repeat(true)
.take(2) // Transmit 2 Line idle bits.
.chain(iter::repeat(true).take(8)) // Transmit 8 Request bits
// Here *should* be a Trn bit, but since something with the spec is akward we leave it away.
// See comments above!
.chain(iter::repeat(false).take(3)) // Receive 3 Ack bits.
.chain(iter::repeat(false).take(32)) // Receive 32 Data bits.
.chain(iter::repeat(false).take(1)) // Receive 1 Parity bit.
.chain(iter::repeat(false).take(1)); // Receive 1 Turnaround bit.
// Now we try to issue the request until it fails or succeeds.
// If we timeout we retry a maximum of 5 times.
let mut retries = 0;
while retries < 5 {
// Transmit the sequence and record the line sequence for the ack bits.
let mut result_sequence = self
.handle
.get_mut()
.unwrap()
.swd_io(direction.clone(), swd_io_sequence.iter().copied())?;
// Throw away the two idle bits.
result_sequence.split_off(2);
// Throw away the request bits.
result_sequence.split_off(8);
// Get the ack.
let ack = result_sequence.split_off(3).collect::<Vec<_>>();
if ack[1] {
// If ack[1] is set the host must retry the request. So let's do that right away!
retries += 1;
log::debug!("DAP line busy, retries remaining {}.", 5 - retries);
continue;
}
if ack[2] {
// A fault happened during operation.
// To get a clue about the actual fault we read the ctrl register,
// which will have the fault status flags set.
let response =
DAPAccess::read_register(self, PortType::DebugPort, Ctrl::ADDRESS as u16)?;
let ctrl = Ctrl::from(response);
log::error!(
"Reading DAP register failed. Ctrl/Stat register value is: {:#?}",
ctrl
);
return Err(DapError::FaultResponse.into());
}
// If we are reading an AP register we only get the actual result in the next transaction.
// So we issue a special transaction to get the read value.
if port {
// We read the RDBUFF register to get the value of the last AP transaction.
// This special register just returns the last read value with no side-effects like auto-increment.
return DAPAccess::read_register(self, PortType::DebugPort, 0x0C);
} else {
// Take the data bits and convert them into a 32bit int.
let register_val = result_sequence.split_off(32);
let value = bits_to_byte(register_val);
// Make sure the parity is correct.
return if let Some(parity) = result_sequence.next() {
if (value.count_ones() % 2 == 1) == parity {
log::trace!("DAP read {}.", value);
Ok(value)
} else {
log::error!("DAP read fault.");
Err(DebugProbeError::Unknown)
}
} else {
log::error!("DAP read fault.");
Err(DebugProbeError::Unknown)
};
// Don't care about the Trn bit at the end.
}
}
// If we land here, the DAP operation timed out.
log::error!("DAP read timeout.");
Err(DebugProbeError::Timeout)
}
fn write_register(
&mut self,
port: PortType,
address: u16,
mut value: u32,
) -> Result<(), DebugProbeError> {
// JLink operates on raw SWD bit sequences.
// So we need to manually assemble the read and write bitsequences.
// The following code with the comments hopefully explains well enough how it works.
// `true` means `1` and `false` means `0` for the SWDIO sequence.
// `true` means `drive line` and `false` means `open drain` for the direction sequence.
// First we determine the APnDP bit.
let port = match port {
PortType::DebugPort => false,
PortType::AccessPort(_) => true,
};
// Then we determine the address bits.
// Only bits 2 and 3 are relevant as we use byte addressing but can only read 32bits
// which means we can skip bits 0 and 1. The ADI specification is defined like this.
let a2 = (address >> 2) & 0x01 == 1;
let a3 = (address >> 3) & 0x01 == 1;
// Now we assemble an SWD write request.
let mut swd_io_sequence = vec![
false, // Line idle.
false, // Line idle.
// Then we assemble the actual request.
true, // Start bit (always 1).
port, // APnDP (0 for DP, 1 for AP).
false, // RnW (0 for Write, 1 for Read).
a2, // Address bit 2.
a3, // Address bit 3,
port ^ false ^ a2 ^ a3, // Odd parity bit over ApnDP, RnW a2 and a3
false, // Stop bit (always 0).
true, // Park bit (always 1).
// Theoretically the spec says that there is a turnaround bit required here, where no clock is driven.
// This seems to not be the case in actual implementations. So we do not insert this bit either!
// false, // Turnaround bit.
false, // ACK bit.
false, // ACK bit.
false, // ACK bit.
// Theoretically the spec says that there is only one turnaround bit required here, where no clock is driven.
// This seems to not be the case in actual implementations. So we insert two turnaround bits here!
false, // Turnaround bit.
false, // Turnaround bit.
];
// Now we add all the data bits to the sequence and in the same loop we also calculate the parity bit.
let mut parity = false;
for _ in 0..32 {
let bit = value & 1 == 1;
swd_io_sequence.push(bit);
parity ^= bit;
value >>= 1;
}
// Then we add the parity bit just after the previously added data bits.
swd_io_sequence.push(parity);
// Assemble the direction sequence.
let direction = iter::repeat(true)
.take(2) // Transmit 2 Line idle bits.
.chain(iter::repeat(true).take(8)) // Transmit 8 Request bits
// Here *should* be a Trn bit, but since something with the spec is akward we leave it away.
// See comments above!
.chain(iter::repeat(false).take(3)) // Receive 3 Ack bits.
.chain(iter::repeat(false).take(2)) // Transmit 2 Turnaround bits.
.chain(iter::repeat(true).take(32)) // Transmit 32 Data bits.
.chain(iter::repeat(true).take(1)); // Transmit 1 Parity bit.
// Now we try to issue the request until it fails or succeeds.
// If we timeout we retry a maximum of 5 times.
let mut retries = 0;
while retries < 5 {
// Transmit the sequence and record the line sequence for the ack and data bits.
let mut result_sequence = self
.handle
.get_mut()
.unwrap()
.swd_io(direction.clone(), swd_io_sequence.iter().copied())?;
// Throw away the two idle bits.
result_sequence.split_off(2);
// Throw away the request bits.
result_sequence.split_off(8);
// Get the ack.
let ack = result_sequence.by_ref().take(3).collect::<Vec<_>>();
if ack[1] {
// If ack[1] is set the host must retry the request. So let's do that right away!
retries += 1;
log::debug!("DAP line busy, retries remaining {}.", 5 - retries);
continue;
}
if ack[2] {
// A fault happened during operation.
// To get a clue about the actual fault we read the ctrl register,
// which will have the fault status flags set.
let response =
DAPAccess::read_register(self, PortType::DebugPort, Ctrl::ADDRESS as u16)?;
let ctrl = Ctrl::from(response);
log::error!(
"Writing DAP register failed. Ctrl/Stat register value is: {:#?}",
ctrl
);
return Err(DebugProbeError::Unknown);
}
// Since this is a write request, we don't care about the part after the ack bits.
// So we just discard the Trn + Data + Parity bits.
log::trace!("DAP wrote {}.", value);
return Ok(());
}
// If we land here, the DAP operation timed out.
log::error!("DAP write timeout.");
Err(DebugProbeError::Timeout)
}
}
fn bits_to_byte(bits: impl IntoIterator<Item = bool>) -> u32 {
let mut bit_val = 0u32;
for (index, bit) in bits.into_iter().take(32).enumerate() {
if bit {
bit_val |= 1 << index;
}
}
bit_val
}
pub(crate) fn list_jlink_devices() -> Result<impl Iterator<Item = DebugProbeInfo>, DebugProbeError>
{
Ok(jaylink::scan_usb()?.map(|device_info| {
let vid = device_info.vid();
let pid = device_info.pid();
let (serial, product) = if let Ok(device) = device_info.open() {
let serial = device.serial_string();
let serial = if serial.is_empty() {
None
} else {
Some(serial.to_owned())
};
let product = device.product_string();
let product = if product.is_empty() {
None
} else {
Some(product.to_owned())
};
(serial, product)
} else {
(None, None)
};
DebugProbeInfo::new(
format!(
"J-Link{}",
product
.map(|p| format!(" ({})", p))
.unwrap_or("".to_string())
),
vid,
pid,
serial,
DebugProbeType::JLink,
)
}))
}
impl From<jaylink::Error> for DebugProbeError {
fn from(e: jaylink::Error) -> DebugProbeError {
DebugProbeError::ProbeSpecific(Box::new(e))
}
}
#[derive(Debug, Error)]
pub enum JlinkError {
#[error("Unknown interface reported by J-Link: {0:?}")]
UnknownInterface(jaylink::Interface),
}
impl TryFrom<jaylink::Interface> for WireProtocol {
type Error = JlinkError;
fn try_from(interface: Interface) -> Result<Self, Self::Error> {
match interface {
Interface::Jtag => Ok(WireProtocol::Jtag),
Interface::Swd => Ok(WireProtocol::Swd),
unknown_interface => Err(JlinkError::UnknownInterface(unknown_interface)),
}
}
}
| 36.287159 | 149 | 0.53745 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.